A hint: This file contains one or more very long lines, so maybe it is better readable using the pure text view mode that shows the contents as wrapped lines within the browser window.
Previous versions of PMD can be downloaded here: https://github.com/pmd/pmd/releases
The PMD team is pleased to announce PMD 6.46.0.
This is a minor release.
The PMD CLI now allows repeating the --dir
(-d
) and --rulesets
(-R
) options,
as well as providing several space-separated arguments to either of
them. For instance:
pmd -d src/main/java src/test/java -R rset1.xml -R rset2.xml
This also allows globs to be used on the CLI if your shell supports shell expansion. For instance, the above can be written
pmd -d src/*/java -R rset*.xml
Please use theses new forms instead of using comma-separated lists as argument to these options.
When executing CPD on C# sources, the option
--ignore-annotations
is now supported as well. It ignores
C# attributes when detecting duplicated code. This option can also be
enabled via the CPD GUI. See #3974 for details.
This release ships with 2 new Java rules.
EmptyControlStatement
reports many instances of empty things, e.g. control statements whose
body is empty, as well as empty initializers.
EmptyControlStatement also works for empty for
and
do
loops, while there were previously no corresponding
rules.
This new rule replaces the rules EmptyFinallyBlock, EmptyIfStmt, EmptyInitializer, EmptyStatementBlock, EmptySwitchStatements, EmptySynchronizedBlock, EmptyTryBlock, and EmptyWhileStmt.
rule ref="category/java/codestyle.xml/EmptyControlStatement"/> <
The rule is part of the quickstart.xml ruleset.
UnnecessarySemicolon
reports semicolons that are unnecessary (so called “empty statements”
and “empty declarations”).
This new rule replaces the rule EmptyStatementNotInLoop.
rule ref="category/java/codestyle.xml/UnnecessarySemicolon"/> <
The rule is part of the quickstart.xml ruleset.
EmptyControlStatement
merges their functionality:
EmptyStatementNotInLoop
is deprecated and removed from the quickstart ruleset. Use the new rule
UnnecessarySemicolon
instead.Ruleset references with the following formats are now deprecated and
will produce a warning when used on the CLI or in a ruleset XML file: -
<lang-name>-<ruleset-name>
, eg
java-basic
, which resolves to
rulesets/java/basic.xml
- the internal release number, eg
600
, which resolves to
rulesets/releases/600.xml
Use the explicit forms of these references to be compatible with PMD 7.
toString
is now deprecated. The format of this method will remain the same until
PMD 7. The deprecation is intended to steer users away from relying on
this format, as it may be changed in PMD 7.getInputPaths
and
setInputPaths
are now deprecated. A new set of methods have been added, which use
lists and do not rely on comma splitting.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.
CPDCommandLineInterface
has been internalized. In order to execute CPD either
CPD#run
or
CPD#main
should be used.BaseCPDCLITest
have been deprecated with replacements.Formatter#start
,
Formatter#end
,
Formatter#getRenderer
,
and
Formatter#isNoOutputSupplied
have been internalized.The PMD team is pleased to announce PMD 6.45.0.
This is a minor release.
Help shape the future of PMD by telling us how you use it.
Our little survey is still open in case you didn’t participate yet. Please participate in our survey at https://forms.gle/4d8r1a1RDzfixHDc7.
Thank you!
This version of PMD ships a new language module to support analyzing of HTML. Support for HTML is experimental and might change without notice. The language implementation is not complete yet and the AST doesn’t look well for text nodes and comment nodes and might be changed in the future. You can write your own rules, but we don’t guarantee that the rules work with the next (minor) version of PMD without adjustments.
Please give us feedback about how practical this new language is in discussions. Please report missing features or bugs as new issues.
AvoidInlineStyles
finds elements which use a style attribute. In order to help maintaining
a webpage it is considered good practice to separate content and styles.
Instead of inline styles one should use CSS files and classes.rule ref="category/html/bestpractices.xml/AvoidInlineStyles" /> <
UnnecessaryTypeAttribute
finds “link” and “script” elements which still have a “type” attribute.
This is not necessary anymore since modern browsers automatically use
CSS and JavaScript.rule ref="category/html/bestpractices.xml/UnnecessaryTypeAttribute" /> <
UseAltAttributeForImages
finds “img” elements without an “alt” attribute. An alternate text
should always be provided in order to help screen readers.rule ref="category/html/bestpractices.xml/UseAltAttributeForImages" /> <
UnusedPrivateField
has a new property ignoredFieldNames
. The default ignores
serialization-specific fields (eg serialVersionUID
). The
property can be used to ignore more fields based on their name. Note
that the rule used to ignore fields named IDENT
, but
doesn’t anymore (add this value to the property to restore the old
behaviour).Report#filterViolations
creates a new report with some violations removed with a given predicate
based filter.Report#union
can combine two reports into a single new Report.net.sourceforge.pmd.util.Predicate
will be replaced in PMD7 with the standard Predicate interface from
java8.pmd-html
is entirely experimental right now.
Anything in the package net.sourceforge.pmd.lang.html
should be used cautiously.The PMD team is pleased to announce PMD 6.44.0.
This is a minor release.
Help shape the future of PMD by telling us how you use it.
Please participate in our survey at https://forms.gle/4d8r1a1RDzfixHDc7.
Thank you!
This release of PMD brings support for Java 18. There are no new standard language features.
PMD also supports JEP
420: Pattern Matching for switch (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
18-preview
:
export PMD_JAVA_OPTS=--enable-preview
./run.sh pmd -language java -version 18-preview ...
Note: Support for Java 16 preview language features have been removed. The version “16-preview” is no longer available.
The new rule class
DomXPathRule
is intended to replace usage of the XPathRule
for XML
rules. This rule executes the XPath query in a different way, which
sticks to the XPath specification. This means the expression is
interpreted the same way in PMD as in all other XPath development tools
that stick to the standard. You can for instance test the expression in
an online XPath editor.
Prefer using this class to define XPath rules: replace the value of
the class
attribute with
net.sourceforge.pmd.lang.xml.rule.DomXPathRule
like so:
rule name="MyXPathRule"
< language="xml"
message="A message"
class="net.sourceforge.pmd.lang.xml.rule.DomXPathRule">
properties>
<property name="xpath">
<value><![CDATA[
<
/a/b/c[@attr = "5"]]]></value>
property>
</<!-- Note: the property "version" is ignored, remove it. The query is XPath 2. -->
properties>
</rule> </
The rule is more powerful than XPathRule
, as it can now
handle XML namespaces, comments and processing instructions. Please
refer to the Javadoc of
DomXPathRule
for information about the differences with XPathRule
and
examples.
XPathRule
is still perfectly supported for all other
languages, including Apex and Java.
The new XPath functions pmd:startLine
,
pmd:endLine
, pmd:startColumn
, and
pmd:endColumn
are now available in XPath rules for all
languages. They replace the node attributes @BeginLine
,
@EndLine
and such. These attributes will be deprecated in a
future release.
Please refer to the documentation of these functions for more information, including usage samples.
Note that the function pmd:endColumn
returns an
exclusive index, while the attribute @EndColumn
is
inclusive. This is for forward compatibility with PMD 7, which uses
exclusive end indices.
This release introduces a new programmatic API to replace the
inflexible
PMD
class. Programmatic execution of PMD should now be done with a
PMDConfiguration
and a
PmdAnalysis
,
for instance:
= new PMDConfiguration();
PMDConfiguration config .setDefaultLanguageVersion(LanguageRegistry.findLanguageByTerseName("java").getVersion("11"));
config.setInputPaths("src/main/java");
config.prependAuxClasspath("target/classes");
config.setMinimumPriority(RulePriority.HIGH);
config.addRuleSet("rulesets/java/quickstart.xml");
config.setReportFormat("xml");
config.setReportFile("target/pmd-report.xml");
config
try (PmdAnalysis pmd = PmdAnalysis.create(config)) {
// note: don't use `config` once a PmdAnalysis has been created.
// optional: add more rulesets
.addRuleSet(pmd.newRuleSetLoader().loadFromResource("custom-ruleset.xml"));
pmd// optional: add more files
.files().addFile(Paths.get("src", "main", "more-java", "ExtraSource.java"));
pmd// optional: add more renderers
.addRenderer(renderer);
pmd
// or just call PMD
.performAnalysis();
pmd}
The PMD
class still supports methods related to CLI
execution: runPmd
and main
. All other members
are now deprecated for removal. The CLI itself remains compatible, if
you run PMD via command-line, no action is required on your part.
Several members of
PMD
have been newly deprecated, including:
PMD#EOL
: use System#lineSeparator()
PMD#SUPPRESS_MARKER
: use
DEFAULT_SUPPRESS_MARKER
PMD#processFiles
: use the new programmatic APIPMD#getApplicableFiles
: is internalPMDConfiguration#prependClasspath
is deprecated in favour of
prependAuxClasspath
.
PMDConfiguration#setRuleSets
and
getRuleSets
are deprecated. Use instead
setRuleSets
,
addRuleSet
,
and
getRuleSetPaths
.
Several members of
BaseCLITest
have been deprecated with replacements.
Several members of
PMDCommandLineInterface
have been explicitly deprecated. The whole class however was deprecated
long ago already with 6.30.0. It is internal API and should not be
used.
In modelica, the rule classes
AmbiguousResolutionRule
and
ConnectUsingNonConnector
have been deprecated, since they didn’t comply to the usual rule class
naming conventions yet. The replacements are in the subpackage
bestpractices
.
Together with the new
programmatic API the interface
TextFile
has been added as experimental. It intends to replace
DataSource
and
SourceCode
in the long term.
This interface will change in PMD 7 to support read/write operations
and other things. You don’t need to use it in PMD 6, as
FileCollector
decouples you from this. A file collector is available through
PmdAnalysis#files
.
The PMD team is pleased to announce PMD 6.43.0.
This is a minor release.
!= null
as positive
conditionSome API deprecations were performed in core PMD classes, to improve
compatibility with PMD 7. -
Report
:
the constructor and other construction methods like addViolation or
createReport -
RuleContext
:
all constructors, getters and setters. A new set of stable methods,
matching those in PMD 7, was added to replace the
addViolation
overloads of
AbstractRule
.
In PMD 7, RuleContext
will be the API to report violations,
and it can already be used as such in PMD 6. - The field
configuration
is unused and will be removed.
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.
RuleSet
:
methods that serve to apply rules, including apply
,
start
, end
,
removeDysfunctionalRules
AbstractAccumulatingRenderer#renderFileReport
is internal API and should not be overridden in own renderers.It is now forbidden to report a violation: - With a null
node - With a null
message - With a null
set
of format arguments (prefer a zero-length array)
Note that the message is set from the XML rule declaration, so this is only relevant if you instantiate rules manually.
RuleContext
now requires setting the current rule before calling
apply
.
This is done automatically by RuleSet#apply
and such.
Creating and configuring a RuleContext
manually is strongly
advised against, as the lifecycle of RuleContext
will
change drastically in PMD 7.
The PMD team is pleased to announce PMD 6.42.0.
This is a minor release.
Rhino, the implementation of JavaScript we use for parsing JavaScript code, has been updated to the latest version 1.7.14. Now language features like template strings can be parsed. However Rhino does not support all features of the latest EcmaScript standard.
FinalParameterInAbstractMethod
detects parameters that are declared as final in interfaces or abstract
methods. Declaring the parameters as final is useless because the
implementation may choose to not respect it.rule ref="category/java/codestyle.xml/FinalParameterInAbstractMethod" /> <
The rule is part of the quickstart.xml ruleset.
ApexDoc
has a new property reportProperty
. If set to
false
(default is true
if unspecified) doesn’t
report missing ApexDoc comments on properties. It allows you to enforce
ApexDoc comments for classes and methods without requiring them for
properties.No changes.
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łoThe 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.UnusedImports
:
use the rule UnnecessaryImport
insteadDuplicateImports
:
use the rule UnnecessaryImport
insteadDontImportJavaLang
:
use the rule UnnecessaryImport
insteadImportFromSamePackage
:
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.The PMD team is pleased to announce PMD 6.31.0.
This is a minor release.
PMD now supports the Static
Analysis Results Interchange Format (SARIF) as an additional report
format. Just use the command line parameter
-format sarif
to select it. SARIF is an OASIS standard
format for static analysis tools. PMD creates SARIF JSON files in SARIF
version 2.1.0. An example report can be found in the documentation
in Report formats for
PMD.
--ignore-literal-sequences
,
which can be used to avoid detection of some uninteresting clones. This
options has been introduced with PMD 6.30.0 for C# and is now available
for C++ as well. See #2963.The new Apex rule OverrideBothEqualsAndHashcode
brings the well known Java rule to Apex. In Apex the same principle
applies: equals
and hashCode
should always be
overridden together to ensure collection classes such as Maps and Sets
work as expected.
The new Visualforce rule VfHtmlStyleTagXss
checks for potential XSS problems when using <style>
tags on Visualforce pages.
AvoidUsingShortType
:
arithmetic on shorts is not significantly slower than on ints, whereas
using shorts may provide significant memory savings in arrays.SimplifyStartsWith
:
the suggested code transformation has an insignificant performance
impact, and decreases readability.AbstractDomXmlRule
AbstractWsdlRule
AbstractXmlRule
GenericToken#getKind
has been added as experimental. This unifies the token interface for
both JavaCC and Antlr. The already existing method
AntlrToken#getKind
is therefore experimental as well. The returned constant depends on the
actual language and might change whenever the grammar of the language is
changed.The PMD team is pleased to announce PMD 6.30.0.
This is a minor release.
The C# module now supports the new option --ignore-literal-sequences
,
which can be used to avoid detection of some uninteresting clones.
Support for other languages may be added in the future. See #2945
The Scala module now supports suppression
through CPD-ON
/CPD-OFF
comment pairs. See #2929
The Visualforce AST now can resolve the data type of Visualforce
expressions that reference Apex Controller properties and Custom Object
fields. This feature improves the precision of existing rules, like VfUnescapeEl
.
This can be configured using two environment variables: *
PMD_VF_APEXDIRECTORIES
: Comma separated list of directories
for Apex classes. Absolute or relative to the Visualforce directory.
Default is ../classes
. Specifying an empty string will
disable data type resolution for Apex Controller properties. *
PMD_VF_OBJECTSDIRECTORIES
: Comma separated list of
directories for Custom Objects. Absolute or relative to the Visualforce
directory. Default is ../objects
. Specifying an empty
string will disable data type resolution for Custom Object fields.
This feature is experimental, in particular, expect changes to the way the configuration is specified. We’ll probably extend the CLI instead of relying on environment variables in a future version.
Thanks to Jeff Bartolotta and Roopa Mohan for contributing this!
RuleSetFactory
and
RulesetsFactoryUtils
have been deprecated in favor of
RuleSetLoader
.
This is easier to configure, and more maintainable than the multiple
overloads of RulesetsFactoryUtils
.RuleSet
for simple cases, eg
forSingleRule
.
These replace some counterparts in
RuleSetFactory
RuleSets
is also deprecated, many APIs that require a RuleSets instance now are
deprecated, and have a counterpart that expects a
List<RuleSet>
.RuleSetReferenceId
,
RuleSetReference
,
RuleSetFactoryCompatibility
are deprecated. They are most likely not relevant outside of the
implementation of pmd-core.PMD
classMany classes around PMD’s entry point
(PMD
)
have been deprecated as internal, including: * The contents of the
packages
net.sourceforge.pmd.cli
,
net.sourceforge.pmd.processor
*
SourceCodeProcessor
* The constructors of
PMD
(the class will be made a utility class)
ASTPackageDeclaration#getPackageNameImage
,
ASTTypeParameter#getParameterName
and the corresponding XPath attributes. In both cases they’re replaced
with a new method getName
, the attribute is
@Name
.ASTClassOrInterfaceBody#isAnonymousInnerClass
,
and
ASTClassOrInterfaceBody#isEnumChild
,
refs #905Those 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.lang.ecmascript.Ecmascript3Handler
net.sourceforge.pmd.lang.ecmascript.Ecmascript3Parser
EcmascriptParser#parserOptions
EcmascriptParser#getSuppressMap
net.sourceforge.pmd.lang.rule.ParametricRuleViolation
ParserOptions#suppressMarker
net.sourceforge.pmd.lang.modelica.rule.ModelicaRuleViolationFactory
The PMD team is pleased to announce PMD 6.29.0.
This is a minor release.
OperationWithLimitsInLoop
(apex-performance
) finds operations in loops that may hit
governor limits such as DML operations, SOQL queries and more. The rule
replaces the three rules “AvoidDmlStatementsInLoops”,
“AvoidSoqlInLoops”, and “AvoidSoslInLoops”.DoNotCallSystemExit
has been renamed to DoNotTerminateVM
,
since it checks for all the following calls:
System.exit(int)
, Runtime.exit(int)
,
Runtime.halt(int)
. All these calls terminate the Java VM,
which is bad, if the VM runs an application server which many
independent applications.AvoidDmlStatementsInLoops
,
AvoidSoqlInLoops
and AvoidSoslInLoops
(apex-performance
) are deprecated in favour of the new rule
OperationWithLimitsInLoop
.
The deprecated rules will be removed with PMD 7.0.0.The PMD team is pleased to announce PMD 6.28.0.
This is a minor release.
The AnyTokenizer is used for languages, that don’t have an own lexer/grammar based tokenizer. AnyTokenizer now handles string literals and end-of-line comments. Fortran, Perl and Ruby have been updated to use AnyTokenizer instead of their old custom tokenizer based on AbstractTokenizer. See #2758 for details.
AbstractTokenizer and the custom tokenizers of Fortran, Perl and Ruby are deprecated now.
net.sourceforge.pmd.RuleViolationComparator
.
Use
RuleViolation#DEFAULT_COMPARATOR
instead.net.sourceforge.pmd.cpd.AbstractTokenizer
.
Use
net.sourceforge.pmd.cpd.AnyTokenizer
instead.net.sourceforge.pmd.cpd.FortranTokenizer
.
Was replaced by an
AnyTokenizer
.
Use
FortranLanguage#getTokenizer
anyway.net.sourceforge.pmd.cpd.PerlTokenizer
.
Was replaced by an
AnyTokenizer
.
Use
PerlLanguage#getTokenizer
anyway.net.sourceforge.pmd.cpd.RubyTokenizer
.
Was replaced by an
AnyTokenizer
.
Use
RubyLanguage#getTokenizer
anyway.RuleReference#getOverriddenLanguage
and
RuleReference#setLanguage
net.sourceforge.pmd.lang.cs.antlr4.CSharpLexer
will be moved to package net.sourceforge.pmd.lang.cs.ast
with PMD 7.net.sourceforge.pmd.lang.dart.antlr4.Dart2Lexer
will be renamed to DartLexer
and moved to package
net.sourceforge.pmd.lang.dart.ast
with PMD 7. All other
classes in the old package will be removed.net.sourceforge.pmd.lang.go.antlr4.GolangLexer
will be moved to package net.sourceforge.pmd.lang.go.ast
with PMD 7. All other classes in the old package will be removed.net.sourceforge.pmd.lang.kotlin.antlr4.Kotlin
will be renamed to KotlinLexer
and moved to package
net.sourceforge.pmd.lang.kotlin.ast
with PMD 7.net.sourceforge.pmd.lang.lua.antlr4.LuaLexer
will be moved to package net.sourceforge.pmd.lang.lua.ast
with PMD 7. All other classes in the old package will be removed.The PMD team is pleased to announce PMD 6.27.0.
This is a minor release.
This release of PMD brings support for Java 15. PMD can parse Text Blocks which have been promoted to be a standard language feature of Java.
PMD also supports Pattern Matching for instanceof, Records, and Sealed Classes.
Note: The Pattern Matching for instanceof, Records, and Sealed
Classes are all preview language features of OpenJDK 15 and are not
enabled by default. 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
15-preview
:
export PMD_JAVA_OPTS=--enable-preview
./run.sh pmd -language java -version 15-preview ...
Note: Support for Java 13 preview language features have been removed. The version “13-preview” is no longer available.
In the past, tab characters in source files has been handled differently in different languages by PMD. For instance in Java, tab characters had a width of 8 columns, while C# used only 1 column. Visualforce instead used 4 columns.
This has been unified now so that tab characters are consistently now always 1 column wide.
This however might be a incompatible change, if you’re using the properties “BeginColumn” or “EndColumn” additionally to “BeginLine” and “EndLine” of a Token/AST node in order to highlight where a rule violation occurred in the source file. If you have logic there that deals with tab characters, you most likely can remove this logic now, since tab characters are now just “normal” characters in terms of string processing.
See also [all] Ensure PMD/CPD uses tab width of 1 for tabs consistently #2656.
This PMD release ships a new version of the pmd-designer. For the changes, see PMD Designer Changelog.
AvoidReassigningCatchVariables
(java-bestpractices
) finds cases where the variable of the
caught exception is reassigned. This practice is surprising and prevents
further evolution of the code like multi-catch.The Java rule CloseResource
(java-errorprone
) has a new property
closeNotInFinally
. With this property set to
true
the rule will also find calls to close a resource,
which are not in a finally-block of a try-statement. If a resource is
not closed within a finally block, it might not be closed at all in case
of exceptions.
As this new detection would yield many new violations, it is disabled by default. It might be enabled in a later version of PMD.
DataflowAnomalyAnalysis
(java-errorprone
) is deprecated in favour of UnusedAssignment
(java-bestpractices
), which was introduced in PMD
6.26.0.language
attribute will be required on all rule
elements that
declare a new rule. Some base rule classes set the language implicitly
in their constructor, and so this is not required in all cases for the
rule to work. But this behavior will be discontinued in PMD 7, so
missing language
attributes are now reported as a forward
compatibility warning.Properties of
AbstractXmlRule
Many methods of
net.sourceforge.pmd.Report
.
They are replaced by accessors that produce a List. For example,
iterator()
(and implementing Iterable) and
isEmpty()
are both replaced by
getViolations()
.
The dataflow codebase is deprecated for removal in PMD 7. This includes all code in the following packages, and their subpackages:
TypeHelper
is deprecated in favor of
TypeTestUtil
,
which has the same functionality, but a slightly changed API.
Many of the classes in
net.sourceforge.pmd.lang.java.symboltable
are deprecated as internal API.
char foo = '\0';
- Mykhailo PalahutaThe PMD team is pleased to announce PMD 6.26.0.
This is a minor release.
UnusedAssignment
(java-bestpractices
) finds assignments to variables, that
are never used and are useless. The new rule is supposed to entirely
replace DataflowAnomalyAnalysis
.ArrayIsStoredDirectly
(java-bestpractices
) now ignores by default private methods
and constructors. You can restore the old behavior by setting the new
property allowPrivate
to “false”.RuleChainVisitor
and all implementations in language modulesAbstractRuleChainVisitor
Language#getRuleChainVisitorClass
BaseLanguageModule#<init>
ImportWrapper
unsafe
- Artem KrosheninnikovThe PMD team is pleased to announce PMD 6.25.0.
This is a minor release.
Up until now the PMD Scala module has been compiled against scala 2.13 only by default. However, this makes it impossible to use pmd as a library in scala projects, that use scala 2.12, e.g. in sbt plugins. Therefore PMD now provides cross compiled pmd-scala modules for both versions: scala 2.12 and scala 2.13.
The new modules have new maven artifactIds. The old artifactId
net.sourceforge.pmd:pmd-scala:6.25.0
is still available,
but is deprecated from now on. It has been demoted to be just a
delegation to the new pmd-scala_2.13
module and will be
removed eventually.
The coordinates for the new modules are:
<dependency>
<groupId>net.sourceforge.pmd</groupId>
<artifactId>pmd-scala_2.12</artifactId>
<version>6.25.0</version>
</dependency>
<dependency>
<groupId>net.sourceforge.pmd</groupId>
<artifactId>pmd-scala_2.13</artifactId>
<version>6.25.0</version>
</dependency>
The command line version of PMD continues to use scala 2.13.
The new Java Rule UnnecessaryCast
(java-codestyle
) finds casts that are unnecessary while
accessing collection elements.
The new Java Rule AvoidCalendarDateCreation
(java-performance
) finds usages of
java.util.Calendar
whose purpose is just to get the current
date. This can be done in a more lightweight way.
The new Java Rule UseIOStreamsWithApacheCommonsFileItem
(java-performance
) finds usage of
FileItem.get()
and FileItem.getString()
. These
two methods are problematic since they load the whole uploaded file into
memory.
The Java rule UseDiamondOperator
(java-codestyle
) now by default finds unnecessary usages of
type parameters, which are nested, involve wildcards and are used within
a ternary operator. These usages are usually only unnecessary with Java8
and later, when the type inference in Java has been improved.
In order to avoid false positives when checking Java7 only code, the
rule has the new property java7Compatibility
, which is
disabled by default. Settings this to “true” retains the old rule
behaviour.
The maven module net.sourceforge.pmd:pmd-scala
is
deprecated. Use net.sourceforge.pmd:pmd-scala_2.13
or
net.sourceforge.pmd:pmd-scala_2.12
instead.
Rule implementation classes are internal API and should not be
used by clients directly. The rules should only be referenced via their
entry in the corresponding category ruleset
(e.g. <rule ref="category/java/bestpractices.xml/AbstractClassWithoutAbstractMethod" />
).
While we definitely won’t move or rename the rule classes in PMD 6.x, we might consider changes in PMD 7.0.0 and onwards.
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.
AbstractIgnoredAnnotationRule
(Java)AbstractInefficientZeroCheck
(Java)AbstractJUnitRule
(Java)AbstractJavaMetricsRule
(Java)AbstractLombokAwareRule
(Java)AbstractPoorMethodCall
(Java)AbstractSunSecureRule
(Java)AbstractNcssCountRule
(Java)AbstractCommentRule
(Java)AbstractOptimizationRule
(Java)RegexHelper
(Java)AbstractApexUnitTestRule
(Apex)AbstractNcssCountRule
(Apex)AbstractNcssCountRule
(PLSQL)ApexParser
ApexHandler
RuleChain
RuleSets
RulesetsFactoryUtils#getRuleSets
TokenEntry#TokenEntry
AbstractTokenizerTest
.
Use CpdTextComparisonTest in module pmd-lang-test instead. For details
see Testing
your implementation in the developer documentation.ASTAnnotation#suppresses
(Apex)ApexXPathRule
(Apex)SymbolTableTestRule
(Java)InefficientStringBufferingRule#isInStringBufferOperation
The PMD team is pleased to announce PMD 6.24.0.
This is a minor release.
Thanks to Fernando Cosso CPD can now find duplicates in XML files as well. This is useful to find duplicated sections in XML files.
This PMD release ships a new version of the pmd-designer. For the changes, see PMD Designer Changelog.
The new Java Rule LiteralsFirstInComparisons
(java-bestpractices
) find String literals, that are used in
comparisons and are not positioned first. Using the String literal as
the receiver of e.g. equals
helps to avoid
NullPointerExceptions.
This rule is replacing the two old rules PositionLiteralsFirstInComparisons
and PositionLiteralsFirstInCaseInsensitiveComparisons
and extends the check for the methods compareTo
,
compareToIgnoreCase
and contentEquals
in
addition to equals
and equalsIgnoreCase
.
Note: This rule also replaces the two mentioned rules in Java’s quickstart ruleset.
PositionLiteralsFirstInComparisons
and PositionLiteralsFirstInCaseInsensitiveComparisons
have been deprecated in favor of the new rule LiteralsFirstInComparisons
.BaseLanguageModule#addVersion(String,
LanguageVersionHandler, boolean)
TokenMgrError
,
in particular, a new constructor is available that should be preferred
to the old onesAntlrTokenManager.ANTLRSyntaxError
Note: Experimental APIs are identified with the
annotation
Experimental
,
see its javadoc for details
BaseLanguageModule
have been replaced by a definitive API.The PMD team is pleased to announce PMD 6.23.0.
This is a minor release.
To facilitate healthy and constructive community behavior PMD adopts Contributor Convenant as its code of conduct.
Please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms.
You can find the code of conduct in the file code_of_conduct.md in our repository.
XPath rules written with XPath 2.0 now support conversion to a
rulechain rule, which improves their performance. The rulechain is a
mechanism that allows several rules to be executed in a single tree
traversal. Conversion to the rulechain is possible if your XPath
expression looks like
//someNode/... | //someOtherNode/... | ...
, that is, a
union of one or more path expressions that start with //
.
Instead of traversing the whole tree once per path expression (and per
rule), a single traversal executes all rules in your ruleset as
needed.
This conversion is performed automatically and cannot be disabled. The conversion should not change the result of your rules, if it does, please report a bug at https://github.com/pmd/pmd/issues
Note that XPath 1.0 support, the default XPath version, is deprecated since PMD 6.22.0. We highly recommend that you upgrade your rules to XPath 2.0. Please refer to the migration guide.
PMD uses the Rhino
library to parse Javascript. The default version has been set to
ES6
, so that some ECMAScript 2015 features are supported.
E.g. let
statements and for-of
loops are now
parsed. However Rhino does not support all features.
PMD now supports a JSON renderer (use it with -f json
on
the CLI). See the
documentation and example
The new Apex rule FieldDeclarationsShouldBeAtStart
(apex-codestyle
) helps to ensure that field declarations
are always at the beginning of a class.
The new Apex rule UnusedLocalVariable
(apex-bestpractices
) detects unused local
variables.
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.
As part of the changes we’d like to do to AST classes for 7.0.0, we would like to hide some methods and constructors that rule writers should not have access to. The following usages are now deprecated in the Apex, Javascript, PL/SQL, Scala and Visualforce ASTs:
InternalApi
.
Nodes should only be obtained from the parser, which for rules, means
that they never need to instantiate node themselves. Those constructors
will be made package private with 7.0.0.Parser
(eg
VfParser
)
are deprecated and should not be used directly. Use
LanguageVersionHandler#getParser
instead.TokenManager
(eg
VfTokenManager
)
are deprecated and should not be used outside of our implementation.
This also affects CPD-only modules.These deprecations are added to the following language modules in
this release. Please look at the package documentation to find out the
full list of deprecations. * Apex:
net.sourceforge.pmd.lang.apex.ast
* Javascript:
net.sourceforge.pmd.lang.ecmascript.ast
* PL/SQL:
net.sourceforge.pmd.lang.plsql.ast
* Scala:
net.sourceforge.pmd.lang.scala.ast
* Visualforce:
net.sourceforge.pmd.lang.vf.ast
These deprecations have already been rolled out in a previous version
for the following languages: * Java:
net.sourceforge.pmd.lang.java.ast
* Java Server Pages:
net.sourceforge.pmd.lang.jsp.ast
* Velocity Template Language:
net.sourceforge.pmd.lang.vm.ast
Outside of these packages, these changes also concern the following TokenManager implementations, and their corresponding Parser if it exists (in the same package):
CppTokenManager
JavaTokenManager
Ecmascript5TokenManager
JspTokenManager
MatlabTokenManager
ModelicaTokenManager
ObjectiveCTokenManager
PLSQLTokenManager
PythonTokenManager
VfTokenManager
VmTokenManager
In the Java AST the following attributes are deprecated and will issue a warning when used in XPath rules:
ASTAdditiveExpression#getImage
- use getOperator()
insteadASTVariableDeclaratorId#getImage
- use getName()
insteadASTVariableDeclaratorId#getVariableName
- use getName()
insteadParser#getTokenManager
TokenManager#setFileName
AbstractTokenManager#setFileName
AbstractTokenManager#getFileName
AntlrToken#getType
- use getKind()
instead.ImmutableLanguage
MockRule
Node#getFirstParentOfAnyType
Node#getAsDocument
AbstractNode#hasDescendantOfAnyType
ASTRecordDeclaration#getComponentList
XPathRule
.
See javadoc for details.The PMD team is pleased to announce PMD 6.22.0.
This is a minor release.
This release of PMD brings support for Java 14. PMD can parse Switch Expressions, which have been promoted to be a standard language feature of Java.
PMD also parses Text Blocks as String literals, which is still a preview language feature in Java 14.
The new Pattern Matching for instanceof can be used as well as Records.
Note: The Text Blocks, Pattern Matching for instanceof and Records
are all preview language features of OpenJDK 14 and are not enabled by
default. 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
14-preview
:
export PMD_JAVA_OPTS=--enable-preview
./run.sh pmd -language java -version 14-preview ...
Note: Support for the extended break statement introduced in Java 12 as a preview language feature has been removed from PMD with this version. The version “12-preview” is no longer available.
This PMD release ships a new version of the pmd-designer. For the changes, see PMD Designer Changelog.
In addition to suppressing violation with the
@SuppressWarnings
annotation, Apex now also supports the
suppressions with a NOPMD
comment. See Suppressing
warnings.
The C# tokenizer is now based on an antlr grammar instead of a manual written tokenizer. This should give more accurate results and especially fixes the problems with the using statement syntax (see #2139).
See the new documentation about Writing XPath Rules.
Note: As of PMD version 6.22.0, XPath versions 1.0 and the 1.0 compatibility mode are deprecated. XPath 2.0 is superior in many ways, for example for its support for type checking, sequence values, or quantified expressions. For a detailed but approachable review of the features of XPath 2.0 and above, see the Saxon documentation.
The Rule CognitiveComplexity
(apex-design
) finds methods and classes that are highly
complex and therefore difficult to read and more costly to maintain. In
contrast to cyclomatic complexity, this rule uses “Cognitive
Complexity”, which is a measure of how difficult it is for humans to
read and understand a method.
The Rule TestMethodsMustBeInTestClasses
(apex-errorprone
) finds test methods that are not residing
in a test class. The test methods should be moved to a proper test
class. Support for tests inside functional classes was removed in
Spring-13 (API Version 27.0), making classes that violate this rule fail
compile-time. This rule is however useful when dealing with legacy
code.
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.
Implementations of
RuleViolationFactory
in each language module, eg
JavaRuleViolationFactory
.
See javadoc of
RuleViolationFactory
.
Implementations of
RuleViolation
in each language module, eg
JavaRuleViolation
.
See javadoc of
RuleViolation
.
Constructors of
RuleSetFactory
,
use factory methods from
RulesetsFactoryUtils
instead
AbstractApexNodeBase
,
and the related visit
methods on
ApexParserVisitor
and its implementations. Use
ApexNode
instead, now considers comments too.
DFAGraphRule
and its implementationsDFAGraphMethod
Node
interface and
AbstractNode
base class. See their javadoc for details.Node#isFindBoundary
is deprecated for XPath queries.net.sourceforge.pmd.lang.metrics
,
though most of them were internal and probably not used directly outside
of PMD. Use
MetricsUtil
as a replacement for the language-specific façades too.QualifiableNode
,
QualifiedName
AbstractJavaParser
AbstractJavaHandler
ASTAnyTypeDeclaration.TypeKind
ASTAnyTypeDeclaration#getKind
JavaQualifiedName
ASTCatchStatement#getBlock
ASTCompilationUnit#declarationsAreInDefaultPackage
JavaQualifiableNode
net.sourceforge.pmd.lang.java.qname
and its contentsMethodLikeNode
ASTMethodOrConstructorDeclaration
,
ASTLambdaExpression
.ASTAnyTypeDeclaration#getImage
will be removed. Please use getSimpleName()
instead. This
affects
ASTAnnotationTypeDeclaration#getImage
,
ASTClassOrInterfaceDeclaration#getImage
,
and
ASTEnumDeclaration#getImage
.ASTTryStatement
,
replacements with other names have been added. This includes the XPath
attribute @Finally
, replace it with a test for
child::FinallyStatement
.getGuardExpressionNode
are
replaced with getCondition
. This affects the following
nodes: WhileStatement, DoStatement, ForStatement, IfStatement,
AssertStatement, ConditionalExpression.ASTYieldStatement
will not implement
TypeNode
anymore come 7.0.0. Test the type of the expression nested within
it.JavaMetrics
,
JavaMetricsComputer
ASTArguments#getArgumentCount
.
Use
size
instead.ASTFormalParameters#getParameterCount
.
Use
size
instead.As part of the changes we’d like to do to AST classes for 7.0.0, we would like to hide some methods and constructors that rule writers should not have access to. The following usages are now deprecated in the JSP AST (with other languages to come):
InternalApi
.
Nodes should only be obtained from the parser, which for rules, means
that they never need to instantiate node themselves. Those constructors
will be made package private with 7.0.0.JspParser
is deprecated and should not be used directly. Use
LanguageVersionHandler#getParser
instead.Please look at
net.sourceforge.pmd.lang.jsp.ast
to find out the full list of deprecations.
As part of the changes we’d like to do to AST classes for 7.0.0, we would like to hide some methods and constructors that rule writers should not have access to. The following usages are now deprecated in the VM AST (with other languages to come):
InternalApi
.
Nodes should only be obtained from the parser, which for rules, means
that they never need to instantiate node themselves. Those constructors
will be made package private with 7.0.0.net.sourceforge.pmd.lang.vm.directive
as well as the classes
DirectiveMapper
and
LogUtil
are deprecated for removal. They were only used internally during
parsing.VmParser
is deprecated and should not be used directly. Use
LanguageVersionHandler#getParser
instead.Please look at
net.sourceforge.pmd.lang.vm.ast
to find out the full list of deprecations.
The production and node ASTCursorBody
was unnecessary,
not used and has been removed. Cursors have been already parsed as
ASTCursorSpecification
.
The PMD team is pleased to announce PMD 6.21.0.
This is a minor release.
Thanks to Anatoly Trosinenko PMD supports now a new language: Modelica is a language to model complex physical systems. Both PMD and CPD are supported and there are already 3 rules available. The PMD Designer supports syntax highlighting for Modelica.
While the language implementation is quite complete, Modelica support is considered experimental for now. This is to allow us to change the rule API (e.g. the AST classes) slightly and improve the implementation based on your feedback.
We added a experimental feature to dump the AST of a source file into XML. The XML format is of course PMD specific and language dependent. That XML file can be used to execute (XPath) queries against without PMD. It can also be used as a textual visualization of the AST if you don’t want to use the Designer.
This feature is experimental and might change or even be removed in the future, if it is not useful. A short description how to use it is available under Creating XML dump of the AST.
Any feedback about it, especially about your use cases, is highly appreciated.
The CPD XML output format has been enhanced to also report column information for found duplications in addition to the line information. This allows to display the exact tokens, that are considered duplicate.
If a CPD language doesn’t provide these exact information, then these additional attributes are omitted.
Each <file>
element in the XML format now has 3
new attributes:
endline
column
(if there is column information
available)endcolumn
(if there is column information
available)The Java rule AvoidLiteralsInIfCondition
(java-errorprone
) has a new property
ignoreExpressions
. This property is set by default to
true
in order to maintain compatibility. If this property
is set to false, then literals in more complex expressions are
considered as well.
The Apex rule ApexCSRF
(apex-errorprone
) has been moved from category “Security”
to “Error Prone”. The Apex runtime already prevents DML statements from
being executed, but only at runtime. So, if you try to do this, you’ll
get an error at runtime, hence this is error prone. See also the
discussion on #2064.
The Java rule CommentRequired
(java-documentation
) has a new property
classCommentRequirement
. This replaces the now deprecated
property headerCommentRequirement
, since the name was
misleading. (File) header comments are not checked, but class comments
are.
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.
Implementations of RuleViolationFactory
in each language module, eg JavaRuleViolationFactory
.
See javadoc of RuleViolationFactory
.
Implementations of RuleViolation
in each language module, eg JavaRuleViolation
.
See javadoc of RuleViolation
.
Constructors of RuleSetFactory
,
use factory methods from RulesetsFactoryUtils
instead
AbstractApexNodeBase
,
and the related visit
methods on ApexParserVisitor
and its implementations. Use ApexNode
instead, now considers comments too.
CharStream
,
JavaCharStream
,
SimpleCharStream
:
these are APIs used by our JavaCC implementations and that will be
moved/refactored for PMD 7.0.0. They should not be used, extended or
implemented directly.
All classes generated by JavaCC, eg JJTJavaParserState
.
This includes token classes, which will be replaced with a single
implementation, and subclasses of ParseException
,
whose usages will be replaced by just that superclass.
Node
interface and AbstractNode
base class. See their javadoc for details.Node#isFindBoundary
is deprecated for XPath queries.AbstractJavaParser
AbstractJavaHandler
ASTAnyTypeDeclaration.TypeKind
ASTAnyTypeDeclaration#getKind
JavaQualifiedName
ASTCatchStatement#getBlock
ASTCompilationUnit#declarationsAreInDefaultPackage
JavaQualifiableNode
net.sourceforge.pmd.lang.java.qname
and its contentsMethodLikeNode
ASTMethodOrConstructorDeclaration
,
ASTLambdaExpression
.ASTAnyTypeDeclaration#getImage
will be removed. Please use getSimpleName()
instead. This
affects ASTAnnotationTypeDeclaration#getImage
,
ASTClassOrInterfaceDeclaration#getImage
,
and ASTEnumDeclaration#getImage
.ASTTryStatement
,
replacements with other names have been added. This includes the XPath
attribute @Finally
, replace it with a test for
child::FinallyStatement
.getGuardExpressionNode
are
replaced with getCondition
. This affects the following
nodes: WhileStatement, DoStatement, ForStatement, IfStatement,
AssertStatement, ConditionalExpression.ASTYieldStatement
will not implement TypeNode
anymore come 7.0.0. Test the type of the expression nested within
it.The PMD team is pleased to announce PMD 6.20.0.
This is a minor release.
The PMD team is pleased to announce PMD 6.19.0.
This is a minor release.
This PMD release ships a new version of the pmd-designer. For the changes, see PMD Designer Changelog.
The Java rules InvalidLogMessageFormat
and MoreThanOneLogger
(java-errorprone
) now both support Log4j2. Note that the
rule “InvalidSlf4jMessageFormat” has been renamed to
“InvalidLogMessageFormat” to reflect the fact, that it now supports more
than slf4j.
The Java rule LawOfDemeter
(java-design
) ignores now also Builders, that are not
assigned to a local variable, but just directly used within a method
call chain. The method, that creates the builder needs to end with
“Builder”, e.g. newBuilder()
or initBuilder()
works. This change fixes a couple of false positives.
The Java rule DataflowAnomalyAnalysis
(java-errorprone
) doesn’t check for UR anomalies (undefined
and then referenced) anymore. These checks were all false-positives,
since actual UR occurrences would lead to compile errors.
The java rule DoNotUseThreads
(java-multithreading
) has been changed to not report usages
of java.lang.Runnable
anymore. Just using
Runnable
does not automatically create a new thread. While
the check for Runnable
has been removed, the rule now
additionally checks for usages of Executors
and
ExecutorService
. Both create new threads, which are not
managed by a J2EE server.
InvalidSlf4jMessageFormat
has been renamed to InvalidLogMessageFormat
since it supports now both slf4j and log4j2 message formats.-norulesetcompatibility
shows a boolean
default valuenet.sourceforge.pmd.dcd
and its subpackages. See DCD
.LanguageRegistry
:
RuleSet#getExcludePatterns
.
Use the new method getFileExclusions
instead.RuleSet#getIncludePatterns
.
Use the new method getFileInclusions
instead.Parser#canParse
Parser#getSuppressMap
RuleBuilder#RuleBuilder
.
Use the new constructor with the correct ResourceLoader instead.RuleFactory#RuleFactory
.
Use the new constructor with the correct ResourceLoader instead.CanSuppressWarnings
and its implementationsisSuppressed
getDeclaringType
.isSupressed
ASTMethodDeclarator
getMethodName
getBlock
getParameterCount
CanSuppressWarnings
and its implementationsisSupressed
net.sourceforge.pmd.util
and its subpackages, except net.sourceforge.pmd.util.datasource
and net.sourceforge.pmd.util.database
.GridBagHelper
ColumnDescriptor
The PMD team is pleased to announce PMD 6.18.0.
This is a minor release.
This release of PMD brings support for Java 13. PMD can parse Switch Expressions with the
new yield
statement and resolve the type of such an
expression.
PMD also parses Text Blocks as String literals.
Note: The Switch Expressions and Text Blocks are a preview language
feature of OpenJDK 13 and are not enabled by default. 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
13-preview
:
export PMD_JAVA_OPTS=--enable-preview
./run.sh pmd -language java -version 13-preview ...
Note: Support for the extended break statement introduced in Java 12 as a preview language feature will be removed with the next PMD version 6.19.0.
Thanks to Chris Smith PMD now fully supports Scala. Now rules for analyzing Scala code can be developed in addition to the Copy-Paste-Detection (CPD) functionality. There are no rules yet, so contributions are welcome.
Additionally Scala support has been upgraded from 2.12.4 to 2.13.
The documentation for the rule designer is now available on the main PMD documentation page: Rule Designer Reference. Check it out to learn about the usage and features of the rule designer.
The Java rule AvoidMessageDigestField
(java-bestpractices
) detects fields of the type
java.security.MessageDigest
. Using a message digest
instance as a field would need to be synchronized, as it can easily be
used by multiple threads. Without synchronization the calculated hash
could be entirely wrong. Instead of declaring this as a field and
synchronize access to use it from multiple threads, a new instance
should be created when needed. This rule is also active when using
java’s quickstart ruleset.
The Apex rule DebugsShouldUseLoggingLevel
(apex-bestpractices
) detects usages of
System.debug()
method calls that are used without
specifying the log level. Having the log level specified provides a
cleaner log, and improves readability of it.
CloseResource
(java-errorprone
) now ignores by default instances of
java.util.stream.Stream
. These streams are
AutoCloseable
, but most streams are backed by collections,
arrays, or generating functions, which require no special resource
management. However, there are some exceptions: The stream returned by
Files::lines(Path)
is backed by a actual file and needs to
be closed. These instances won’t be found by default by the rule
anymore.Each renderer has now a new method Renderer#setUseShortNames
which is used for implementing the “shortnames” CLI option. The method
is automatically called by PMD, if this CLI option is in use. When
rendering filenames to the report, the new helper method AbstractRenderer#determineFileName
should be used. This will change the filename to a short name, if the
CLI option “shortnames” is used.
Not adjusting custom renderers will make them render always the full file names and not honoring the CLI option “shortnames”.
getImportedNameNode
and getPackage
have been deprecated and will be removed with PMD 7.0.0.RuleContext#setSourceCodeFilename
has been deprecated and will be removed. The already existing method RuleContext#setSourceCodeFile
should be used instead. The method RuleContext#getSourceCodeFilename
still exists and returns just the filename without the full path.AbstractPMDProcessor#filenameFrom
has been deprecated. It was used to determine a “short name” of the file
being analyzed, so that the report can use short names. However, this
logic has been moved to the renderers.Report#metrics
and Report
have been deprecated. They were leftovers from a previous deprecation
round targeting StatisticalRule
.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.lang.java.typeresolution
:
Everything, including subpackages, except TypeHelper
and JavaTypeDefinition
.ASTCompilationUnit#getClassTypeResolver
The PMD team is pleased to announce PMD 6.17.0.
This is a minor release.
This PMD release ships a new version of the pmd-designer. For the changes, see PMD Designer Changelog. It contains a new feature to edit test cases directly within the designer. Any feedback is highly appreciated.
Thanks to the contribution from Maikel Steneker, and built on top of the ongoing efforts to fully support Antlr-based languages, PMD now has CPD support for Lua.
Being based on a proper Antlr grammar, CPD can: * ignore comments * honor comment-based suppressions
The Java rule CloseResource
(java-errorprone
) ignores now by default
java.io.ByteArrayInputStream
and
java.io.CharArrayWriter
. Such streams/writers do not need
to be closed.
The Java rule MissingStaticMethodInNonInstantiatableClass
(java-errorprone
) has now the new property
annotations
. When one of the private constructors is
annotated with one of the annotations, then the class is not considered
non-instantiatable anymore and no violation will be reported. By
default, Spring’s @Autowired
and Java EE’s
@Inject
annotations are recognized.
The PMD team is pleased to announce PMD 6.16.0.
This is a minor release.
This PMD release ships a new version of the pmd-designer. For the changes, see PMD Designer Changelog.
The grammar has been updated to support inline constraints in CREATE TABLE statements. Additionally, the CREATE TABLE statement may now be followed by physical properties and table properties. However, these properties are skipped over during parsing.
The CREATE VIEW statement now supports subquery views.
The EXTRACT function can now be parsed correctly. It is used to extract values from a specified datetime field. Also date time literals are parsed now correctly.
The CASE expression can now be properly used within SELECT statements.
Table aliases are now supported when specifying columns in INSERT INTO clauses.
The Java rule DoubleBraceInitialization
(java-bestpractices
) detects non static initializers in
anonymous classes also known as “double brace initialization”. This can
be problematic, since a new class file is generated and object holds a
strong reference to the surrounding class.
Note: This rule is also part of the Java quickstart ruleset
(rulesets/java/quickstart.xml
).
The Java rule UnusedPrivateField
(java-bestpractices
) now ignores by default fields, that
are annotated with the Lombok experimental annotation
@Delegate
. This can be customized with the property
ignoredAnnotations
.
The Java rule SingularField
(java-design
) now ignores by default fields, that are
annotated with the Lombok experimental annotation
@Delegate
. This can be customized with the property
ignoredAnnotations
.
The Java rules UnsynchronizedStaticFormatter
and UnsynchronizedStaticDateFormatter
(java-multithreading
) now prefer synchronized blocks by
default. They will raise a violation, if the synchronization is
implemented on the method level. To allow the old behavior, the new
property allowMethodLevelSynchronization
can be
enabled.
The Java rule UseUtilityClass
(java-design
) has a new property
ignoredAnnotations
. By default, classes that are annotated
with Lombok’s @UtilityClass
are ignored now.
The Java rule NonStaticInitializer
(java-errorprone
) does not report non static initializers
in anonymous classes anymore. For this use case, there is a new rule
now: DoubleBraceInitialization
(java-bestpractices
).
The Java rule CommentDefaultAccessModifier
(java-codestyle
) was enhanced in the last version 6.15.0 to
check also top-level types by default. This created many new violations.
Missing the access modifier for top-level types is not so critical,
since it only decreases the visibility of the type.
The default behaviour has been restored. If you want to enable the
check for top-level types, you can use the new property
checkTopLevelTypes
.
The Java rule CloseResource
(java-errorprone
) now by default searches for any unclosed
java.lang.AutoCloseable
resource. This includes now the
standard java.io.*Stream
classes. Previously only
SQL-related resources were considered by this rule. The types can still
be configured via the types
property. Some resources do not
need to be closed (e.g. ByteArrayOutputStream
). These
exceptions can be configured via the new property
allowedResourceTypes
. In order to restore the old
behaviour, just remove the type java.lang.AutoCloseable
from the types
property and keep the remaining SQL-related
classes.
AvoidFinalLocalVariable
(java-codestyle
) has been deprecated and will be removed
with PMD 7.0.0. The rule is controversial and also contradicts other
existing rules such as LocalVariableCouldBeFinal
.
If the goal is to avoid defining constants in a scope smaller than the
class, then the rule AvoidDuplicateLiterals
should be used instead.Reminder: Please don’t use members marked with the annotation
InternalApi
, as they will likely be removed, hidden, or otherwise intentionally broken with 7.0.0.
As part of the changes we’d like to do to AST classes for 7.0.0, we would like to hide some methods and constructors that rule writers should not have access to. The following usages are now deprecated in the Java AST (with other languages to come):
InternalApi
.
Nodes should only be obtained from the parser, which for rules, means
that never need to instantiate node themselves. Those constructors will
be made package private with 7.0.0.Please look at net.sourceforge.pmd.lang.java.ast
to find out the full list of deprecations.
The PMD team is pleased to announce PMD 6.15.0.
This is a minor release.
Thanks to the contributions from Maikel Steneker CPD for Matlab can now parse Matlab programs which use the question mark operator to specify access to class members:
classdef Class1
properties (SetAccess = ?Class2)
CPD also understands now double quoted strings, which are supported since version R2017a of Matlab:
str = "This is a string"
CPD now supports digit separators in C++ (language module “cpp”). This is a C++14 feature.
Example: auto integer_literal = 1'000'000;
The single quotes can be used to add some structure to large numbers.
CPD also parses raw string literals now correctly (see #1784).
The new Apex rule FieldNamingConventions
(apex-codestyle
) checks the naming conventions for field
declarations. By default this rule uses the standard Apex naming
convention (Camel case), but it can be configured through
properties.
The new Apex rule FormalParameterNamingConventions
(apex-codestyle
) checks the naming conventions for formal
parameters of methods. By default this rule uses the standard Apex
naming convention (Camel case), but it can be configured through
properties.
The new Apex rule LocalVariableNamingConventions
(apex-codestyle
) checks the naming conventions for local
variable declarations. By default this rule uses the standard Apex
naming convention (Camel case), but it can be configured through
properties.
The new Apex rule PropertyNamingConventions
(apex-codestyle
) checks the naming conventions for property
declarations. By default this rule uses the standard Apex naming
convention (Camel case), but it can be configured through
properties.
The new Java rule UseShortArrayInitializer
(java-codestyle
) searches for array initialization
expressions, which can be written shorter.
The Apex rule ClassNamingConventions
(apex-codestyle
) can now be configured using various
properties for the specific kind of type declarations (e.g. class,
interface, enum). As before, this rule uses by default the standard Apex
naming convention (Pascal case).
The Apex rule MethodNamingConventions
(apex-codestyle
) can now be configured using various
properties to differenciate e.g. static methods and test methods. As
before, this rule uses by default the standard Apex naming convention
(Camel case).
The Java rule FieldNamingConventions
(java-codestyle
) now by default ignores the field
serialPersistentFields
. Since this is a field which needs
to have this special name, no field naming conventions can be applied
here. It is excluded the same way like serialVersionUID
via
the property exclusions
.
The Java rule CommentRequired
(java-documentation
) has a new property
serialPersistentFieldsCommentRequired
with the default
value “Ignored”. This means that from now on comments for the field
serialPersistentFields
are not required anymore. You can
change the property to restore the old behavior.
The Java rule ProperLogger
(java-errorprone
) has two new properties to configure the
logger class (e.g. “org.slf4j.Logger”) and the logger name of the
special case, when the logger is not static. The name of the static
logger variable was already configurable. The new property “loggerClass”
allows to use this rule for different logging frameworks. This rule
covers all the cases of the now deprecated rule LoggerIsNotStaticFinal
.
The Java rule CommentDefaultAccessModifier
(java-codestyle
) now reports also missing comments for
top-level classes and annotations, that are package-private.
The Apex rule VariableNamingConventions
(apex-codestyle
) has been deprecated and will be removed
with PMD 7.0.0. The rule is replaced by the more general rules FieldNamingConventions
,
FormalParameterNamingConventions
,
LocalVariableNamingConventions
,
and PropertyNamingConventions
.
The Java rule LoggerIsNotStaticFinal
(java-errorprone
) has been deprecated and will be removed
with PMD 7.0.0. The rule is replaced by ProperLogger
.
DumpFacades
in all languages, that could be used to
transform a AST into a textual representation, will be removed with PMD
7. The rule designer is a better way to inspect nodes.
net.sourceforge.pmd.lang.apex.ast.DumpFacade
net.sourceforge.pmd.lang.java.ast.DumpFacade
net.sourceforge.pmd.lang.ecmascript.ast.DumpFacade
net.sourceforge.pmd.lang.jsp.ast.DumpFacade
net.sourceforge.pmd.lang.plsql.ast.DumpFacade
net.sourceforge.pmd.lang.vf.ast.DumpFacade
net.sourceforge.pmd.lang.vm.ast.AbstractVmNode#dump
net.sourceforge.pmd.lang.xml.ast.DumpFacade
LanguageVersionHandler#getDumpFacade
will be removed as well. It is deprecated, along with all its
implementations in the subclasses of LanguageVersionHandler
.The PMD team is pleased to announce PMD 6.14.0.
This is a minor release.
Thanks to the contribution from Maikel Steneker, and built on top of the ongoing efforts to fully support Antlr-based languages, PMD now has CPD support for Dart.
Being based on a proper Antlr grammar, CPD can: * ignore comments * ignore imports / libraries * honor comment-based suppressions
This PMD release ships a new version of the pmd-designer. For the changes, see PMD Designer Changelog.
The Java rule AssignmentToNonFinalStatic
(java-errorprone
) will now report on each assignment made
within a constructor rather than on the field declaration. This makes it
easier for developers to find the offending statements.
The Java rule NoPackage
(java-codestyle
) will now report additionally enums and
annotations that do not have a package declaration.
No changes.
The PMD team is pleased to announce PMD 6.13.0.
This is a minor release.
We are still searching for a new logo for PMD for the next major release.
Learn more about how to participate on github issue 1663.
This release of PMD brings support for Java 12. PMD can parse the new Switch Expressions and resolve the type of such an expression.
Note: The Switch Expressions are a preview language feature of
OpenJDK 12 and are not enabled by default. In order to analyze a project
with PMD that uses these language features, you’ll need to enable it via
the new environment variable PMD_JAVA_OPTS
:
export PMD_JAVA_OPTS=--enable-preview
./run.sh pmd ...
PMD provides now a quickstart ruleset for Salesforce.com Apex, which
you can use as a base ruleset to get your custom ruleset started. You
can reference it with rulesets/apex/quickstart.xml
. You are
strongly encouraged to create
your own ruleset though.
The quickstart ruleset has the intention, to be useful out-of-the-box for many projects. Therefore it references only rules, that are most likely to apply everywhere.
Any feedback would be greatly appreciated.
The rule designer’s codebase has been moved out of the main repository and will be developed at pmd/pmd-designer from now on. The maven coordinates will stay the same for the time being. The designer will still be shipped with PMD’s binaries.
Annotation[@Resolved = false()]
finds unsupported
annotations.AnnotationParameter[@Name='RestResource'][@Value='/myurl']
gives access to annotation parameters.CatchBlockStatement[@ExceptionType='Exception'][@VariableName='e']
finds catch block for specific exception types.Field[@Type='String']
find all String fields,
Field[string-length(@Name) < 5]
finds all fields with
short names and Field[@Value='a']
find alls fields, that
are initialized with a specific value.LiteralExpression[@String = true()]
finds all String
literals. There are attributes for each type: @Boolean
,
@Integer
, @Double
, @Long
,
@Decimal
, @Null
.Method[@Constructor = true()]
selects all constructors.
Method[@ReturnType = 'String']
selects all methods that
return a String.ModifierNode
node has a couple of attributes to
check for the existence of specific modifiers: @Test
,
@TestOrTestSetup
, @WithSharing
,
@WithoutSharing
, @InheritedSharing
,
@WebService
, @Global
,
@Override
.Parameter[@Type='Integer']
you can find all method
parameters of type Integer. The same attribute Type
exists
as well for: NewObjectExpression
, Property
,
VariableDeclaration
.VariableExpression[@Image='i']
finds all variable
usages of the variable “i”.The new Java rule AvoidUncheckedExceptionsInSignatures
(java-design
) finds methods or constructors that declare
unchecked exceptions in their throws
clause. This forces
the caller to handle the exception, even though it is a runtime
exception.
The new Java rule DetachedTestCase
(java-errorprone
) searches for public methods in test
classes, which are not annotated with @Test
. These methods
might be test cases where the annotation has been forgotten. Because of
that those test cases are never executed.
The new Java rule WhileLoopWithLiteralBoolean
(java-bestpractices
) finds Do-While-Loops and While-Loops
that can be simplified since they use simply true
or
false
as their loop condition.
The new Apex rule ApexAssertionsShouldIncludeMessage
(apex-bestpractices
) searches for assertions in unit tests
and checks, whether they use a message argument.
The new Apex rule ApexUnitTestMethodShouldHaveIsTestAnnotation
(apex-bestpractices
) searches for methods in test classes,
which are missing the @IsTest
annotation.
The new PLSQL rule AvoidTabCharacter
(plsql-codestyle
) checks, that there are no tab characters
(“) in the source file.
The new PLSQL rule LineLength
(plsql-codestyle
) helps to enforce a maximum line
length.
The start scripts run.sh
, pmd.bat
and
cpd.bat
support the new environment variable
PMD_JAVA_OPTS
. This can be used to set arbitrary JVM
options for running PMD, such as memory settings
(e.g. PMD_JAVA_OPTS=-Xmx512m
) or enable preview language
features (e.g. PMD_JAVA_OPTS=--enable-preview
).
The previously available variables such as OPTS
or
HEAPSIZE
are deprecated and will be removed with PMD
7.0.0.
CodeClimateRule
is deprecated in 7.0.0 because it was unused for 2 years and created an
unwanted dependency. Properties “cc_categories”,
“cc_remediation_points_multiplier”, “cc_block_highlighting” will also be
removed. See #1702
for more.
The Apex ruleset rulesets/apex/ruleset.xml
has been
deprecated and will be removed in 7.0.0. Please use the new quickstart
ruleset rulesets/apex/quickstart.xml
instead.
The PMD team is pleased to announce PMD 6.12.0.
This is a minor release.
PMD’s logo was great for a long time. But now we want to take the opportunity with the next major release to change our logo in order to use a more “politically correct” one.
Learn more about how to participate on github issue 1663.
ITBA students Matías Fraga, Tomi De Lucca and Lucas Soncini keep working on
bringing full Antlr support to PMD. For this release, they have
implemented token filtering in an equivalent way as we did for JavaCC
languages, adding support for CPD suppressions through
CPD-OFF
and CPD-ON
comments for all
Antlr-based languages.
This means, you can now ignore arbitrary blocks of code on: * Go * Kotlin * Swift
Simply start the suppression with any comment (single or multiline)
containing CPD-OFF
, and resume again with a comment
containing CPD-ON
.
More information is available in the user documentation.
UseTryWithResources
(java-bestpractices
) searches for try-blocks, that could be
changed to a try-with-resources statement. This statement ensures that
each resource is closed at the end of the statement and is available
since Java 7.MethodNamingConventions
(apex-codestyle
) has a new property
skipTestMethodUnderscores
, which is by default disabled.
The new property allows for ignoring all test methods, either using the
testMethod
modifier or simply annotating them
@isTest
.No changes.
The PMD team is pleased to announce PMD 6.11.0.
This is a minor release.
//BooleanExpression[@Operator='&&']
.SELECT * FROM TABLE(expr)
).The new Java rule UnsynchronizedStaticFormatter
(java-multithreading
) detects unsynchronized usages of
static java.text.Format
instances. This rule is a more
generic replacement of the rule UnsynchronizedStaticDateFormatter
which focused just on DateFormat
.
The new Java rule ForLoopVariableCount
(java-bestpractices
) checks for the number of control
variables in a for-loop. Having a lot of control variables makes it
harder to understand what the loop does. The maximum allowed number of
variables is by default 1 and can be configured by a property.
The new Java rule AvoidReassigningLoopVariables
(java-bestpractices
) searches for loop variables that are
reassigned. Changing the loop variables additionally to the loop itself
can lead to hard-to-find bugs.
The new Java rule UseDiamondOperator
(java-codestyle
) looks for constructor calls with explicit
type parameters. Since Java 1.7, these type parameters are not necessary
anymore, as they can be inferred now.
LocalVariableCouldBeFinal
(java-codestyle
) has a new property
ignoreForEachDecl
, which is by default disabled. The new
property allows for ignoring non-final loop variables in a for-each
statement.UnsynchronizedStaticDateFormatter
has been deprecated and will be removed with PMD 7.0.0. The rule is
replaced by the more general UnsynchronizedStaticFormatter
.StatisticalRule
and the related helper classes and base rule classes are deprecated for
removal in 7.0.0. This includes all of net.sourceforge.pmd.stat
and net.sourceforge.pmd.lang.rule.stat
,
and also AbstractStatisticalJavaRule
,
AbstractStatisticalApexRule
and the like. The methods Report#addMetric
and metricAdded
will also be removed.setProperty
is deprecated, because MultiValuePropertyDescriptor
is deprecated as wellThe PMD team is pleased to announce PMD 6.10.0.
This is a minor release.
Thanks to Maikel Steneker, CPD now supports Kotlin. This means, you can use CPD to find duplicated code in your Kotlin projects.
UseUnderscoresInNumericLiterals
(java-codestyle
) verifies that numeric literals over a
given length (4 chars by default, but configurable) are using
underscores every 3 digits for readability. The rule only applies to
Java 7+ codebases.The Java rule JUnitTestsShouldIncludeAssert
(java-bestpractices
) now also detects Soft
Assertions.
The property exceptionfile
of the rule AvoidDuplicateLiterals
(java-errorprone
) has been deprecated and will be removed
with 7.0.0. Please use exceptionList
instead.
The properties framework is about to get a lifting, and for that reason, we need to deprecate a lot of APIs to remove them in 7.0.0. The proposed changes to the API are described on the wiki
Construction of property descriptors has been possible through
builders since 6.0.0. The 7.0.0 API will only allow construction through
builders. The builder hierarchy, currently found in the package net.sourceforge.pmd.properties.builders
,
is being replaced by the simpler PropertyBuilder
.
Their APIs enjoy a high degree of source compatibility.
Concrete property classes like IntegerProperty
and StringMultiProperty
will gradually all be deprecated until 7.0.0. Their usages should be
replaced by direct usage of the PropertyDescriptor
interface, e.g. PropertyDescriptor<Integer>
or
PropertyDescriptor<List<String>>
.
Instead of spreading properties across countless classes, the
utility class PropertyFactory
will become from 7.0.0 on the only provider for property descriptor
builders. Each current property type will be replaced by a corresponding
method on PropertyFactory
:
IntegerProperty
is replaced by PropertyFactory#intProperty
IntegerMultiProperty
is replaced by PropertyFactory#intListProperty
FloatProperty
and DoubleProperty
are both replaced by PropertyFactory#doubleProperty
.
Having a separate property for floats wasn’t that useful.
FloatMultiProperty
and DoubleMultiProperty
are replaced by PropertyFactory#doubleListProperty
.StringProperty
is replaced by PropertyFactory#stringProperty
StringMultiProperty
is replaced by PropertyFactory#stringListProperty
RegexProperty
is replaced by PropertyFactory#regexProperty
EnumeratedProperty
is replaced by PropertyFactory#enumProperty
EnumeratedProperty
is replaced by PropertyFactory#enumListProperty
BooleanProperty
is replaced by PropertyFactory#booleanProperty
BooleanMultiProperty
,
is not replaced, because it doesn’t have a use case.CharacterProperty
is replaced by PropertyFactory#charProperty
CharacterMultiProperty
is replaced by PropertyFactory#charListProperty
LongProperty
is replaced by PropertyFactory#longIntProperty
LongMultiProperty
is replaced by PropertyFactory#longIntListProperty
MethodProperty
,
FileProperty
,
TypeProperty
and their multi-valued counterparts are discontinued for lack of a
use-case, and have no planned replacement in 7.0.0 for now.
Here’s an example:
// Before 7.0.0, these are equivalent:
= new IntegerProperty("score", "Top score value", 1, 100, 40, 3.0f);
IntegerProperty myProperty = IntegerProperty.named("score").desc("Top score value").range(1, 100).defaultValue(40).uiOrder(3.0f);
IntegerProperty myProperty
// They both map to the following in 7.0.0
PropertyDescriptor<Integer> myProperty = PropertyFactory.intProperty("score").desc("Top score value").require(inRange(1, 100)).defaultValue(40);
You’re highly encouraged to migrate to using this new API as soon as possible, to ease your migration to 7.0.0.
EnumeratedPropertyDescriptor
,
NumericPropertyDescriptor
,
PackagedPropertyDescriptor
,
and the related builders (in net.sourceforge.pmd.properties.builders
)
will be removed. These specialized interfaces allowed additional
constraints to be enforced on the value of a property, but made the
property class hierarchy very large and impractical to maintain. Their
functionality will be mapped uniformly to PropertyConstraint
s,
which will allow virtually any constraint to be defined, and improve
documentation and error reporting. The related methods PropertyTypeId#isPropertyNumeric
and PropertyTypeId#isPropertyPackaged
are also deprecated.
MultiValuePropertyDescriptor
and SingleValuePropertyDescriptor
are deprecated. 7.0.0 will introduce a new XML syntax which will remove
the need for such a divide between single- and multi-valued properties.
The method PropertyDescriptor#isMultiValue
will be removed accordingly.
preferredRowCount
is deprecated with no intended replacement. It was never implemented,
and does not belong in this interface. The methods uiOrder
and compareTo(PropertyDescriptor)
are deprecated for the
same reason. These methods mix presentation logic with business logic
and are not necessary for PropertyDescriptors to work.
PropertyDescriptor
will not extend
Comparable<PropertyDescriptor>
anymore come
7.0.0.propertyErrorFor
is deprecated and will be removed with no intended replacement. It’s
really just a shortcut for
prop.errorFor(rule.getProperty(prop))
.T
valueFrom(String)
and String
asDelimitedString
(T)
are deprecated and will be removed. These were used to serialize and
deserialize properties to/from a string, but 7.0.0 will introduce a more
flexible XML syntax which will make them obsolete.isMultiValue
and type
are deprecated and won’t be replaced. The new XML syntax will remove the
need for a divide between multi- and single-value properties, and will
allow arbitrary types to be represented. Since arbitrary types may be
represented, type
will become obsolete as it can’t
represent generic types, which will nevertheless be representable with
the XML syntax. It was only used for documentation, but a new way to
document these properties exhaustively will be added with 7.0.0.errorFor
is deprecated as its return type will be changed to
Optional<String>
with the shift to Java 8.The implementation of the adapters for the XPath engines Saxon
and Jaxen (package net.sourceforge.pmd.lang.ast.xpath
)
are now deprecated. They’ll be moved to an internal package come 7.0.0.
Only Attribute
remains public API.
The classes PropertyDescriptorField
,
PropertyDescriptorBuilderConversionWrapper
,
and the methods PropertyDescriptor#attributeValuesById
,
PropertyDescriptor#isDefinedExternally
and PropertyTypeId#getFactory
.
These were used to read and write properties to and from XML, but were
not intended as public API.
The class ValueParserConstants
and the interface ValueParser
.
All classes from net.sourceforge.pmd.lang.java.metrics.impl.visitors
are now considered internal API. They’re deprecated and will be moved
into an internal package with 7.0.0. To implement your own metrics
visitors, JavaParserVisitorAdapter
should be directly subclassed.
LanguageVersionHandler#getDataFlowHandler()
,
LanguageVersionHandler#getDFAGraphRule()
All classes from net.sourceforge.pmd.properties.modules
will be removed.
The interface Dimensionable
has been deprecated. It gets in the way of a grammar change for 7.0.0
and won’t be needed anymore (see #997).
Several methods from ASTLocalVariableDeclaration
and ASTFieldDeclaration
have also been deprecated:
ASTFieldDeclaration
won’t be a TypeNode
come 7.0.0, so getType
and getTypeDefinition
are deprecated.
The method getVariableName
on those two nodes will
be removed, too.
All these are deprecated because those nodes may declare several
variables at once, possibly with different types (and obviously with
different names). They both implement Iterator<
ASTVariableDeclaratorId
>
though, so you should iterate on each declared variable. See #910.
Visitor decorators are now deprecated and will be removed in PMD 7.0.0. They were originally a way to write composable visitors, used in the metrics framework, but they didn’t prove cost-effective.
net.sourceforge.pmd.lang.java.ast
:
JavaParserDecoratedVisitor
,
JavaParserControllessVisitor
,
JavaParserControllessVisitorAdapter
,
and JavaParserVisitorDecorator
are deprecated with no intended replacement.The LanguageModules of several languages, that only support CPD execution, have been deprecated. These languages are not fully supported by PMD, so having a language module does not make sense. The functionality of CPD is not affected by this change. The following classes have been deprecated and will be removed with PMD 7.0.0:
CppHandler
CppLanguageModule
CppParser
CsLanguageModule
FortranLanguageModule
GroovyLanguageModule
MatlabHandler
MatlabLanguageModule
MatlabParser
ObjectiveCHandler
ObjectiveCLanguageModule
ObjectiveCParser
PhpLanguageModule
PythonHandler
PythonLanguageModule
PythonParser
RubyLanguageModule
ScalaLanguageModule
SwiftLanguageModule
Optional AST processing stages like symbol table, type resolution or data-flow analysis will be reified in 7.0.0 to factorise common logic and make them extensible. Further explanations about this change can be found on #1426. Consequently, the following APIs are deprecated for removal:
Rule
:
isDfa()
,
isTypeResolution()
,
isMultifile()
and their respective setters.RuleSet
:
usesDFA(Language)
,
usesTypeResolution(Language)
,
usesMultifile(Language)
RuleSets
:
usesDFA(Language)
,
usesTypeResolution(Language)
,
usesMultifile(Language)
LanguageVersionHandler
:
getDataFlowFacade()
,
getSymbolFacade()
,
getSymbolFacade(ClassLoader)
,
getTypeResolutionFacade(ClassLoader)
,
getQualifiedNameResolutionFacade(ClassLoader)
The PMD team is pleased to announce PMD 6.9.0.
This is a minor release.
Thanks to the work of ITBA students Matías Fraga, Tomi De Lucca and Lucas Soncini, Golang is now backed by a proper Antlr Grammar. This means CPD is now better at detecting duplicates, as comments are recognized as such and ignored.
CodeFormat
(plsql-codestyle
) verifies that PLSQL code is properly
formatted. It checks e.g. for correct indentation in select statements
and verifies that each parameter is defined on a separate line.-ignorelist
. With that, you
can provide a file containing a comma-delimit list of files, that should
be excluded during analysis. The ignorelist is applied after the files
have been selected via -dir
or -filelist
,
which means, if the file is in both lists, then it will be ignored.
Note: there is no corresponding option for the Ant task, since the
feature is already available via Ant’s FileSet include/exclude
filters.The PMD team is pleased to announce PMD 6.8.0.
This is a minor release.
Until now, all released public members and types were implicitly considered part of PMD’s public API, including inheritance-specific members (protected members, abstract methods). We have maintained those APIs with the goal to preserve full binary compatibility between minor releases, only breaking those APIs infrequently, for major releases.
In order to allow PMD to move forward at a faster pace, this implicit contract will be invalidated with PMD 7.0.0. We now introduce more fine-grained distinctions between the type of compatibility support we guarantee for our libraries, and ways to make them explicit to clients of PMD.
.internal
packages and @InternalApi
annotationInternal API is meant for use only by the main PMD codebase. Internal types and methods may be modified in any way, or even removed, at any time.
Any API in a package that contains an .internal
segment
is considered internal. The @InternalApi
annotation will be
used for APIs that have to live outside of these packages, e.g. methods
of a public type that shouldn’t be used outside of PMD (again, these can
be removed anytime).
@ReservedSubclassing
Types marked with the @ReservedSubclassing
annotation
are only meant to be subclassed by classes within PMD. As such, we may
add new abstract methods, or remove protected methods, at any time. All
published public members remain supported. The annotation is
not inherited, which means a reserved interface doesn’t prevent
its implementors to be subclassed.
@Experimental
APIs marked with the @Experimental
annotation at the
class or method level are subject to change. They can be modified in any
way, or even removed, at any time. You should not use or rely on them in
any production code. They are purely to allow broad testing and
feedback.
@Deprecated
APIs marked with the @Deprecated
annotation at the class
or method level will remain supported until the next major release but
it is recommended to stop using them.
All currently supported APIs will remain so until 7.0.0. All
APIs that are to be moved to .internal
packages or hidden
will be tagged @InternalApi
before that major release, and
the breaking API changes will be performed in 7.0.0.
PMD 6.8.0 provides a first quickstart ruleset for Java, which you can
use as a base ruleset to get your custom ruleset started. You can
reference it with rulesets/java/quickstart.xml
. You are
strongly encouraged to create
your own ruleset though.
The quickstart ruleset has the intention, to be useful out-of-the-box for many projects. Therefore it references only rules, that are most likely to apply everywhere.
Any feedback would be greatly appreciated.
ApexDoc
(apex-documentation
) enforces the inclusion of ApexDoc on
classes, interfaces, properties and methods; as well as some sanity
rules for such docs (no missing parameters, parameters’ order, and
return value). By default, method overrides and test classes are allowed
to not include ApexDoc.MissingSerialVersionUID
(java-errorprone
) has been modified in order to recognize
also missing serialVersionUID
fields in abstract classes,
if they are serializable. Each individual class in the inheritance chain
needs an own serialVersionUID field. See also Should
an abstract class have a serialVersionUID. This change might lead to
additional violations in existing code bases.The grammar for PLSQL has been revamped in order to fully parse
SELECT INTO
, UPDATE
, and DELETE
statements. Previously such statements have been simply skipped ahead,
now PMD is parsing them, giving access to the individual parts of a
SELECT-statement, such as the Where-Clause. This might produce new
parsing errors where PMD previously could successfully parse PLSQL code.
If this happens, please report a new issue to get this
problem fixed.
A couple of methods and fields in
net.sourceforge.pmd.properties.AbstractPropertySource
have
been deprecated, as they are replaced by already existing functionality
or expose internal implementation details:
propertyDescriptors
,
propertyValuesByDescriptor
,
copyPropertyDescriptors()
,
copyPropertyValues()
, ignoredProperties()
,
usesDefaultValues()
,
useDefaultValueFor()
.
Some methods in
net.sourceforge.pmd.properties.PropertySource
have been
deprecated as well: usesDefaultValues()
,
useDefaultValueFor()
,
ignoredProperties()
.
The class
net.sourceforge.pmd.lang.rule.AbstractDelegateRule
has been
deprecated and will be removed with PMD 7.0.0. It is internally only in
use by RuleReference.
The default constructor of
net.sourceforge.pmd.lang.rule.RuleReference
has been
deprecated and will be removed with PMD 7.0.0. RuleReferences should
only be created by providing a Rule and a RuleSetReference. Furthermore
the following methods are deprecated: setRuleReference()
,
hasOverriddenProperty()
, usesDefaultValues()
,
useDefaultValueFor()
.
The PMD team is pleased to announce PMD 6.7.0.
This is a minor release.
java-bestpractices
) has been revamped to consider not only
local variable declarations, but field declarations too.The new Java rule {% rule java/codestyle/LinguisticNaming %}
(java-codestyle
) detects cases, when a method name
indicates it returns a boolean (such as isSmall()
) but it
doesn’t. Besides method names, the rule also checks field and variable
names. It also checks, that getters return something but setters won’t.
The rule has several properties with which it can be
customized.
The new PL/SQL rule {% rule plsql/codestyle/ForLoopNaming %}
(plsql-codestyle
) enforces a naming convention for “for
loops”. Both “cursor for loops” and “index for loops” are covered. The
rule can be customized via patterns. By default, short variable names
are reported.
The new Java rule {% rule java/codestyle/FieldNamingConventions
%} (java-codestyle
) detects field names that don’t comply
to a given convention. It defaults to standard Java convention of using
camelCase, but can be configured with ease for e.g. constants or static
fields.
The new Apex rule {% rule apex/codestyle/OneDeclarationPerLine %}
(apex-codestyle
) enforces declaring a single field /
variable per line; or per statement if the strictMode
property is set. It’s an Apex equivalent of the already existing Java
rule of the same name.
All classes in the package
net.sourceforge.pmd.lang.dfa.report
have been deprecated
and will be removed with PMD 7.0.0. This includes the class
net.sourceforge.pmd.lang.dfa.report.ReportTree
. The reason
is, that this class is very specific to Java and not suitable for other
languages. It has only been used for YAHTMLRenderer
, which
has been rewritten to work without these classes.
The nodes RUNSIGNEDSHIFT and RSIGNEDSHIFT are deprecated and will be removed from the AST with PMD 7.0.0. These represented the operator of ShiftExpression in two cases out of three, but they’re not needed and make ShiftExpression inconsistent. The operator of a ShiftExpression is now accessible through ShiftExpression#getOperator.
The PMD team is pleased to announce PMD 6.6.0.
This is a minor release.
PMD is now able to parse the local-variable declaration syntax
var xxx
, that has been extended for lambda parameters with
Java 11 via JEP 323:
Local-Variable Syntax for Lambda Parameters.
The new Java rule LocalVariableNamingConventions
(java-codestyle
) detects local variable names that don’t
comply to a given convention. It defaults to standard Java convention of
using camelCase, but can be configured. Special cases can be configured
for final variables and caught exceptions’ names.
The new Java rule FormalParameterNamingConventions
(java-codestyle
) detects formal parameter names that don’t
comply to a given convention. It defaults to standard Java convention of
using camelCase, but can be configured. Special cases can be configured
for final parameters and lambda parameters (considering whether they are
explicitly typed or not).
AccessorClassGeneration
and AccessorMethodGeneration
(both in category java-bestpractices
) have been modified to
be only valid up until Java 10. Java 11 adds support for JEP 181: Nest-Based Access
Control which avoids the generation of accessor classes / methods
altogether.findDescendantsOfType
methods in
net.sourceforge.pmd.lang.ast.AbstractNode
no longer search
for exact type matches, but will match subclasses, too. That means, it’s
now possible to look for abstract node types such as
AbstractJavaTypeNode
and not only for it’s concrete
subtypes.The PMD team is pleased to announce PMD 6.5.0.
This is a minor release.
AvoidNonExistentAnnotations
(apex-errorprone
) detects usages non-officially supported
annotations. Apex supported non existent annotations for legacy reasons.
In the future, use of such non-existent annotations could result in
broken Apex code that will not compile. A full list of supported
annotations can be found herejava-codestyle
) now detects enum constrcutors with
explicit private
modifier. The rule now produces better
error messages letting you know exactly which modifiers are redundant at
each declaration.The utility class
net.sourceforge.pmd.lang.java.ast.CommentUtil
has been
deprecated and will be removed with PMD 7.0.0. Its methods have been
intended to parse javadoc tags. A more useful solution will be added
around the AST node FormalComment
, which contains as
children JavadocElement
nodes, which in turn provide access
to the JavadocTag
.
All comment AST nodes (FormalComment
,
MultiLineComment
, SingleLineComment
) have a
new method getFilteredComment()
which provide access to the
comment text without the leading /*
markers.
The method AbstractCommentRule.tagsIndicesIn()
has
been deprecated and will be removed with PMD 7.0.0. It is not very
useful, since it doesn’t extract the information in a useful way. You
would still need check, which tags have been found, and with which data
they might be accompanied.
The PMD team is pleased to announce PMD 6.4.0.
This is a minor release.
PMD is now able to understand local-variable type inference as
introduced by Java 10. Simple type resolution features are available,
e.g. the type of the variable s
is inferred correctly as
String
:
var s = "Java 10";
For some time now PMD has supported Type Resolution, and exposed this
functionality to XPath rules for the Java language with the
typeof
function. This function however had a number of
shortcomings:
@Image
but was still
required.In this release we are deprecating typeof
in favor of a
simpler typeIs
function, which behaves exactly as the old
typeof
when given all 3 arguments.
typeIs
receives a single parameter, which is the fully
qualified name of the class to test against.
So, calls such as:
//ClassOrInterfaceType[typeof(@Image, 'junit.framework.TestCase', 'TestCase')]
can now we expressed much more concisely as:
//ClassOrInterfaceType[typeIs('junit.framework.TestCase')]
With this change, we also allow to check against array types by just
appending []
to the fully qualified class name. These can
be repeated for arrays of arrays (e.g. byte[][]
or
java.lang.String[]
).
Additionally, we introduce the companion function
typeIsExactly
, that receives the same parameters as
typeIs
, but checks for exact type matches, without
considering the type hierarchy. That is, the test
typeIsExactly('junit.framework.TestCase')
will match only
if the context node is an instance of TestCase
, but not if
it’s an instance of a subclass of TestCase
. Be aware then,
that using that method with abstract types will never match.
The new Java rule HardCodedCryptoKey
(java-security
) detects hard coded keys used for
encryption. It is recommended to store keys outside of the source
code.
The new Java rule IdenticalCatchBranches
(java-codestyle
) finds catch blocks, that catch different
exception but perform the same exception handling and thus can be
collapsed into a multi-catch try statement.
The Java rule JUnit4TestShouldUseTestAnnotation
(java-bestpractices
) has a new parameter
“testClassPattern”. It is used to distinguish test classes from other
classes and avoid false positives. By default, any class, that has
“Test” in its name, is considered a test class.
The Java rule CommentDefaultAccessModifier
(java-codestyle
) allows now by default the comment
“/* package */
in addition to”/* default */
.
This behavior can still be adjusted by setting the property
regex
.
net.sourceforge.pmd.benchmark
have been deprecated:
Benchmark
, Benchmarker
,
BenchmarkReport
, BenchmarkResult
,
RuleDuration
, StringBuilderCR
and
TextReport
. Their API is not supported anymore and is
disconnected from the internals of PMD. Use the newer API based around
TimeTracker
instead, which can be found in the same
package.net.sourceforge.pmd.lang.java.xpath.TypeOfFunction
has been
deprecated. Use the newer TypeIsFunction
in the same
package.typeof
methdos in
net.sourceforge.pmd.lang.java.xpath.JavaFunctions
have been
deprecated. Use the newer typeIs
method in the same class
instead..isA
, isEither
and
isNeither
of
net.sourceforge.pmd.lang.java.typeresolution.TypeHelper
.
Use the new isExactlyAny
and isExactlyNone
methods in the same class instead.DoNotExtendJavaLangError
- Akshat BahetyThe PMD team is pleased to announce PMD 6.3.0.
This is a minor release.
As described in #904, when searching
for child nodes of the AST methods such as
hasDescendantOfType
, getFirstDescendantOfType
and findDescendantsOfType
were found to behave
inconsistently, not all of them honoring find boundaries; that is, nodes
that define a self-contained entity which should be considered
separately (think of lambdas, nested classes, anonymous classes, etc.).
We have modified these methods to ensure all of them honor find
boundaries.
This change implies several false positives / unexpected results (ie:
ASTBlockStatement
falsely returning true
to
isAllocation()
) have been fixed; and lots of searches are
now restricted to smaller search areas, which improves performance
(depending on the project, we have measured up to 10% improvements
during Type Resolution, Symbol Table analysis, and some rules’
application).
ClassNamingConventions
(java-codestyle
) has been enhanced to allow granular
configuration of naming conventions for different kinds of type
declarations (eg enum or abstract class). Each kind of declaration can
use its own naming convention using a regex property. See the rule’s
documentation for more info about configuration and default
conventions.
MethodNamingConventions
(java-codestyle
) has been enhanced in the same
way.
Back in PMD 5.6.0 we introduced the ability to suppress CPD warnings
in Java using comments, by including CPD-OFF
(to start
ignoring code), or CPD-ON
(to resume analysis) during CPD
execution. This has proved to be much more flexible and versatile than
the old annotation-based approach, and has since been the preferred way
to suppress CPD warnings.
On this occasion, we are extending support for comment-based suppressions to many other languages:
So for instance, in Python we could now do:
class BaseHandler(object):
def __init__(self):
# some unignored code
# tell cpd to start ignoring code - CPD-OFF
# mission critical code, manually loop unroll
+ x / 2);
GoDoSomethingAwesome(x + x / 2);
GoDoSomethingAwesome(x + x / 2);
GoDoSomethingAwesome(x + x / 2);
GoDoSomethingAwesome(x + x / 2);
GoDoSomethingAwesome(x + x / 2);
GoDoSomethingAwesome(x
# resume CPD analysis - CPD-ON
# further code will *not* be ignored
Other languages are equivalent.
Thanks to major contributions from kenji21 the Swift grammar has been updated to support Swift 4.1. This is a major update, since the old grammar was quite dated, and we are sure all iOS developers will enjoy it.
Unfortunately, this change is not compatible. The grammar elements
that have been removed (ie: the keywords __FILE__
,
__LINE__
, __COLUMN__
and
__FUNCTION__
) are no longer supported. We don’t usually
introduce such drastic / breaking changes in minor releases, however,
given that the whole Swift ecosystem pushes hard towards always using
the latest versions, and that Swift needs all code and libraries to be
currently compiling against the same Swift version, we felt strongly
this change was both safe and necessary to be shipped as soon as
possible. We had great feedback from the community during the process
but if you have a legitimate use case for older Swift versions, please
let us know on our Issue
Tracker.
java-security
) detects hard coded initialization vectors
used in cryptographic operations. It is recommended to use a randomly
generated IV.The Java rule UnnecessaryConstructor
(java-codestyle
) has been rewritten as a Java rule
(previously it was a XPath-based rule). It supports a new property
ignoredAnnotations
and ignores by default empty
constructors, that are annotated with javax.inject.Inject
.
Additionally, it detects now also unnecessary private constructors in
enums.
The property checkNativeMethods
of the Java rule MethodNamingConventions
(java-codestyle
) is now deprecated, as it is now superseded
by nativePattern
. Support for that property will be
maintained until 7.0.0.
The Java rule ControlStatementBraces
(java-codestyle
) supports a new boolean property
checkSingleIfStmt
. When unset, the rule won’t report
if
statements which lack braces, if the statement is not
part of an if ... else if
chain. This property defaults to
true.
java-codestyle
) is deprecated in favour of ClassNamingConventions.
See Naming rules
enhancements.The PMD team is pleased to announce PMD 6.2.0.
This is a minor release.
The Rhino Library has been upgraded from version 1.7.7 to version 1.7.7.2.
Detailed changes for changed in Rhino can be found: * For 1.7.7.2 * For 1.7.7.1
Both are bugfixing releases.
Some time ago, we added support for Incremental Analysis. On PMD 6.0.0, we started to add warns when not using it, as we strongly believe it’s a great improvement to our user’s experience as analysis time is greatly reduced; and in the future we plan to have it enabled by default. However, we realize some scenarios don’t benefit from it (ie: CI jobs), and having the warning logged can be noisy and cause confusion.
To this end, we have added a new flag to allow you to explicitly
disable incremental analysis. On CLI, this is the new
-no-cache
flag. On Ant, there is a noCache
attribute for the <pmd>
task.
On both scenarios, disabling the cache takes precedence over setting a cache location.
The new Java rule MissingOverride
(category bestpractices
) detects overridden and implemented
methods, which are not marked with the @Override
annotation. Annotating overridden methods with @Override
ensures at compile time that the method really overrides one, which
helps refactoring and clarifies intent.
The new Java rule UnnecessaryAnnotationValueElement
(category codestyle
) detects annotations with a single
element (value
) that explicitely names it. That is, doing
@SuppressWarnings(value = "unchecked")
would be flagged in
favor of @SuppressWarnings("unchecked")
.
The new Java rule ControlStatementBraces
(category codestyle
) enforces the presence of braces on
control statements where they are optional. Properties allow to
customize which statements are required to have braces. This rule
replaces the now deprecated rules WhileLoopMustUseBraces
,
ForLoopMustUseBraces
, IfStmtMustUseBraces
, and
IfElseStmtMustUseBraces
. More than covering the use cases
of those rules, this rule also supports do ... while
statements and case
labels of switch
statements (disabled by default).
The Java rule CommentContentRule
(java-documentation
) previously had the property
wordsAreRegex
. But this property never had been implemented
and is removed now.
The Java rule UnusedPrivateField
(java-bestpractices
) now has a new
ignoredAnnotations
property that allows to configure
annotations that imply the field should be ignored. By default
@java.lang.Deprecated
and @javafx.fxml.FXML
are ignored.
The Java rule UnusedPrivateMethod
(java-bestpractices
) now has a new
ignoredAnnotations
property that allows to configure
annotations that imply the method should be ignored. By default
@java.lang.Deprecated
is ignored.
The Java rule ImmutableField
(java-design
) now has a new ignoredAnnotations
property that allows to configure annotations that imply the method
should be ignored. By default several lombok
annotations
are ignored
The Java rule SingularField
(java-design
) now has a new ignoredAnnotations
property that allows to configure annotations that imply the method
should be ignored. By default several lombok
annotations
are ignored
WhileLoopMustUseBraces
,
ForLoopMustUseBraces
, IfStmtMustUseBraces
, and
IfElseStmtMustUseBraces
are deprecated. They will be
replaced by the new rule ControlStatementBraces
, in the
category codestyle
.A new CLI switch, -no-cache
, disables incremental
analysis and the related suggestion. This overrides the
-cache
option. The corresponding Ant task parameter is
noCache
.
The static method
PMDParameters.transformParametersIntoConfiguration(PMDParameters)
is now deprecated, for removal in 7.0.0. The new instance method
PMDParameters.toConfiguration()
replaces it.
The method ASTConstructorDeclaration.getParameters()
has been deprecated in favor of the new method
getFormalParameters()
. This method is available for both
ASTConstructorDeclaration
and
ASTMethodDeclaration
.
The PMD team is pleased to announce PMD 6.1.0.
This is a minor release.
The Designer now supports configuring properties for XPath based rule development. The Designer is still under development and any feedback is welcome.
You can start the designer via run.sh designer
or
designer.bat
.
The method getXPathNodeName
is added to the
Node
interface, which removes the use of the
toString
of a node to get its XPath element name (see #569). A default
implementation is provided in AbstractNode
, to stay
compatible with existing implementors.
The toString
method of a Node is not changed for the
time being, and still produces the name of the XPath node. That
behaviour may however change in future major releases, e.g. to produce a
more useful message for debugging.
The interface net.sourceforge.pmd.cpd.Renderer
has been
deprecated. A new interface
net.sourceforge.pmd.cpd.renderer.CPDRenderer
has been
introduced to replace it. The main difference is that the new interface
is meant to render directly to a java.io.Writer
rather than
to a String. This allows to greatly reduce the memory footprint of CPD,
as on large projects, with many duplications, it was causing
OutOfMemoryError
s (see #795).
net.sourceforge.pmd.cpd.FileReporter
has also been
deprecated as part of this change, as it’s no longer needed.
The PMD team is pleased to announce PMD 6.0.1.
This is a bug fixing release.
With the release of PMD 6.0.0, all rules have been sorted into one of the following eight categories:
Please note, that not every category in every language may have a
rule. There might be categories with no rules at all, such as
category/java/security.xml
, which has currently no rules.
There are even languages, which only have rules of one category
(e.g. category/xml/errorprone.xml
).
You can find the information about available rules in the generated rule documentation, available at https://pmd.github.io/6.0.1/.
In order to help migrate to the new category scheme, the new name for the old, deprecated rule names will be logged as a warning. See PR #865. Please note, that the deprecated rule names will keep working throughout PMD 6. You can upgrade to PMD 6 without the immediate need to migrate your current ruleset. That backwards compatibility will be maintained until PMD 7.0.0 is released.
net.sourceforge.pmd.PMD.VERSION
has been
deprecated and will be removed with PMD 7.0.0. Please use
net.sourceforge.pmd.PMDVersion.VERSION
instead.The PMD team is pleased to announce PMD 6.0.0.
This is a major release.
Thanks to Clément Fournier, we now have a new rule designer GUI, which is based on JavaFX. It replaces the old designer and can be started via
bin/run.sh designer
(on Unix-like platform such as
Linux and Mac OS X)bin\designer.bat
(on Windows)Note: At least Java8 is required for the designer. The old designer
is still available as designerold
but will be removed with
the next major release.
The Java grammar has been updated to support analyzing Java 9 projects:
module-info.java
can be
parsedJava 9 support is enabled by default. You can switch back to an older
java version via the command line,
e.g. -language java -version 1.8
.
We are now using the Apex Jorje Lexer to tokenize Apex code for CPD. This change means:
CPD will therefore have less false positives and false negatives.
As part of Google Summer of Code 2017, Bendegúz Nagy worked on type resolution for Java. For this release he has extended support for method calls for both instance and static methods.
Method shadowing and overloading are supported, as are varargs. However, the selection of the target method upon the presence of generics and type inference is still work in progress. Expect it in forecoming releases.
As for fields, the basic support was in place for release 5.8.0, but has now been expanded to support static fields.
As part of Google Summer of Code 2017, Clément Fournier is worked on the new metrics framework for object-oriented metrics.
There are already a couple of metrics (e.g. ATFD, WMC, Cyclo, LoC) implemented. More metrics are planned. Based on those metrics, rules like “GodClass” detection could be implemented more easily. The following rules benefit from the metrics framework: NcssCount (java), NPathComplexity (java), CyclomaticComplexity (both java and apex).
The Metrics framework has been abstracted and is available in
pmd-core
for other languages. With this PMD release, the
metrics framework is supported for both Java and Apex.
A number of improvements on error reporting have taken place, meaning changes to some of the report formats.
Also of note, the xml report now provides a XML Schema definition, allowing easier parsing and validation.
Processing errors can now provide not only the message previously included on some reports, but also a full stacktrace. This will allow better error reports when providing feedback to the PMD team and help in debugging issues.
The report formats providing full stacktrace of errors are:
For a long time reports have been notified of configuration errors on rules, but they have remained hidden. On a push to make these more evident to users, and help them get the best results out of PMD, we have started to include them on the reports.
So far, only reports that include processing errors are showing configuration errors. In other words, the report formats providing configuration error reporting are:
As we move forward we will be able to detect and report more
configuration errors (ie: incomplete auxclasspath
) and
include them to such reports.
Apex violations can now be suppressed very similarly to how it’s done
in Java, by making use of a @SuppressWarnings
annotation.
Supported syntax includes:
@SupressWarnings('PMD') // to supress all Apex rules
@SupressWarnings('all') // to supress all Apex rules
@SupressWarnings('PMD.ARuleName') // to supress only the rule named ARuleName
@SupressWarnings('PMD.ARuleName, PMD.AnotherRuleName') // to supress only the rule named ARuleName or AnotherRuleName
Notice this last scenario is slightly different to the Java syntax. This is due to differences in the Apex grammar for annotations.
All built-in rules have been sorted into one of eight categories:
These categories help you to find rules and figure out the relevance and impact for your project.
All rules have been moved accordingly, e.g. the rule
“JumbledIncrementer”, which was previously defined in the ruleset
“java-basic” has now been moved to the “Error Prone” category. The new
rule reference to be used is
<rule ref="category/java/errorprone.xml/JumbledIncrementer"/>
.
The old rulesets like “java-basic” are still kept for backwards-compatibility but will be removed eventually. The rule reference documentation has been updated to reflect these changes.
The new Java rule NcssCount
(category
design
) replaces the three rules “NcssConstructorCount”,
“NcssMethodCount”, and “NcssTypeCount”. The new rule uses the metrics
framework to achieve the same. It has two properties, to define the
report level for method and class sizes separately. Constructors and
methods are considered the same.
The new Java rule DoNotExtendJavaLangThrowable
(category errorprone
) is a companion for the
java-strictexception.xml/DoNotExtendJavaLangError
,
detecting direct extensions of
java.lang.Throwable
.
The new Java rule ForLoopCanBeForeach
(category
errorprone
) helps to identify those for-loops that can be
safely refactored into for-each-loops available since java 1.5.
The new Java rule AvoidFileStream
(category
performance
) helps to identify code relying on
FileInputStream
/ FileOutputStream
which, by
using a finalizer, produces extra / unnecessary overhead to garbage
collection, and should be replaced with
Files.newInputStream
/ Files.newOutputStream
available since java 1.7.
The new Java rule DataClass
(category
design
) detects simple data-holders without behaviour. This
might indicate that the behaviour is scattered elsewhere and the data
class exposes the internal data structure, which breaks
encapsulation.
The new Apex rule AvoidDirectAccessTriggerMap
(category errorprone
) helps to identify direct array access
to triggers, which can produce bugs by either accessing non-existing
indexes, or leaving them out. You should use for-each-loops
instead.
The new Apex rule AvoidHardcodingId
(category
errorprone
) detects hardcoded strings that look like
identifiers and flags them. Record IDs change between environments,
meaning hardcoded ids are bound to fail under a different
setup.
The new Apex rule CyclomaticComplexity
(category
design
) detects overly complex classes and methods. The
report threshold can be configured separately for classes and
methods.
A whole bunch of new rules has been added to Apex. They all fit
into the category errorprone
. The 5 rules are migrated for
Apex from the equivalent Java rules and include:
EmptyCatchBlock
to detect catch blocks completely
ignoring exceptions.EmptyIfStmt
for if blocks with no content, that can be
safely removed.EmptyTryOrFinallyBlock
for empty try / finally blocks
that can be safely removed.EmptyWhileStmt
for empty while loops that can be safely
removed.EmptyStatementBlock
for empty code blocks that can be
safely removed.The new Apex rule AvoidSoslInLoops
(category
performance
) is the companion of the old
AvoidSoqlInLoops
rule, flagging SOSL (Salesforce Object
Search Language) queries when within loops, to avoid governor issues,
and hitting the database too often.
The Java rule UnnecessaryFinalModifier
(category
codestyle
, former ruleset
java-unnecessarycode
) has been merged into the rule
UnnecessaryModifier
. As part of this, the rule has been
revamped to detect more cases. It will now flag anonymous class’ methods
marked as final (can’t be overridden, so it’s pointless), along with
final methods overridden / defined within enum instances. It will also
flag final
modifiers on try-with-resources.
The Java rule UnnecessaryParentheses
(category
codestyle
, former ruleset java-controversial
)
has been merged into UselessParentheses
(category
codestyle
, former ruleset java-unnecessary
).
The rule covers all scenarios previously covered by either
rule.
The Java rule UncommentedEmptyConstructor
(category
documentation
, former ruleset java-design
)
will now ignore empty constructors annotated with
javax.inject.Inject
.
The Java rule AbstractClassWithoutAnyMethod
(category bestpractices
, former ruleset
java-design
) will now ignore classes annotated with
com.google.auto.value.AutoValue
.
The Java rule GodClass
(category
design', former ruleset
java-design`) has been revamped to
use the new metrics framework.
The Java rule LooseCoupling
(category
bestpractices
, former ruleset java-coupling
)
has been replaced by the typeresolution-based implementation.
The Java rule CloneMethodMustImplementCloneable
(category errorprone
, former ruleset
java-clone
) has been replaced by the typeresolution-based
implementation and is now able to detect cases if a class implements or
extends a Cloneable class/interface.
The Java rule UnusedImports
(category
bestpractices
, former ruleset java-imports
)
has been replaced by the typeresolution-based implementation and is now
able to detect unused on-demand imports.
The Java rule SignatureDeclareThrowsException
(category design
, former ruleset ‘java-strictexception’)
has been replaced by the typeresolution-based implementation. It has a
new property IgnoreJUnitCompletely
, which allows all
methods in a JUnit testcase to throw exceptions.
The Java rule NPathComplexity
(category
design
, former ruleset java-codesize
) has been
revamped to use the new metrics framework. Its report threshold can be
configured via the property reportLevel
, which replaces the
now deprecated property minimum
.
The Java rule CyclomaticComplexity
(category
design
, former ruleset java-codesize
) has been
revamped to use the new metrics framework. Its report threshold can be
configured via the properties classReportLevel
and
methodReportLevel
separately. The old property
reportLevel
, which configured the level for both total
class and method complexity, is deprecated.
The Java rule CommentRequired
(category
documentation
, former ruleset java-comments
)
has been revamped to include 2 new properties:
accessorCommentRequirement
to specify documentation
requirements for getters and setters (default to
ignored
)methodWithOverrideCommentRequirement
to specify
documentation requirements for methods annotated with
@Override
(default to ignored
)The Java rule EmptyCatchBlock
(category
errorprone
, former ruleset java-empty
) has
been changed to ignore exceptions named ignore
or
expected
by default. You can still override this behaviour
by setting the allowExceptionNameRegex
property.
The Java rule OptimizableToArrayCall
(category
performance
, former ruleset design
) has been
modified to fit for the current JVM implementations: It basically
detects now the opposite and suggests to use
Collection.toArray(new E[0])
with a zero-sized array. See
Arrays
of Wisdom of the Ancients.
The Java rules NcssConstructorCount
,
NcssMethodCount
, and NcssTypeCount
(ruleset
java-codesize
) have been deprecated. They will be replaced
by the new rule NcssCount
in the category
design
.
The Java rule LooseCoupling
in ruleset
java-typeresolution
is deprecated. Use the rule with the
same name from category bestpractices
instead.
The Java rule CloneMethodMustImplementCloneable
in
ruleset java-typeresolution
is deprecated. Use the rule
with the same name from category errorprone
instead.
The Java rule UnusedImports
in ruleset
java-typeresolution
is deprecated. Use the rule with the
same name from category bestpractices
instead.
The Java rule SignatureDeclareThrowsException
in
ruleset java-typeresolution
is deprecated. Use the rule
with the same name from category design
instead.
The Java rule EmptyStaticInitializer
in ruleset
java-empty
is deprecated. Use the rule
EmptyInitializer
from the category errorprone
,
which covers both static and non-static empty initializers.`
The Java rules GuardDebugLogging
(ruleset
java-logging-jakarta-commons
) and
GuardLogStatementJavaUtil
(ruleset
java-logging-java
) have been deprecated. Use the rule
GuardLogStatement
from the category
bestpractices
, which covers all cases regardless of the
logging framework.
UseSingleton
has been removed
from the ruleset java-design
. The rule has been renamed
long time ago to UseUtilityClass
(category
design
).A bug
in symbol table prevented the symbol table analysis to properly
match primitive arrays types. The issue affected the
java-unsedcode/UnusedPrivateMethod
rule, but other
rules may now produce improved results as consequence of this fix.
The Apex parser version was bumped, from 1.0-sfdc-187
to
210-SNAPSHOT
. This update let us take full advantage of the
latest improvements from Salesforce, but introduces some breaking
changes:
BlockStatements
are now created for all control
structures, even if no brace is used. We have therefore added a
hasCurlyBrace
method to differentiate between both
scenarios.CastExpression
, ConstructorPreamble
,
IllegalStoreExpression
, MethodBlockStatement
,
Modifier
, MultiStatement
,
NestedExpression
, NestedStoreExpression
,
NewKeyValueObjectExpression
and
StatementExecuted
TestNode
, DottedExpression
and
NewNameValueObjectExpression
(replaced by
NewKeyValueObjectExpression
)All existing rules have been updated to reflect these changes. If you have custom rules, be sure to update them.
For more info about the included Apex parser, see the new pmd module “pmd-apex-jorje”, which packages and provides the parser as a binary.
The incremental analysis feature first introduced in PMD 5.6.0 has been enhanced. A few minor issues have been fixed, and several improvements have been performed to make it more accurate.
The cache will now detect changes to the JARs referenced in the
auxclasspath
instead of simply looking at their paths and
order. This means that if you are referencing a JAR you are overwriting
in some way, the incremental analysis can now detect it and invalidate
it’s cache to avoid false reports.
Similarly, any changes to the execution classpath of PMD will invalidate the cache. This means that if you have custom rules packaged in a jar, any changes to it will invalidate the cache automatically.
We have also improved logging on the analysis code, allowing better insight into how the cache is performing, under debug / verbose builds you can even see individual hits / misses to the cache (and the reason for any miss!)
Finally, as this feature keeps maturing, we are gently pushing this forward. If not using incremental analysis, a warning will now be produced suggesting users to adopt it for better performance.
The implementation around the properties support for rule properties
and report properties has been revamped to be fully typesafe. Along with
that change, the support classes have been moved into an own package
net.sourceforge.pmd.properties
. While there is no change
necessary in the ruleset XML files, when using/setting values for rules,
there are adjustments necessary when declaring properties in
Java-implemented rules.
Rule properties can be declared both for Java based rules and XPath rules. This is now very well documented in Working with properties.
With PMD 6.0.0, multivalued properties are now also possible with XPath rules.
The class net.sourceforge.pmd.lang.dfa.NodeType
has
been converted to an enum. All node types are enum members now instead
of int constants. The names for node types are retained.
The Properties API (rule and report properties) has been
revamped to be fully typesafe. This is everything around
net.sourceforge.pmd.properties.PropertyDescriptor
.
Note: All classes related to properties have been moved into the
package net.sourceforge.pmd.properties
.
The rule classes
net.sourceforge.pmd.lang.apex.rule.apexunit.ApexUnitTestClassShouldHaveAsserts
and
net.sourceforge.pmd.lang.apex.rule.apexunit.ApexUnitTestShouldNotUseSeeAllDataTrue
have been renamed to ApexUnitTestClassShouldHaveAssertsRule
and ApexUnitTestShouldNotUseSeeAllDataTrueRule
,
respectively. This is to comply with the naming convention, that each
rule class should be suffixed with “Rule”.
This change has no impact on custom rulesets, since the rule names themselves didn’t change.
The never implemented method
PMD.processFiles(PMDConfiguration, RuleSetFactory, Collection<File>, RuleContext, ProgressMonitor)
along with the interface ProgressMonitor
has been
removed.
The method
PMD.setupReport(RuleSets, RuleContext, String)
is gone. It
was used to report dysfunctional rules. But PMD does this now
automatically before processing the files, so there is no need for this
method anymore.
All APIs deprecated in older versions are now removed. This includes:
Renderer.getPropertyDefinitions
AbstractRenderer.defineProperty(String, String)
AbstractRenderer.propertyDefinitions
ReportListener
Report.addListener(ReportListener)
SynchronizedReportListener
CPDConfiguration.CPDConfiguration(int, Language, String)
CPDConfiguration.getRendererFromString(String)
StreamUtil
StringUtil.appendXmlEscaped(StringBuilder, String)
StringUtil.htmlEncode(String)
Several methods in
net.sourceforge.pmd.util.CollectionUtil
have been
deprecated and will be removed in PMD 7.0.0. In particular:
CollectionUtil.addWithoutDuplicates(T[], T)
CollectionUtil.addWithoutDuplicates(T[], T[])
CollectionUtil.areSemanticEquals(T[], T[])
CollectionUtil.areEqual(Object, Object)
CollectionUtil.arraysAreEqual(Object, Object)
CollectionUtil.valuesAreTransitivelyEqual(Object[], Object[])
Several methods in
net.sourceforge.pmd.util.StringUtil
have been deprecated
and will be removed in PMD 7.0.0. In particular:
StringUtil.startsWithAny(String, String[])
StringUtil.isNotEmpty(String)
StringUtil.isEmpty(String)
StringUtil.isMissing(String)
StringUtil.areSemanticEquals(String, String)
StringUtil.replaceString(String, String, String)
StringUtil.replaceString(String, char, String)
StringUtil.substringsOf(String, char)
StringUtil.substringsOf(String, String)
StringUtil.asStringOn(StringBuffer, Iterator, String)
StringUtil.asStringOn(StringBuilder, Object[], String)
StringUtil.lpad(String, int)
The class
net.sourceforge.pmd.lang.java.typeresolution.typedefinition.JavaTypeDefinition
is now abstract, and has been enhanced to provide several new
methods.
The constructor of
net.sourceforge.pmd.RuleSetFactory
, which took a
ClassLoader
is deprecated. Please use the alternative
constructor with the
net.sourceforge.pmd.util.ResourceLoader
instead.
The following GUI related classes have been deprecated and will
be removed in PMD 7.0.0. The tool “bgastviewer”, that could be started
via the script bgastviewer.bat
or
run.sh bgastviewer
is deprecated, too, and will be removed
in PMD 7.0.0. Both the “old designer” and “bgastviewer” are replaced by
the New Rule Designer.
net.sourceforge.pmd.util.designer.CodeEditorTextPane
net.sourceforge.pmd.util.designer.CreateXMLRulePanel
net.sourceforge.pmd.util.designer.Designer
net.sourceforge.pmd.util.designer.DFAPanel
net.sourceforge.pmd.util.designer.LineGetter
net.sourceforge.pmd.util.viewer.Viewer
net.sourceforge.pmd.util.viewer.gui.ActionCommands
net.sourceforge.pmd.util.viewer.gui.ASTPanel
net.sourceforge.pmd.util.viewer.gui.EvaluationResultsPanel
net.sourceforge.pmd.util.viewer.gui.MainFrame
net.sourceforge.pmd.util.viewer.gui.ParseExceptionHandler
net.sourceforge.pmd.util.viewer.gui.SourceCodePanel
net.sourceforge.pmd.util.viewer.gui.XPathPanel
net.sourceforge.pmd.util.viewer.gui.menu.ASTNodePopupMenu
net.sourceforge.pmd.util.viewer.gui.menu.AttributesSubMenu
net.sourceforge.pmd.util.viewer.gui.menu.SimpleNodeSubMenu
net.sourceforge.pmd.util.viewer.gui.menu.XPathFragmentAddingItem
net.sourceforge.pmd.util.viewer.model.ASTModel
net.sourceforge.pmd.util.viewer.model.AttributeToolkit
net.sourceforge.pmd.util.viewer.model.SimpleNodeTreeNodeAdapter
net.sourceforge.pmd.util.viewer.model.ViewerModel
net.sourceforge.pmd.util.viewer.model.ViewerModelEvent
net.sourceforge.pmd.util.viewer.model.ViewerModelListener
net.sourceforge.pmd.util.viewer.util.NLS
The following methods in net.sourceforge.pmd.Rule
have been deprecated and will be removed in PMD 7.0.0. All methods are
replaced by their bean-like counterparts
void setUsesDFA()
. Use
void setDfa(boolean)
instead.boolean usesDFA()
. Use boolean isDfa()
instead.void setUsesTypeResolution()
. Use
void setTypeResolution(boolean)
instead.boolean usesTypeResolution()
. Use
boolean isTypeResolution()
instead.void setUsesMultifile()
. Use
void setMultifile(boolean)
instead.boolean usesMultifile()
. Use
boolean isMultifile()
instead.boolean usesRuleChain()
. Use
boolean isRuleChain()
instead.The PMD team is pleased to announce PMD 5.8.1.
This is a bug fixing release.
getGenericArgs()
method introduced to
TypeNode
in 5.8.0 was removed. You can access to generics’
info through the JavaTypeDefinition
object.JavaTypeDefinitionBuilder
class introduced in 5.8.0
is not more. You can use factory methods available on
JavaTypeDefinition
The PMD team is pleased to announce PMD 5.8.0.
This is a minor release.
As part of Google Summer of Code 2017, Bendegúz Nagy has been working on completing type resolution for Java. His progress so far has allowed to properly resolve, in addition to previously supported statements:
this
and super
, even when
qualifiedthis.myObject.aField
), and properly handling inheritance /
shadowingLambda parameter types where these are infered rather than explicit are still not supported. Expect future releases to do so.
As part of Google Summer of Code 2017, Clément Fournier has been working on a new metrics framework for object-oriented metrics.
The basic groundwork has been done already and with this release, including a first rule based on the metrics framework as a proof-of-concept: The rule CyclomaticComplexity, currently in the temporary ruleset java-metrics, uses the Cyclomatic Complexity metric to find overly complex code. This rule will eventually replace the existing three CyclomaticComplexity rules that are currently defined in the java-codesize ruleset (see also issue #445).
Since this work is still in progress, the metrics API (package
net.sourceforge.pmd.lang.java.oom
) is not finalized yet and
is expected to change.
The Java rule UnnecessaryFinalModifier
(ruleset
java-unnecessary) now also reports on private methods marked as
final
. Being private, such methods can’t be overriden, and
therefore, the final keyword is redundant.
The Java rule PreserveStackTrace
(ruleset
java-design) has been relaxed to support the builder pattern on thrown
exception. This change may introduce some false positives if using the
exception in non-orthodox ways for things other than setting the root
cause of the exception. Contact us if you find any such
scenarios.
The ruleset java-junit now properly detects JUnit5, and rules are being adapted to the changes on it’s API. This support is, however, still incomplete. Let us know of any uses we are still missing on the issue tracker
The Java rule EmptyTryBlock
(ruleset java-empty) now
allows empty blocks when using try-with-resources.
The Java rule EmptyCatchBlock
(ruleset java-empty)
now exposes a new property called allowExceptionNameRegex
.
This allow to setup a regular expression for names of exceptions you
wish to ignore for this rule. For instance, setting it to
^(ignored|expected)$
would ignore all empty catch blocks
where the catched exception is named either ignored
or
expected
. The default ignores no exceptions, being
backwards compatible.
CyclomaticComplexity
,
StdCyclomaticComplexity
,
ModifiedCyclomaticComplexity
(ruleset java-codesize) have
been deprecated. They will be eventually replaced by a new
CyclomaticComplexity rule based on the metrics framework. See also issue #445.The PMD team is pleased to announce PMD 5.7.0.
This is a minor release.
The rule “FieldDeclarationsShouldBeAtStartOfClass” of the
java-design ruleset has a new property
ignoreInterfaceDeclarations
. Setting this property to
true
ignores interface declarations, that precede fields.
Example usage:
net.sourceforge.pmd.util.StringUtil#htmlEncode(String)
is
deprecated.
org.apache.commons.lang3.StringEscapeUtils#escapeHtml4(String)
should be used instead.The PMD team is pleased to announce PMD 5.6.1.
This is a bug fixing release.
The PMD team is pleased to announce PMD 5.6.0.
The most significant changes are on analysis performance, support for Salesforce’s Visualforce language a whole new Apex Security Rule Set and the new Braces Rule Set for Apex.
We have added initial support for incremental analysis. The experimental feature allows PMD to cache analysis results between executions to speed up the analysis for all languages. New CLI flags and Ant options are available to configure it. Currently the feature is disabled by default, but this may change as it matures.
Multithread performance has been enhanced by reducing thread-contention on a bunch of areas. This is still an area of work, as the speedup of running multithreaded analysis is still relatively small (4 threads produce less than a 50% speedup). Future releases will keep improving on this area.
Once again, Symbol Table has been an area of great performance improvements. This time we were able to further improve it’s performance by roughly 10% on all supported languages. In Java in particular, several more improvements were possible, improving Symbol Table performance by a whooping 80%, that’s over 15X faster than PMD 5.5.1, when we first started working on it.
Java developers will also appreciate the revamp of
CloneMethodMustImplementCloneable
, making it over 500X
faster, and PreserveStackTrace
which is now 7X faster.
PMD now supports incremental analysis. Analysis results can be cached and reused between runs. This allows PMD to skip files without violations that have remained unchanged. In future releases, we plan to extend this behavior to unchanged files with violations too.
The cache is automatically invalidated if: * the used PMD version
changes * the auxclasspath
changed and any rules require
type resolution * the configured rule set has changed
This feature is incubating and is disabled by default. It’s only enabled if you specifically configure a cache file.
To configure the cache file from CLI, a new
-cache <path/to/file>
flag has been added.
For Ant, a new cacheLocation
attribute has been added.
For instance:
target name="pmd">
<taskdef name="pmd" classname="net.sourceforge.pmd.ant.PMDTask"/>
<pmd cacheLocation="build/pmd/pmd.cache">
<ruleset>rulesets/java/design.xml</ruleset>
<ruleset>java-basic</ruleset>
<formatter type="xml" toFile="c:\pmd_report.xml"/>
<fileset dir="/usr/local/j2sdk1.4.1_01/src/">
<include name="java/lang/*.java"/>
<fileset>
</pmd>
</target> </
Salesforce developers rejoice. To out growing Apex support we have
added full Visualforce support. Both CPD and PD are available. So far
only a security ruleset is available (vf-security
).
The rule looks for Expression Language occurances printing unescaped values from the backend. These could lead to XSS attacks.
The rule looks for <apex:page>
tags performing an
action on page load, definish such action
through
Expression Language, as doing so is vulnerable to CSRF attacks.
A new ruleset focused on security has been added, consisting of a wide range of rules to detect most common security problems.
The rule makes sure you are using randomly generated IVs and keys for
Crypto
calls. Hard-wiring these values greatly compromises
the security of encrypted data.
For instance, it would report violations on code such as:
public class without sharing Foo {
Blob hardCodedIV = Blob.valueOf('Hardcoded IV 123');
Blob hardCodedKey = Blob.valueOf('0000000000000000');
Blob data = Blob.valueOf('Data to be encrypted');
Blob encrypted = Crypto.encrypt('AES128', hardCodedKey, hardCodedIV, data);
}
The rule validates you are checking for access permissions before a SOQL/SOSL/DML operation. Since Apex runs in system mode not having proper permissions checks results in escalation of privilege and may produce runtime errors. This check forces you to handle such scenarios.
For example, the following code is considered valid:
public class Foo {
public Contact foo(String status, String ID) {
Contact c = [SELECT Status__c FROM Contact WHERE Id=:ID];
// Make sure we can update the database before even trying
if (!Schema.sObjectType.Contact.fields.Name.isUpdateable()) {
return null;
}
c.Status__c = status;
update c;
return c;
}
}
Check to avoid making DML operations in Apex class constructor/init method. This prevents modification of the database just by accessing a page.
For instance, the following code would be invalid:
public class Foo {
public init() {
insert data;
}
public Foo() {
insert data;
}
}
Checks against calling dangerous methods.
For the time being, it reports:
FinancialForce
’s
Configuration.disableTriggerCRUDSecurity()
. Disabling CRUD
security opens the door to several attacks and requires manual
validation, which is unreliable.System.debug
passing sensitive data as
parameter, which could lead to exposure of private data.Checks against accessing endpoints under plain http. You should always use https for security.
Checks against redirects to user-controlled locations. This prevents attackers from redirecting users to phishing sites.
For instance, the following code would be reported:
public class without sharing Foo {
String unsafeLocation = ApexPage.getCurrentPage().getParameters.get('url_param');
PageReference page() {
return new PageReference(unsafeLocation);
}
}
Detect classes declared without explicit sharing mode if DML methods are used. This forces the developer to take access restrictions into account before modifying objects.
Detects the usage of untrusted / unescaped variables in DML queries.
For instance, it would report on:
public class Foo {
public void test1(String t1) {
Database.query('SELECT Id FROM Account' + t1);
}
}
Detects hardcoded credentials used in requests to an endpoint.
You should refrain from hardcoding credentials: * They are hard to mantain by being mixed in application code * Particularly hard to update them when used from different classes * Granting a developer access to the codebase means granting knowledge of credentials, keeping a two-level access is not possible. * Using different credentials for different environments is troublesome and error-prone.
Instead, you should use Named Credentials and a callout endpoint.
For more information, you can check this
Reports on calls to addError
with disabled escaping. The
message passed to addError
will be displayed directly to
the user in the UI, making it prime ground for XSS attacks if
unescaped.
Makes sure that all values obtained from URL parameters are properly escaped / sanitized to avoid XSS attacks.
The Braces Rule Set has been added and serves the same purpose as the Braces Rule Set from Java: It checks the use and placement of braces around if-statements, for-loops and so on.
Avoid using if statements without using braces to surround the code block. If the code formatting or indentation is lost then it becomes difficult to separate the code being controlled from the rest.
For instance, the following code shows the different. PMD would report on the not recommended approach:
if (foo) // not recommended
x++;
if (foo) { // preferred approach
x++;
}
Avoid using ‘while’ statements without using braces to surround the code block. If the code formatting or indentation is lost then it becomes difficult to separate the code being controlled from the rest.
For instance, the following code shows the different. PMD would report on the not recommended approach:
while (true) // not recommended
x++;
while (true) { // preferred approach
x++;
}
Avoid using if..else statements without using surrounding braces. If the code formatting or indentation is lost then it becomes difficult to separate the code being controlled from the rest.
For instance, the following code shows the different. PMD would report on the not recommended approach:
// this is not recommended
if (foo)
x = x+1;
else
x = x-1;
// preferred approach
if (foo) {
x = x+1;
} else {
x = x-1;
}
Avoid using ‘for’ statements without using surrounding braces. If the code formatting or indentation is lost then it becomes difficult to separate the code being controlled from the rest.
For instance, the following code shows the different. PMD would report on the not recommended approach:
for (int i = 0; i < 42; i++) // not recommended
foo();
for (int i = 0; i < 42; i++) { // preferred approach
foo();
}
When accessing a private field / method from another class, the Java compiler will generate an accessor method with package-private visibility. This adds overhead, and to the dex method count on Android. This situation can be avoided by changing the visibility of the field / method from private to package-private.
For instance, it would report violations on code such as:
public class OuterClass {
private int counter;
/* package */ int id;
public class InnerClass {
InnerClass() {
OuterClass.this.counter++; // wrong, accessor method will be generated
}
public int getOuterClassId() {
return OuterClass.this.id; // id is package-private, no accessor method needed
}
}
}
This new rule is part of the java-design
ruleset.
The Java rule UnnecessaryLocalBeforeReturn
(ruleset
java-design) now has a new property statementOrderMatters
.
It is enabled by default to stay backwards compatible. But if this
property is set to false
, this rule no longer requires the
variable declaration and return statement to be on consecutive lines.
Any variable that is used solely in a return statement will be
reported.
The Java rule UseLocaleWithCaseConversions
(ruleset
java-design) has been modified, to detect calls to
toLowerCase
and to toUpperCase
also within
method call chains. This leads to more detected cases and potentially
new false positives. See also bugfix
#1556.
The Java rule AvoidConstantsInterface
(ruleset
java-design) has been removed. It is completely replaced by the rule
ConstantsInInterface
.
The Java rule UnusedModifier
(ruleset
java-unusedcode) has been moved to the ruleset java-unnecessary and has
been renamed to UnnecessaryModifier
. Additionally, it has
been expanded to consider more redundant modifiers:
abstract
.static
.public
.public
or static
.static
.The Java rule JUnitTestsShouldIncludeAssert
(ruleset
java-junit) now accepts usage of @Rule
ExpectedException
to set expectations on exceptions, and
are considered as valid assertions.
It is now possible to allow CPD suppression through comments in
Java. You tell CPD to ignore the following code with a
comment containin CPD-OFF
and with CPD-ON
you
tell CPD to resume analysis. The old approach via
@SuppressWarnings
annotation is still supported, but is
considered deprecated, since it is limited to locations
where the SuppressWarnings
annotation is allowed. See PR #250.
For example:
public Object someMethod(int x) throws Exception {
// some unignored code
// tell cpd to start ignoring code - CPD-OFF
// mission critical code, manually loop unroll
goDoSomethingAwesome(x + x / 2);
goDoSomethingAwesome(x + x / 2);
goDoSomethingAwesome(x + x / 2);
goDoSomethingAwesome(x + x / 2);
goDoSomethingAwesome(x + x / 2);
goDoSomethingAwesome(x + x / 2);
// resume CPD analysis - CPD-ON
// further code will *not* be ignored
}
CPD now supports the command line option --filelist
.
With that, you can specify a file, which contains the names and paths of
the files, that should be analyzed. This is similar to PMD’s filelist
option. You need to use this, if you have a large project with many
files, and you hit the command line length limit.
ResultSet
(false negative)net.sourceforge.pmd.RuleSetFactory
is now immutable and
its behavior cannot be changed anymore. It provides constructors to
create new adjusted instances. This allows to avoid synchronization in
RuleSetFactory. See PR
#131.net.sourceforge.pmd.RuleSet
is now immutable, too, and
can only be created via RuleSetFactory
. See PR #145.net.sourceforge.pmd.cli.XPathCLI
has been removed. It’s
functionality is fully covered by the Designer.net.sourceforge.pmd.Report
now works with
ThreadSafeReportListener
s. Both ReportListener
and SynchronizedReportListener
are deprecated in favor of
net.sourceforge.pmd.ThreadSafeReportListener
. Therefore,
the methods getSynchronizedListeners()
and
addSynchronizedListeners(...)
have been replaced by
getListeners()
and addListeners(...)
. See PR #193.The PMD team is pleased to announce PMD 5.5.7.
This is a bug fixing release.
The PMD team is pleased to announce PMD 5.5.6.
This is a bug fixing release.
The PMD team is pleased to announce PMD 5.5.5.
The PMD team is pleased to announce PMD 5.5.4
When accessing a private field / method from another class, the Java compiler will generate a accessor methods with package-private visibility. This adds overhead, and to the dex method count on Android. This situation can be avoided by changing the visibility of the field / method from private to package-private.
For instance, it would report violations on code such as:
public class OuterClass {
private int counter;
/* package */ int id;
public class InnerClass {
InnerClass() {
OuterClass.this.counter++; // wrong, accessor method will be generated
}
public int getOuterClassId() {
return OuterClass.this.id; // id is package-private, no accessor method needed
}
}
}
This new rule is part of the java-design
ruleset.
UnusedModifier
(ruleset java-unusedcode)
has been expanded to consider more redundant modifiers.
abstract
.static
.public
.public
or static
.static
.UnnecessaryLocalBeforeReturn
(ruleset
java-design) no longer requires the variable declaration and return
statement to be on consecutive lines. Any variable that is used solely
in a return statement will be reported.The PMD team is pleased to announce PMD 5.5.3
The most significant changes are on analysis performance and a whole new Apex Security Rule Set.
Multithread performance has been enhanced by reducing thread-contention on a bunch of areas. This is still an area of work, as the speedup of running multithreaded analysis is still relatively small (4 threads produce less than a 50% speedup). Future releases will keep improving on this area.
Once again, Symbol Table has been an area of great performance improvements. This time we were able to further improve it’s performance by roughly 10% on all supported languages. In Java in particular, several more improvements were possible, improving Symbol Table performance by a whooping 30%, that’s over 5X faster than PMD 5.5.1, when we first started working on it.
Java developers will also appreciate the revamp of
CloneMethodMustImplementCloneable
, making it over 500X
faster, and PreserveStackTrace
which is now 7X faster.
A new ruleset focused on security has been added, consisting of a wide range of rules to detect most common security problems.
The rule makes sure you are using randomly generated IVs and keys for
Crypto
calls. Hard-wiring these values greatly compromises
the security of encrypted data.
For instance, it would report violations on code such as:
public class without sharing Foo {
Blob hardCodedIV = Blob.valueOf('Hardcoded IV 123');
Blob hardCodedKey = Blob.valueOf('0000000000000000');
Blob data = Blob.valueOf('Data to be encrypted');
Blob encrypted = Crypto.encrypt('AES128', hardCodedKey, hardCodedIV, data);
}
The rule validates you are checking for access permissions before a SOQL/SOSL/DML operation. Since Apex runs in system mode not having proper permissions checks results in escalation of privilege and may produce runtime errors. This check forces you to handle such scenarios.
For example, the following code is considered valid:
public class Foo {
public Contact foo(String status, String ID) {
Contact c = [SELECT Status__c FROM Contact WHERE Id=:ID];
// Make sure we can update the database before even trying
if (!Schema.sObjectType.Contact.fields.Name.isUpdateable()) {
return null;
}
c.Status__c = status;
update c;
return c;
}
}
Check to avoid making DML operations in Apex class constructor/init method. This prevents modification of the database just by accessing a page.
For instance, the following code would be invalid:
public class Foo {
public init() {
insert data;
}
public Foo() {
insert data;
}
}
Checks against calling dangerous methods.
For the time being, it reports:
FinancialForce
’s
Configuration.disableTriggerCRUDSecurity()
. Disabling CRUD
security opens the door to several attacks and requires manual
validation, which is unreliable.System.debug
passing sensitive data as
parameter, which could lead to exposure of private data.Checks against accessing endpoints under plain http. You should always use https for security.
Checks against redirects to user-controlled locations. This prevents attackers from redirecting users to phishing sites.
For instance, the following code would be reported:
public class without sharing Foo {
String unsafeLocation = ApexPage.getCurrentPage().getParameters.get('url_param');
PageReference page() {
return new PageReference(unsafeLocation);
}
}
Detect classes declared without explicit sharing mode if DML methods are used. This forces the developer to take access restrictions into account before modifying objects.
Detects the usage of untrusted / unescaped variables in DML queries.
For instance, it would report on:
public class Foo {
public void test1(String t1) {
Database.query('SELECT Id FROM Account' + t1);
}
}
Detects hardcoded credentials used in requests to an endpoint.
You should refrain from hardcoding credentials: * They are hard to mantain by being mixed in application code * Particularly hard to update them when used from different classes * Granting a developer access to the codebase means granting knowledge of credentials, keeping a two-level access is not possible. * Using different credentials for different environments is troublesome and error-prone.
Instead, you should use Named Credentials and a callout endpoint.
For more information, you can check this
Reports on calls to addError
with disabled escaping. The
message passed to addError
will be displayed directly to
the user in the UI, making it prime ground for XSS attacks if
unescaped.
Makes sure that all values obtained from URL parameters are properly escaped / sanitized to avoid XSS attacks.
The Java rule “UseLocaleWithCaseConversions” (ruleset java-design)
has been modified, to detect calls to toLowerCase
and to
toUpperCase
also within method call chains. This leads to
more detected cases and potentially new false positives. See also bugfix #1556.
ResultSet
(false negative)net.sourceforge.pmd.RuleSetFactory
is now immutable and
its behavior cannot be changed anymore. It provides constructors to
create new adjusted instances. This allows to avoid synchronization in
RuleSetFactory. See PR
#131.Summary:
New Supported Languages:
Feature Requests and Improvements:
New Rules:
Pull Requests:
Bugfixes:
New Rules:
Pull Requests:
Bugfixes:
System requirements:
PMD and CPD need at least a java7 runtime environment. For analyzing Salesforce.com Apex source code, you’ll need a java8 runtime environment.
New Supported Languages:
New and modified Rules:
serialVersionUIDCommentRequired
which controls the comment
requirements for serialVersionUID fields. By default, no
comment is required for this field.if
block contains a
return. Then the content of the else block can be put outside. See #1486.Improvements and CLI changes:
--ignore-usings
: Ignore
using directives in C# when comparing text.-norulesetcompatibility
- this disables the ruleset factory
compatibility filter and fails, if e.g. an old rule name is used in the
ruleset. See also #1360. This option
is also available for the ant task:
<noRuleSetCompatibility>true</noRuleSetCompatibility>
.-filelist
- this
provides an alternative way to define, which files should be process by
PMD. With this option, you can provide the path to a single file
containing a comma delimited list of files to analyze. If this is given,
then you don’t need to provide -dir
. See PR#98.Pull Requests:
Bugfixes:
The PMD team is pleased to announce PMD 5.4.6.
This is a bug fixing release.
The PMD team is pleased to announce PMD 5.4.5
This is a bug fixing release.
UnusedModifier
(ruleset java-unusedcode)
has been expanded to consider more redundant modifiers.
abstract
.static
.public
.public
or static
.static
.The PMD team is pleased to announce PMD 5.4.4
This is a bug fixing release. The most significant changes are on analysis performance.
Multithread performance has been enhanced by reducing thread-contention on a bunch of areas. This is still an area of work, as the speedup of running multithreaded analysis is still relatively small (4 threads produce less than a 50% speedup). Future releases will keep improving on this area.
Once again, Symbol Table has been an area of great performance improvements. This time we were able to further improve it’s performance by roughly 10% on all supported languages. In Java in particular, several more improvements were possible, improving Symbol Table performance by a whooping 30%, that’s over 5X faster than PMD 5.4.2, when we first started working on it.
Java developers will also appreciate the revamp of
CloneMethodMustImplementCloneable
, making it over 500X
faster, and PreserveStackTrace
which is now 7X faster.
This is a bug fixing release, no major changes were introduced.
The Java rule “UseLocaleWithCaseConversions” (ruleset java-design)
has been modified, to detect calls to toLowerCase
and to
toUpperCase
also within method call chains. This leads to
more detected cases and potentially new false positives. See also bugfix #1556.
ResultSet
(false negative)Summary:
Pull Requests:
Bugfixes:
New Supported Languages:
Feature Request and Improvements:
Modified Rules:
Pull Requests:
Bugfixes:
CLI Changes:
-norulesetcompatibility
- this disables the ruleset factory
compatibility filter and fails, if e.g. an old rule name is used in the
ruleset. See also #1360. This option
is also available for the ant task:
<noRuleSetCompatibility>true</noRuleSetCompatibility>
.Feature Request and Improvements:
--ignore-usings
: Ignore
using directives in C# when comparing text.Modified Rules:
serialVersionUIDCommentRequired
which controls the comment
requirements for serialVersionUID fields. By default, no
comment is required for this field.Pull Requests:
Bugfixes:
Note: PMD 5.4.0 requires JDK 1.7 or above.
Summary:
Feature Request and Improvements:
failOnViolation
. Executing PMD with the option
-failOnViolation false
will perform the PMD checks but
won’t fail the build and still exit with status 0. This is useful if you
only want to generate the report with violations but don’t want to fail
your build.New Rules:
Java:
Basic: SimplifiedTernary
(rulesets/java/basic.xml/SimplifiedTernary)
Ternary operator with a
boolean literal can be simplified with a boolean expression.
Clone: CloneMethodMustBePublic
(rulesets/java/clone.xml/CloneMethodMustBePublic)
The java manual
says “By convention, classes that implement the Cloneable
interface should override Object.clone
(which is protected)
with a public method.”
Clone: CloneMethodReturnTypeMustMatchClassName
(rulesets/java/clone.xml/CloneMethodReturnTypeMustMatchClassName)
If a class implements Cloneable
the return type of the
method clone()
must be the class name.
Comments: CommentDefaultAccessModifier
(rulesets/java/comments.xml/CommentDefaultAccessModifier)
In order
to avoid mistakes with forgotten access modifiers for methods, this rule
ensures, that you explicitly mark the usage of the default access
modifier by placing a comment.
Design: SingletonClassReturningNewInstance
(rulesets/java/design.xml/SingletonClassReturningNewInstance)
Verifies that the method called getInstance
returns a
cached instance and not always a fresh, new instance.
Design: SingleMethodRule
(rulesets/java/design.xml/SingleMethodSingletonRule)
Verifies that
there is only one method called getInstance
. If there are
more methods that return the singleton, then it can easily happen, that
these are not the same instances - and thus no singleton.
Unnecessary: UselessQualifiedThis
(rulesets/java/unnecessary.xml/UselessQualifiedThis)
Flags
unnecessary qualified usages of this, when this
alone would
be unique. E.g. use just this
instead of
Foo.this
.
Maven POM: (The rules can be found in the pmd-xml module)
Basic: ProjectVersionAsDependencyVersion
(rulesets/pom/basic.xml/ProjectVersionAsDependencyVersion)
Checks
the usage of ${project.version}
in Maven POM
files.
Basic: InvalidDependencyTypes
(rulesets/pom/basic.xml/InvalidDependencyTypes)
Verifies that only
the default types (jar, war, …) for dependencies are used.
Ruleset snippet to activate the new rules:
<rule ref="rulesets/java/basic.xml/SimplifiedTernary"/>
<rule ref="rulesets/java/clone.xml/CloneMethodReturnTypeMustMatchClassName"/>
<rule ref="rulesets/java/clone.xml/CloneMethodMustBePublic"/>
<rule ref="rulesets/java/comments.xml/CommentDefaultAccessModifier"/>
<rule ref="rulesets/java/design.xml/SingleMethodSingleton"/>
<rule ref="rulesets/java/design.xml/SingletonClassReturningNewInstance"/>
<rule ref="rulesets/java/unnecessary.xml/UselessQualifiedThis"/>
<rule ref="rulesets/pom/basic.xml/ProjectVersionAsDependencyVersion"/>
<rule ref="rulesets/pom/basic.xml/InvalidDependencyTypes"/>
Modified Rules:
Java
Basic: CheckResultSet
(rulesets/java/basic.xml/CheckResultSet)
Do not require to check
the result of a navigation method, if it is returned.
JUnit: UseAssertTrueInsteadOfAssertEquals
(rulesets/java/junit.xml/UseAssertTrueInsteadOfAssertEquals)
This
rule also flags assertEquals, that use Boolean.TRUE/FALSE
constants.
Naming: AbstractNaming
(rulesets/java/naming.xml/AbstractNaming)
By default, this rule
flags now classes, that are named “Abstract” but are not abstract. This
behavior can be disabled by setting the new property strict
to false.
Naming: ShortMethodName
(rulesets/java/naming.xml/ShortMethodName)
Additional property
minimum
to configure the minimum required length of a
method name.
Naming: ShortVariable
(rulesets/java/naming.xml/ShortVariable)
Additional property
minimum
to configure the minimum required length of a
variable name.
UnusedCode: UnusedPrivateField
(rulesets/java/unusedcode.xml/UnusedPrivateField)
This rule won’t
trigger anymore if Lombok is in
use. See #1420.
Renamed Rules:
Removed Rules:
Basic: The following rules of ruleset “Basic” were marked as
deprecated and are removed with this release now:
EmptyCatchBlock, EmptyIfStatement, EmptyWhileStmt, EmptyTryBlock,
EmptyFinallyBlock, EmptySwitchStatements, EmptySynchronizedBlock,
EmptyStatementNotInLoop, EmptyInitializer, EmptyStatementBlock,
EmptyStaticInitializer
UnnecessaryConversionTemporary,
UnnecessaryReturn, UnnecessaryFinalModifier, UselessOverridingMethod,
UselessOperationOnImmutable, UnusedNullCheckInEquals, UselessParentheses
These rules are still available in the rulesets “Empty”
(rulesets/java/empty.xml) and “Unnecessary”
(rulesets/java/unnecessary.xml) respectively.
Design: The rule “UncommentedEmptyMethod” has been renamed last release to “UncommentedEmptyMethodBody”. The old rule name reference has been removed with this release now.
Controversial: The rule “BooleanInversion” has been deprecated last release and has been removed with this release completely.
Pull Requests:
Bugfixes:
API Changes:
pmd requires now JDK 1.7 or above.
pmd-core:
net.sourceforge.pmd.lang.symboltable.Scope
:
The method addNameOccurrence
returns now a Set of
NameDeclarations to which the given occurrence has been added. This is
useful in case there are ambiguous declarations of methods.
pmd-core:
net.sourceforge.pmd.lang.symboltable.AbstractScope
:
The method findVariableHere
returns now a Set of
NameDeclarations which match the given occurrence. This is useful in
case there are ambiguous declarations of methods.
Summary
Feature Requests and Improvements:
Pull Requests:
Bugfixes:
API Changes:
-norulesetcompatibility
- this disables the ruleset factory
compatibility filter and fails, if e.g. an old rule name is used in the
ruleset. See also #1360. This option
is also available for the ant task:
<noRuleSetCompatibility>true</noRuleSetCompatibility>
.New Supported Languages:
Feature Request and Improvements:
Modified Rules:
Pull Requests:
Bugfixes:
CLI Changes:
Feature Request and Improvements:
--ignore-usings
: Ignore
using directives in C# when comparing text.Modified Rules:
serialVersionUIDCommentRequired
which controls the comment
requirements for serialVersionUID fields. By default, no
comment is required for this field.Pull Requests:
Bugfixes:
Modified Rules:
close
itself is always considered as a
closeTarget - no matter whether it is configured with the
closeTargets property or not.Pull Requests:
Bugfixes:
Bugfixes:
Pull Requests:
Bugfixes:
Bugfixes:
New/Modified/Deprecated Rules:
Pull Requests:
Bugfixes:
New Supported Languages:
Feature Requests and Improvements:
4
if any violations have been
found. This behavior has been introduced to ease PMD integration into
scripts or hooks, such as SVN hooks.New/Modified/Deprecated Rules:
The following rules have been enhanced :
The following rules are marked as deprecated and will be removed with the next release of PMD.
Language Java, ruleset basic.xml: The following rules have been
moved into the empty.xml
ruleset. You’ll need to
enable the “empty” ruleset explicitly from now on, if you want to have
these rules executed:
EmptyCatchBlock, EmptyIfStatement, EmptyWhileStmt, EmptyTryBlock, EmptyFinallyBlock, EmptySwitchStatements, EmptySynchronizedBlock, EmptyStatementNotInLoop, EmptyInitializer, EmptyStatementBlock, EmptyStaticInitializer.
Language Java, ruleset basic.xml: The following rules have been
moved into the unnecessary.xml
ruleset. You’ll
need to enable the “unnecessary” ruleset explicitly from now on, if you
want to have these rules executed:
UnnecessaryConversionTemporary, UnnecessaryReturn, UnnecessaryFinalModifier, UselessOverridingMethod, UselessOperationOnImmutable, UnusedNullCheckInEquals, UselessParentheses.
Language Java, ruleset design.xml: The rule “UncommentedEmptyMethod” has been renamed to “UncommentedEmptyMethodBody”. See also bug #1283.
Language Java, ruleset controversial.xml: The rule “BooleanInversion” is deprecated and will be removed with the next release. See #1277 for more details.
Pull Requests:
csv_with_linecount_per_file
which
outputs the correct line count per file.Bugfixes:
API Changes:
net.sourceforge.pmd.cpd.Match.iterator()
now returns
an iterator of the new type net.sourceforge.pmd.cpd.Mark
instead of TokenEntry. A Mark
contains all the informations
about each single duplication, including the TokenEntry via
Mark.getToken()
. This Mark is useful for reporting the
correct line count for each duplication. Previously only one line count
was available. As for some languages CPD can be instructed to ignore
comments, the line count could be different in the different files for
the same duplication.
pmd-test: The utility class StreamUtil
is
deprecated. Just use Apache Commons IO Utils instead.
Feature Requests and Improvements:
Modified Rules:
byte[]
is used as the last
argument, it is ignored and no violation will be reported.checkNativeMethods
checkNativeMethodParameters
Pull requests:
Bugfixes:
New Parameters for CPD:
For the language cpp, the following new parameters are supported:
--no-skip-blocks
: Disables skipping of code blocks like
a pre-processor. This is by default enabled.--skip-blocks-pattern
: Pattern to find the blocks to
skip. Start and End pattern separated by “|
”. Default value
is “#if 0|#endif
”.Bugfixes:
Bugfixes:
Modularization of the source code:
The source code of pmd was undergoing a major restructuring. Each language is separated out into its own module. This reduces the size of the artifacts significantly, if only one language is needed. It also makes it easier, to add new languages as extensions.
Therefore, the maven coordinates needed to change. In order to just use pmd with java support, you’ll need the following two dependencies:
<dependency>
<groupId>net.sourceforge.pmd</groupId>
<artifactId>pmd-core</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>net.sourceforge.pmd</groupId>
<artifactId>pmd-java</artifactId>
<version>5.2.0</version>
</dependency>
The binary package still contains all languages and can be used as usual. Have a look at the central repository for available modules.
New Languages
Pull requests:
New/Modified Rules:
Bugfixes:
Feature Requests and Improvements:
New/Modified Rules:
ignoreAnonymousClassDeclarations
:
Ignore Field Declarations, that are initialized with anonymous class
declarations. This property is enabled by default. See feature #1244.minimum
: Number of characters that are required as a
minimum for a class name. By default, 5 characters are required - if the
class name is shorter, a violation will be reported. See feature #1232.Bugfixes:
Feature Requests and Improvements:
Pull requests:
New Rules:
Bugfixes:
CPD Changes:
New/Updated Languages:
New/Updated Rulesets and Rules:
Bugfixes:
http://sourceforge.net/p/pmd/bugs/milestone/PMD-5.1.0/
CPD Changes: - Command Line - Added non-recursive option “–non-recursive” to not scan sub-directories - Added option “–exclude” to exclude specific files from being scanned (thanks to Delmas for patch #272) - CPD is now thread-safe, so that multiple instances of CPD can run concurrently without stepping on each other (eg: multi-module Maven projects.). Thanks to David Golpira.
Miscellaneous:
API Changes
Fixed bug 991: AvoidSynchronizedAtMethodLevel for static methods
Fixed bug 1084: NPE at UselessStringValueOfRule.java:36
Fixed bug 1091: file extension for fortran seems to be wrong in cpdgui tools
Fixed bug 1092: Wrong Attribute "excludemarker" in Ant Task Documentation
Fixed bug 1095: AvoidFinalLocalVariable false positive
Fixed bug 1099: UseArraysAsList false positives
Fixed bug 1102: False positive: shift operator parenthesis
Fixed bug 1104: IdempotentOperation false positive
Fixed bug 1107: PMD 5.0.4 couldn't parse call of parent outer java class method from inner class
Fixed bug 1069: Eclipse plugin does not accept project-local config
Fixed bug 1111: False positive: Useless parentheses
Fixed bug 1114: CPD - Tokenizer not initialized with requested properties
Fixed bug 1118: ClassCastException in pmd.lang.ecmascript.ast.ASTElementGet
Fixed bug 254: False+ : UnusedImport with Javadoc @throws
Fixed bug 794: False positive on PreserveStackTrace with anonymous inner
Fixed bug 1063: False+: ArrayIsStoredDirectly
Fixed bug 1080: net.sourceforge.pmd.cpd.CPDTest test failing
Fixed bug 1081: Regression: CPD skipping all files when using relative paths
Fixed bug 1082: CPD performance issue on larger projects
Fixed bug 1085: NullPointerException by at net.sourceforge.pmd.lang.java.rule.design.GodClassRule.visit(GodClassRule.java:313)
Fixed bug 1086: Unsupported Element and Attribute in Ant Task Example
Fixed bug 1087: PreserveStackTrace (still) ignores initCause()
Fixed bug 1089: When changing priority in a custom ruleset, violations reported twice
Fixed bug 938: False positive on LooseCoupling for overriding methods
Fixed bug 940: False positive on UnsynchronizedStaticDateFormatter
Fixed bug 942: CheckResultSet False Positive and Negative
Fixed bug 943: PreserveStackTrace false positive if a StringBuffer exists
Fixed bug 945: PMD generates RuleSets it cannot read.
Fixed bug 958: Intermittent NullPointerException while loading XPath node attributes
Fixed bug 968: Issues with JUnit4 @Test annotation with expected exception (Thanks to Yiannis Paschalidis)
Fixed bug 975: false positive in ClassCastExceptionWithToArray
Fixed bug 976: UselessStringValueOf wrong when appending character arrays
Fixed bug 977: MisplacedNullCheck makes false positives
Fixed bug 984: Cyclomatic complexity should treat constructors like methods
Fixed bug 985: Suppressed methods shouldn't affect avg CyclomaticComplexity
Fixed bug 992: Class java.beans.Statement triggered in CloseResource rule
Fixed bug 997: Rule NonThreadSafeSingleton gives analysis problem
Fixed bug 999: Law of Demeter: False positives and negatives
Fixed bug 1002: False +: FinalFieldCouldBeStatic on inner class
Fixed bug 1005: False + for ConstructorCallsOverridableMethod - overloaded methods
Fixed bug 1027: PMD Ant: java.lang.ClassCastException
Fixed bug 1032: ImmutableField Rule: Private field in inner class gives false positive
Fixed bug 1064: Exception running PrematureDeclaration
Fixed bug 1068: CPD fails on broken symbolic links
Fixed bug 1073: Hard coded violation messages CommentSize
Fixed bug 1074: rule priority doesn't work on group definitions
Fixed bug 1076: Report.treeIterator() does not return all violations
Fixed bug 1077: Missing JavaDocs for Xref-Test Files
Fixed bug 1078: Package statement introduces false positive UnnecessaryFullyQualifiedName violation
Merged pull request #14: fix Nullpointer Exception when using -l jsp
Fixed bug 878: False positive: UnusedFormalParameter for abstract methods
Fixed bug 913: SignatureDeclareThrowsException is raised twice
Fixed bug 947: CloseResource rule fails if field is marked with annotation
Fixed bug 1004: targetjdk isn't attribute of PMD task
Fixed bug 1007: Parse Exception with annotation
Fixed bug 1011: CloseResource Rule ignores Constructors
Fixed bug 1012: False positive: Useless parentheses.
Fixed bug 1020: Parsing Error
Fixed bug 1026: PMD doesn't handle 'value =' in SuppressWarnings annotation
Fixed bug 1028: False-positive: Compare objects with equals for Enums
Fixed bug 1030: CPD Java.lang.IndexOutOfBoundsException: Index:
Fixed bug 1037: Facing a showstopper issue in PMD Report Class (report listeners)
Fixed bug 1039: pmd-nicerhtml.xsl is packaged in wrong location
Fixed bug 1043: node.getEndLine() always returns 0 (ECMAscript)
Fixed bug 1044: Unknown option: -excludemarker
Fixed bug 1046: ant task CPDTask doesn't accept ecmascript
Fixed bug 1047: False Positive in 'for' loops for LocalVariableCouldBeFinal in 5.0.1
Fixed bug 1048: CommentContent Rule, String Index out of range Exception
Fixed bug 1049: Errors in "How to write a rule"
Fixed bug 1055: Please add a colon in the ant output after line,column for Oracle JDeveloper IDE usage
Fixed bug 1056: "Error while processing" while running on xml file with DOCTYPE reference
Fixed bug 1060: GodClassRule >>> wrong method
Fixed bug 820: False+ AvoidReassigningParameters
Fixed bug 1008: pmd-5.0.0: ImmutableField false positive on self-inc/dec
Fixed bug 1009: pmd-5.0.0: False + UselessParentheses
Fixed bug 1003: newline characters stripped from CPD data in PMD 5.0.0
Fixed bug 1001: InsufficientStringBufferDeclaration fails to parse hex
Fixed bug 522: InefficientStringBuffering bug false +
Fixed bug 953: String.InefficientStringBuffering false +
Fixed bug 981: Unable to parse
Fixed bug 1010: pmd: parsing of generic method call with super fails
Fixed bug 996: pmd-4.2.6: MissingBreakInSwitch fails to report violation
Fixed bug 993: Invalid NPath calculation in return statement. Thanks to Prabhjot Singh for the patch.
Fixed bug 1023: c/c++ \ as a continuation character not supported
Fixed bug 1033: False+ : SingularField
Fixed bug 1025: Regression of Crash in PMDTask due to multithreading (Eclipse and Java 1.5)
Fixed bug 1017: Type resolution very slow for big project. Thanks to Roman for the patch.
Fixed bug 1036: Documentation: default threshold values removed from v5.0
Fixed bug 1035: UseObjectForClearerAPI has misspelled message
Fixed bug 1031: false DontImportJavaLang
Fixed bug 1034: UseConcurrentHashMap flags calls to methods that return Map
Fixed bug 1006: Problem with implementation of getPackageNameImage method
Fixed bug 1014: AvoidLiteralsInIfCondition must NOT consider null
Fixed bug 1013: jnlp link for CPD is wrong
PMD Command Line Changes:
Improved command line interface (CLI) parsing using JCommander.
Note: this breaks compatibility, but should be easy to fix.
With "-d" you specify nowtThe source files / source directory to be scanned.
With "-f" you select the report format (like text, html, ...)
With "-R" you select the rulesets to be used.
Example: pmd -d c:\data\pmd\pmd\test-data\Unused1.java -f xml -R rulesets/java/unusedcode.xml
Improved JSP parser to be less strict with not valid XML documents (like HTML). Thanks to Victor Bucutea.
Fixed bgastviewer not working. Thanks to Victor Bucutea.
Improved CPD: Support in CPD for IgnoreAnnotations and SuppressWarnings("CPD-START"). Thanks to Matthew Short.
Fixed C# support for CPD - thanks to TIOBE Software.
New Ecmascript rules:
Basic ruleset: AvoidTrailingComma
Fixed bug 3515487: Inconsistent reference to ruleset file in documentation
Fixed bug 3470274: Using Label for lines in XMLRenderer
Fixed bug 3175710: NPE in InsufficientStringBufferDeclaration
CPD:
- Exit with status code 4 when CPD detects code duplication (Patch ID: 3497021)
This version of PMD breaks API compatibility with prior versions of PMD, as well
as RuleSet XML compatibility. Also the maven coordinates (groupId) have been changed.
The decision to break compatibility, allows PMD
internals and code organization to be improved to better handle additional
languages. This opportunity was used to remove depreciated APIs, and beat up
any code which has thumbed its nose at the developers over the years. ;)
The following is relatively complete list of the major changes (this may not be
100% accurate, see actual source code when in doubt):
Fixed bug (no number) - Fixed UseStringBufferLengthRule only worked once per class
All StringBuffer-related rules now also catch StringBuilder-related issues in the same way
API Change - Unification of treatment of languages within PMD core:
Added - net.sourceforge.pmd.lang.Language (now an 'enum')
Added - net.sourceforge.pmd.lang.LanguageVersion
Added - net.sourceforge.pmd.lang.LanguageVersionDiscoverer
Added - net.sourceforge.pmd.lang.LanguageVersionHandler
Added - net.sourceforge.pmd.lang.XPathHandler
Added - net.sourceforge.pmd.lang.ast.xpath.AbstractASTXPathHandler
Added - net.sourceforge.pmd.lang.xpath.Initializer
Added - net.sourceforge.pmd.lang.ast.AbstractTokenManager
Added - net.sourceforge.pmd.lang.ast.CharStream
Added - net.sourceforge.pmd.lang.ast.JavaCharStream
Added - net.sourceforge.pmd.lang.ast.SimpleCharStream
Added - net.sourceforge.pmd.lang.ast.TokenMgrError
Added - net.sourceforge.pmd.lang.rule.stat.StatisticalRule
Added - net.sourceforge.pmd.lang.rule.stat.StatisticalRuleHelper
Added - net.sourceforge.pmd.lang.java.rule.AbstractStatisticalJavaRule
Added - net.sourceforge.pmd.lang.rule.AbstractRuleViolationFactory
Added - net.sourceforge.pmd.lang.rule.RuleViolationFactory
Added - net.sourceforge.pmd.lang.java.rule.JavaRuleViolationFactory
Added - net.sourceforge.pmd.lang.jsp.rule.JspRuleViolationFactory
Renamed - net.sourceforge.pmd.AbstractRule to net.sourceforge.pmd.lang.rule.AbstractRule
Renamed - net.sourceforge.pmd.AbstractJavaRule to net.sourceforge.pmd.lang.java.rule.AbstractJavaRule
Renamed - net.sourceforge.pmd.AbstractRuleChainVisitor to net.sourceforge.pmd.lang.rule.AbstractRuleChainVisitor
Renamed - net.sourceforge.pmd.RuleChainVisitor to net.sourceforge.pmd.lang.rule.RuleChainVisitor
Renamed - net.sourceforge.pmd.SourceFileSelector to net.sourceforge.pmd.lang.rule.LanguageFilenameFilter
Renamed - net.sourceforge.pmd.rule.XPathRule to net.sourceforge.pmd.lang.rule.XPathRule
Renamed - net.sourceforge.pmd.jsp.rule.AbstractJspRule to net.sourceforge.pmd.lang.jsp.rule.AbstractJspRule
Renamed - net.sourceforge.pmd.ast.CompilationUnit to net.sourceforge.pmd.lang.ast.RootNode
Renamed - net.sourceforge.pmd.ast.JavaRuleChainVisitor to net.sourceforge.pmd.lang.java.rule.JavaRuleChainVisitor
Renamed - net.sourceforge.pmd.jsp.ast.JspRuleChainVisitor to net.sourceforge.pmd.lang.jsp.rule.JspRuleChainVisitor
Renamed - net.sourceforge.pmd.parser.Parser to net.sourceforge.pmd.lang.Parser
Renamed - net.sourceforge.pmd.parser.TokenManager to net.sourceforge.pmd.lang.TokenManager
Renamed - net.sourceforge.pmd.parser.* into net.sourceforge.pmd.lang.{Language}
Renamed - net.sourceforge.pmd.sourcetypehandlers.SourceTypeHandler to net.sourceforge.pmd.lang.LanguageVersionHandler
Renamed - net.sourceforge.pmd.sourcetypehandlers.VisitorStarter to net.sourceforge.pmd.lang.VisitorStarter
Renamed - net.sourceforge.pmd.sourcetypehandlers.* into net.sourceforge.pmd.lang.{Language}
Renamed - net.sourceforge.pmd.stat.StatisticalRule to net.sourceforge.pmd.lang.rule.StatisticalRuleHelper
Renamed - net.sourceforge.pmd.jaxen.TypeOfFunction to net.sourceforge.pmd.lang.java.xpath.TypeOfFunction
Renamed - net.sourceforge.pmd.jaxen.MatchesFunction to net.sourceforge.pmd.lang.xpath.MatchesFunction
Renamed - net.sourceforge.pmd.jaxen.Attribute to net.sourceforge.pmd.lang.ast.xpath.Attribute
Renamed - net.sourceforge.pmd.jaxen.AttributeAxisIterator to net.sourceforge.pmd.lang.ast.xpath.AttributeAxisIterator
Renamed - net.sourceforge.pmd.jaxen.DocumentNavigator to net.sourceforge.pmd.lang.ast.xpath.DocumentNavigator
Renamed - net.sourceforge.pmd.jaxen.NodeIterator to net.sourceforge.pmd.lang.ast.xpath.NodeIterator
Renamed - net.sourceforge.pmd.ast.* into net.sourceforge.pmd.lang.java.ast.*
Renamed - net.sourceforge.pmd.rules.* into net.sourceforge.pmd.lang.java.rule.* and updated to follow conventions
Renamed - net.sourceforge.pmd.jsp.ast.* into net.sourceforge.pmd.lang.jsp.ast.*
Renamed - net.sourceforge.pmd.jsp.rules.* into net.sourceforge.pmd.lang.jsp.ast.rule.* and updated to follow conventions
Deleted - net.sourceforge.pmd.cpd.cppast.* into net.sourceforge.pmd.lang.cpp.ast.*
Deleted - net.sourceforge.pmd.CommonAbstractRule
Deleted - net.sourceforge.pmd.SourceFileConstants
Deleted - net.sourceforge.pmd.SourceType
Deleted - net.sourceforge.pmd.SourceTypeDiscoverer
Deleted - net.sourceforge.pmd.SourceTypeToRuleLanguageMapper
Deleted - net.sourceforge.pmd.TargetJDK1_3
Deleted - net.sourceforge.pmd.TargetJDK1_4
Deleted - net.sourceforge.pmd.TargetJDK1_5
Deleted - net.sourceforge.pmd.TargetJDK1_6
Deleted - net.sourceforge.pmd.TargetJDK1_7
Deleted - net.sourceforge.pmd.TargetJDKVersion
Deleted - net.sourceforge.pmd.cpd.SourceFileOrDirectoryFilter
Deleted - net.sourceforge.pmd.sourcetypehandlers.SourceTypeHandlerBroker
Deleted - net.sourceforge.pmd.ast.JavaCharStream
Deleted - net.sourceforge.pmd.ast.CharStream
Deleted - net.sourceforge.pmd.ast.TokenMgrError
Deleted - net.sourceforge.pmd.jsp.ast.JspCharStream
Deleted - net.sourceforge.pmd.jsp.ast.TokenMgrError
API Change - Generalize RuleViolation treatment
Renamed - net.sourceforge.pmd.IRuleViolation to net.sourceforge.pmd.RuleViolation
Renamed - net.sourceforge.pmd.RuleViolation to net.sourceforge.pmd.lang.rule.AbstractRuleViolation
Added - net.sourceforge.pmd.RuleViolationComparator
Added - net.sourceforge.pmd.lang.java.rule.JavaRuleViolation
Added - net.sourceforge.pmd.lang.jsp.rule.JspRuleViolation
API Change - Generalize DFA treatment
Renamed - net.sourceforge.pmd.dfa.IDataFlowNode to net.sourceforge.pmd.lang.dfa.DataFlowNode
Renamed - net.sourceforge.pmd.dfa.DataFlowNode to net.sourceforge.pmd.lang.dfa.AbstractDataFlowNode
Renamed - net.sourceforge.pmd.dfa.Linker to net.sourceforge.pmd.lang.dfa.Linker
Renamed - net.sourceforge.pmd.dfa.LinkerException to net.sourceforge.pmd.lang.dfa.LinkerException
Renamed - net.sourceforge.pmd.dfa.NodeType to net.sourceforge.pmd.lang.dfa.NodeType
Renamed - net.sourceforge.pmd.dfa.StackObject to net.sourceforge.pmd.lang.dfa.StackObject
Renamed - net.sourceforge.pmd.dfa.SequenceChecker to net.sourceforge.pmd.lang.dfa.SequenceChecker
Renamed - net.sourceforge.pmd.dfa.SequenceException to net.sourceforge.pmd.lang.dfa.SequenceException
Renamed - net.sourceforge.pmd.dfa.StartOrEndDataFlowNode to net.sourceforge.pmd.lang.dfa.StartOrEndDataFlowNode
Renamed - net.sourceforge.pmd.dfa.Structure to net.sourceforge.pmd.lang.dfa.Structure
Renamed - net.sourceforge.pmd.dfa.variableaccess.VariableAccess to net.sourceforge.pmd.lang.dfa.VariableAccess
Renamed - net.sourceforge.pmd.dfa.variableaccess.VariableAccessException to net.sourceforge.pmd.lang.dfa.VariableAccessException
Renamed - net.sourceforge.pmd.dfa.pathfinder.* to net.sourceforge.pmd.lang.dfa.pathfinder.*
Renamed - net.sourceforge.pmd.dfa.report.* to net.sourceforge.pmd.lang.dfa.report.*
Renamed - net.sourceforge.pmd.dfa.DaaRuleViolation to net.sourceforge.pmd.lang.java.dfa.DaaRuleViolation
Renamed - net.sourceforge.pmd.dfa.DataFlowFacade to net.sourceforge.pmd.lang.java.dfa.DataFlowFacade
Renamed - net.sourceforge.pmd.dfa.StatementAndBraceFinder to net.sourceforge.pmd.lang.java.dfa.StatementAndBraceFinder
Renamed - net.sourceforge.pmd.dfa.variableaccess.VariableAccessVisitor to net.sourceforge.pmd.lang.java.dfa.VariableAccessVisitor
Added - net.sourceforge.pmd.lang.java.dfa.JavaDataFlowNode
Added - net.sourceforge.pmd.lang.DataFlowHandler
API Change - Generalize Symbol Table treatement
Deleted - net.sourceforge.pmd.symboltable.JspSymbolFacade
Deleted - net.sourceforge.pmd.symboltable.JspScopeAndDeclarationFinder
Renamed - net.sourceforge.pmd.symboltable.* to net.sourceforge.pmd.lang.java.symboltable.*
API Change - Generalize Type Resolution treatment
Renamed - net.sourceforge.pmd.typeresolution.* to net.sourceforge.pmd.lang.java.typeresolution.*
API Change - Generalize Property Descriptor treatment
Renamed - net.sourceforge.pmd.properties.* to net.sourceforge.pmd.lang.rule.properties.*
Renamed - net.sourceforge.pmd.properties.AbstractPMDProperty to net.sourceforge.pmd.lang.rule.properties.AbstractProperty
Changed - net.sourceforge.pmd.properties.PropertyDescriptor to use Generics, and other changes
Added - net.sourceforge.pmd.lang.rule.properties.* new types and other API changes
API Change - Generalize AST treatment
Added - net.sourceforge.pmd.lang.ast.Node (interface extracted from old Node/SimpleNode)
Added - net.sourceforge.pmd.lang.ast.AbstractNode
Added - net.sourceforge.pmd.ast.DummyJavaNode
Added - net.sourceforge.pmd.jsp.ast.AbstractJspNode
Added - net.sourceforge.pmd.jsp.ast.JspNode
Renamed - net.sourceforge.pmd.ast.SimpleJavaNode to net.sourceforge.pmd.ast.AbstractJavaNode
Renamed - net.sourceforge.pmd.ast.SimpleJavaTypeNode to net.sourceforge.pmd.ast.AbstractJavaTypeNode
Renamed - net.sourceforge.pmd.ast.SimpleJavaAccessNode to net.sourceforge.pmd.ast.AbstractJavaAccessNode
Renamed - net.sourceforge.pmd.ast.SimpleJavaAccessTypeNode to net.sourceforge.pmd.ast.AbstractJavaAccessTypeNode
Deleted - net.sourceforge.pmd.ast.Node
Deleted - net.sourceforge.pmd.ast.SimpleNode
Deleted - net.sourceforge.pmd.ast.AccessNodeInterface
Deleted - net.sourceforge.pmd.jsp.ast.Node
Deleted - net.sourceforge.pmd.jsp.ast.SimpleNode
API Change - General code reorganization/cleanup
Renamed - net.sourceforge.pmd.AbstractDelegateRule to net.sourceforge.pmd.lang.rule.AbstractDelegateRule
Renamed - net.sourceforge.pmd.MockRule to net.sourceforge.pmd.lang.rule.MockRule
Renamed - net.sourceforge.pmd.RuleReference to net.sourceforge.pmd.lang.rule.RuleReference
Renamed - net.sourceforge.pmd.ScopedLogHandlersManager to net.sourceforge.pmd.util.log.ScopedLogHandlersManager
Renamed - net.sourceforge.pmd.util.AntLogHandler to net.sourceforge.pmd.util.log.AntLogHandler
Renamed - net.sourceforge.pmd.util.ConsoleLogHandler to net.sourceforge.pmd.util.log.ConsoleLogHandler
Renamed - net.sourceforge.pmd.util.PmdLogFormatter to net.sourceforge.pmd.util.log.PmdLogFormatter
API Change - Changes to Rule/RuleSet/RuleSets
Removed - boolean Rule.include()
Removed - void Rule.setInclude(boolean)
Removed - String Rule.getRulePriorityName()
Removed - String Rule.getExample()
Removed - Rule.LOWEST_PRIORITY
Removed - Rule.PRIORITIES
Removed - Properties Rule.getProperties()
Removed - Rule.addProperties(Properties)
Removed - boolean Rule.hasProperty(String)
Removed - RuleSet.applies(Language,Language)
Removed - RuleSet.getLanguage()
Removed - RuleSet.setLanguage(Language)
Removed - RuleSets.applies(Language,Language)
Changed - void Rule.setPriority(int) to void Rule.setPriority(RulePriority)
Changed - int Rule.getPriority() to void RulePriority Rule.getPriority()
Changed - XXX Rule.getXXXProperty(String) to <T> Rule.getProperty(PropertyDescriptor<T>)
Changed - XXX Rule.getXXXProperty(PropertyDescriptor) to <T> Rule.getProperty(PropertyDescriptor<T>)
Changed - Rule.addProperty(String, String) to Rule.setProperty(PropertyDescriptor<T>, T)
Changed - Rule.setProperty(PropertyDescriptor, Object) to Rule.setProperty(PropertyDescriptor<T>, T)
Changed - Rule.setProperty(PropertyDescriptor, Object[]) to Rule.setProperty(PropertyDescriptor<T>, T)
Changed - Rule.propertyValuesByDescriptor() to Rule.getPropertiesByPropertyDescriptor()
Changed - PropertyDescriptor Rule.propertyDescriptorFor(String) to PropertyDescriptor Rule.getPropertyDescriptor(String)
Changed - boolean RuleSet.usesDFA() to boolean RuleSet.usesDFA(Language)
Changed - boolean RuleSet.usesTypeResolution() to boolean RuleSet.usesTypeResolution(Language)
Added - Rule.setLanguage(Language)
Added - Language Rule.getLanguage()
Added - Rule.setMinimumLanguageVersion(LanguageVersion)
Added - LanguageVersion Rule.getMinimumLanguageVersion()
Added - Rule.setMaximumLanguageVersion(LanguageVersion)
Added - LanguageVersion Rule.getMaximumLanguageVersion()
Added - Rule.setDeprecated(boolean)
Added - boolean Rule.isDeprecated()
Added - String Rule.dysfunctionReason();
Added - Rule.definePropertyDescriptor(PropertyDescriptor)
Added - List<PropertyDescriptor> Rule.getPropertyDescriptors()
Added - RuleSet.applies(Rule,LanguageVersion)
API Change - Changes to PMD class
Renamed - PMD.EXCLUDE_MARKER to PMD.SUPPRESS_MARKER
Removed - PMD.processFile(InputStream, RuleSet, RuleContext)
Removed - PMD.processFile(InputStream, String, RuleSet, RuleContext)
Removed - PMD.processFile(Reader, RuleSet, RuleContext)
Removed - PMD.processFile(Reader, RuleSets, RuleContext, LanguageVersion)
Moved - PMD.getExcludeMarker() to Configuration.getSuppressMarker()
Moved - PMD.setExcludeMarker(String) to Configuration.getSuppressMarker(String)
Moved - PMD.getClassLoader() to Configuration.getClassLoader()
Moved - PMD.setClassLoader(ClassLoader) to Configuration.getClassLoader(ClassLoader)
Moved - PMD.setDefaultLanguageVersion(LanguageVersion) to Configuration.setDefaultLanguageVersion(LanguageVersion)
Moved - PMD.setDefaultLanguageVersions(List<LanguageVersion>) to Configuration.setDefaultLanguageVersions(List<LanguageVersion>)
Moved - PMD.createClasspathClassLoader(String) to Configuration.createClasspathClassLoader(String)
API Change - Changes to Node interface
Renamed - Node.findChildrenOfType(Class) as Node.findDescendantsOfType(Class)
Renamed - Node.getFirstChildOfType(Class) as Node.getFirstDescendantOfType(Class)
Renamed - Node.containsChildOfType(Class) as Node.hasDescendantOfType(Class)
Renamed - Node.getAsXml() as Node.getAsDocument()
Added - Node.findChildrenOfType(Class), non recursive version
Added - Node.getFirstChildOfType(Class), non recursive version
API Change - Remove deprecated APIs
Removed - AccessNode.setXXX() methods, use AccessNode.setXXX(boolean) instead.
Removed - PMDException.getReason()
Removed - RuleSetFactory.createRuleSet(String,ClassLoader), use RuleSetFactory.setClassLoader(ClassLoader) and RuleSetFactory.createRuleSets(String) instead.
Removed - net.sourceforge.pmd.cpd.FileFinder use net.sourceforge.pmd.util.FileFinder instead.
API Change - RuleSetFactory
Added - RuleSetFactory.setClassLoader(ClassLoader)
Added - RuleSetFactory.createRuleSets(List<RuleSetReferenceId>)
Added - RuleSetFactory.createRuleSet(RuleSetReferenceId)
Added - RuleSetFactory.setClassLoader(ClassLoader)
Added - RuleSetReferenceId class to handle parsing of RuleSet strings, see RuleSetReferenceId.parse(String)
Renamed - RuleSetFactory.createSingleRuleSet(String) to RuleSetFactory.createRuleSet(String);
Removed - RuleSetFactory.createRuleSets(String, ClassLoader), use RuleSetFactory.createRuleSets(String) instead.
Removed - RuleSetFactory.createSingleRuleSet(String, ClassLoader), use RuleSetFactory.createSingleRuleSet(String) instead.
Removed - RuleSetFactory.createRuleSet(InputStream, ClassLoader), use RuleSetFactory.createRuleSet(RuleSetReferenceId) instead.
Removed - ExternalRuleID, use RuleSetReferenceId instead
Removed - SimpleRuleSetNameMapper, use RuleSetReferenceId instead
API Change - Changes to Renderer class, and Renderer implementations
Added - Renderer.getName()
Added - Renderer.setName(String)
Added - Renderer.getDescription()
Added - Renderer.setDescription(String)
Added - Renderer.getPropertyDefinitions()
Added - Renderer.isShowSuppressedViolations()
Added - AbstractAccumulatingRenderer
Removed - Renderer.render(Report)
Removed - Renderer.render(Report, Writer)
Renamed - Renderer.showSuppressedViolations(boolean) to Renderer.setShowSuppressedViolations(boolean)
Renamed - PapariTextRenderer to TextColorRenderer
Renamed - OntheFlyRenderer to AbstractIncrementingRenderer
PMD command line changes:
Removed -lineprefix use -property linePrefix {value} instead
Removed -linkprefix use -property linkPrefix {value} instead
Removed -xslt use -property xsltFilename {value} instead
Removed -nojsp now obsolete
Removed -targetjdk use -version {name} {version} instead
Added -version {name} {version} to set language version to use for a given language
Added -property {name} {value} as generic way to pass properties to Renderers
Added -showsuppressed as a means to show suppressed rule violations (consistent with Ant task behavior)
Renamed 'nicehtml' report to 'xslt'
Renamed 'papari' report to 'textcolor'
Renamed -excludemarker option to -suppressmarker
Renamed -cpus option to -threads
Ant changes:
Removed - <formatter> 'linkPrefix' attribute, use <param name="linkPrefix"> instead
Removed - <formatter> 'linePrefix' attribute, use <param name="linePrefix"> instead
Changed - <formatter> is optional - if not specified, falls back to "text" and console output.
Removed - <pmd> 'targetJDK' attribute to <version>lang version</version> instead
Added - <param name="name" value="value"/> as generic way to pass properties to Renderers on <formatter>
Renamed - <pmd> 'excludeMarker' attribute to 'suppressMarker'
Renamed - <pmd> 'cpus' attribute to 'threads'
Maven changes:
The new maven coordinates are: net.sourceforge.pmd:pmd, e.g.
<dependency>
<groupId>net.sourceforge.pmd</groupId>
<artifactId>pmd</artifactId>
<version>5.0</version>
</dependency>
New features:
New Language 'ecmascript' added, for writing XPathRule and Java Rules against ECMAScript/JavaScript documents (must be standalone, not embedded in HTML). Many thanks to Rhino!
New Language 'xml' added, for writing XPathRules against XML documents
New Language 'xsl' added, as a derivative from XML.
Rules can now define a 'violationSuppressRegex' property to universally suppress violations with messages matching the given regular expression
Rules can now define a 'violationSuppressXPath' property to universally suppress violations on nodes which match the given relative XPath expression
Rules are now directly associated with a corresponding Language, and a can also be associated with a specific Language Version range if desired.
Rules can now be flagged with deprecated='true' in the RuleSet XML to allow the PMD Project to indicate a Rule (1) is scheduled for removal, (2) has been removed, or (3) has been renamed/moved.
XPathRules can now query using XPath 2.0 with 'version=2.0"', or XPath 2.0 in XPath 1.0 compatibility mode using 'version="1.0 compatibility"'. Many thanks to Saxon!
Rules can now use property values in messages, for example ${propertyName} will expand to the value of the 'propertyName' property on the Rule.
Rules can now use violation specific values in messages, specifically ${variableName}, ${methodName}, ${className}, ${packageName}.
New XPath function 'getCommentOn' can be used to search for strings in comments - Thanks to Andy Throgmorton
CPD:
Add .hxx and .hpp as valid file extension for CPD - Thanks to Ryan Pavlik
Add options to to the CPD command line task - Thanks to Cd-Man
Add C# support for CPD - thanks to Florian Bauer
Fix small bug in Rule Designer UI
Performance enhacement when parsing Javadoc (Patch ID: 3217201), thanks to Cd-Man
Rework the XMLRenderer to use proper XML API and strictly uses the system value for encoding (Fix bug: 1435751)
Other changes:
Rule property API upgrades:
All numeric property descriptors can specify upper & lower limits
Newly functional Method & Type descriptors allow rule developers to incorporate/watch for individual methods or types
Better initialization error detection
Deprecated old string-keyed property API, will leave some methods behind for XPath rules however
'41' and '42' shortcuts for rulesets added
The default Java version processed by PMD is now uniformly Java 1.5.
RuleViolations in Reports now uses List internally, and RuleViolationComparator is no longer broken
TokenManager errors now include a file name whenever possible for every AST in PMD
Added file encoding option to CPD GUI, which already existed for the command line and Ant
AssignmentInOperand enhanced to catch assignment in 'for' condition, as well as use of increment/decrement operators. Customization properties added to allow assignment in if/while/for, or use of increment/decrement.
Fix false positive on CastExpressions for UselessParentheses
Fix false positive where StringBuffer.setLength(0) was using default constructor size of 16, instead of actual constructor size.
Fix false negative for non-primitive types for VariableNamingConventions, also expanded scope to local and method/constructors, and enhanced customization options to choose between members/locals/parameters (all checked by default)
Fix false negative for UseArraysAsList when the array was passed as method parameter - thanks to Andy Throgmorton
Improve TooManyMethods rule - thanks to a patch from Riku Nykanen
Improve DoNotCallSystemExit - thanks to a patch from Steven Christou
Correct -benchmark reporting of Rule visits via the RuleChain
Creating an Empty Code Ruleset and moved the following rules from Basic ruleset:
* Empty Code Rules
* EmptyCatchBlock
* EmptyIfStmt
* EmptyWhileStmt
* EmptyTryBlock
* EmptyFinallyBlock
* EmptySwitchStatements
* EmptySynchronizedBlock
* EmptyStatementNotInLoop
* EmptyInitializer
* EmptyStatementBlock
* EmptyStaticInitializer
Basic rulesets still includes a reference to those rules.
Creating a unnecessary Code Ruleset and moved the following rules from Basic ruleset:
* UnnecessaryConversionTemporary
* UnnecessaryReturn
* UnnecessaryFinalModifier
* UselessOverridingMethod
* UselessOperationOnImmutable
* UnusedNullCheckInEquals
* UselessParentheses
Basic rulesets still includes a reference to those rules.
Fixed bug 2920057 - Fixed False + on CloseResource
Fixed bug 1808110 - Fixed performance issues on PreserveStackTrace
Fixed bug 2832322 - cpd.xml file tag path attribute should be entity-encoded
Fixed bug 2826119 - False +: DoubleCheckedLocking warning with volatile field
Fixed bug 2835074 - False -: DoubleCheckedLocking with reversed null check
Fixed bug 1932242 - EmptyMethodInAbstractClassShouldBeAbstract false +
Fixed bug 1928009 - Error using migration ruleset in PMD 4.2
Fixed bug 1808110 - PreserveStackTrace
Fixed bug 1988829 - Violation reported without source file name (actually a fix to ConsecutiveLiteralAppends)
Fixed bug 1989814 - false +: ConsecutiveLiteralAppends
Fixed bug 1977230 - false positive: UselessOverridingMethod
Fixed bug 1998185 - BeanMembersShouldSerialize vs @SuppressWarnings("serial")
Fixed bug 2002722 - false + in UseStringBufferForStringAppends
Fixed bug 2056318 - False positive for AvoidInstantiatingObjectsInLoops
Fixed bug 1977438 - False positive for UselessStringValueOf
Fixed bug 2050064 - False + SuspiciousOctalEscape with backslash literal
Fixed bug 1556594 - Wonky detection of NullAssignment
Fixed bug 1481051 - false + UnusedNullCheckInEquals (and other false positives too)
Fixed bug 1943204 - Ant task: <ruleset> path should be relative to Ant basedir
Fixed patch 2075906 - Add toString() to the rule UnnecessaryWrapperObjectCreation
Fixed bug 2315623 - @SuppressWarnings("PMD.UseSingleton") has no effect
Fixed bug 2230809 - False +: ClassWithOnlyPrivateConstructorsShouldBeFinal
Fixed bug 2338341 - ArrayIndexOutOfBoundsException in CPD (on Ruby)
Fixed bug 2315599 - False +: UseSingleton with class containing constructor
Fixed bug 1955852 - false positives for UnusedPrivateMethod & UnusedLocalVariable
Fixed bug 2404700 - UseSingleton should not act on enums
Fixed bug - JUnitTestsShouldIncludeAssert now detects Junit 4 Assert.assert... constructs
Fixed bug 1609038 - Xslt report generators break if path contains "java"
Fixed bug 2142986 - UselessOverridingMethod doesn't consider annotations
Fixed bug 2027626 - False + : AvoidFinalLocalVariable
Fixed bug 2606609 - False "UnusedImports" positive in package-info.java
Fixed bug 2645268 - ClassCastException in UselessOperationOnImmutable.getDeclaration
Fixed bug 2724653 - AvoidThreadGroup reports false positives
Fixed bug 2904832 - Type resolution not working for ASTType when using an inner class
Fixed bug 1435751 - XML format does not support UTF-8
Fixed bug 3303811 - Deadlink on "Similar projects" page
Fixed bug 3017616 - Updated documentation regarding Netbeans plugin - thanks to Jesse Glick
Fixed bug 3427563 - Deprecated class (android.util.config) - thanks to Lukas Reschke for the patch
ruleset.dtd and ruleset_xml_schema.xsd added to jar file in rulesets directory
bin and java14/bin scripts:
retroweaver version was not correct in java14/bin scripts
support for extra languages in cpd.sh
standard unix scripts can be used with cygwin
Upgrading UselessOperationOnImmutable to detect more use cases, especially on String and fix false positives
AvoidDuplicateLiteralRule now has 'skipAnnotations' boolean property
Fixed false positive in UnusedImports: javadoc comments are parsed to check @see and other tags
Fixed parsing bug: constant fields in annotation classes
Bug fix: NPE in MoreThanOneLogger
UnnecessaryParentheses now checks all expressions, not just return statements
UnusedFormalParameter now reports violations on the parameter node, not the method/constructor node
Updates to RuleChain to honor RuleSet exclude-pattern
Optimizations and false positive fixes in PreserveStackTrace
@SuppressWarnings("all") disables all warnings
SingularField now checks for multiple fields in the same declaration
Java grammar enhanced to include AnnotationMethodDeclaration as parent node of method related children of AnnotationTypeMemberDeclaration
JavaCC generated artifacts updated to JavaCC 4.1.
Dependencies updates: asm updated to 3.2
Ant requirement is now 1.7.0 or higher for compilation
JUnit testing jar is packaged on 1.7.0+ only in ant binary distributions
Note that the ant task still works with 1.6.0 and higher
All comment types are now stored in ASTCompilationUnit, not just formal ones
Fixed false negative in UselessOverridingMethod
Fixed handling of escape characters in UseIndexOfChar and AppendCharacterWithChar
Fixed ClassCastException on generic method in BeanMembersShouldSerialize
Fixed ClassCastException in symbol table code
Support for Java 1.4 runtime dropped, PMD now requires Java 5 or higher. PMD can still process Java 1.4 source files.
Support for Java 1.7
Text renderer is now silent if there's no violation instead of displaying "No problems found!"
RuleSet short names now require a language prefix, 'basic' is now 'java-basic', and 'rulesets/basic.xml' is now 'rulesets/java/basic.xml'
The JSP RuleSets are now in the 'jsp' language, and are 'jsp-basic', 'jsp-basic-jsf', 'rulesets/jsp/basic.xml' and 'rulesets/jsp/basic-jsp.xml'
Enhanced logging in the ClassTypeResolver to provide more detailed messaging.
AvoidUsingHardCodedIP modified to not use InetAddress.getByName(String), instead does better pattern analysis.
The JSP/JSF parser can now parse Unicode input.
The JSP/JSP parser can now handle <script>...</script> tags. The AST HtmlScript node contains the content.
Added Ecmascript as a supported language for CPD.
The RuleSet XML Schema namespace is now: http://pmd.sourceforge.net/ruleset/2.0.0
The RuleSet XML Schema is located in the source at: etc/ruleset_2_0_0.xsd
The RuleSet DTD is located in the source at: etc/ruleset_2_0_0.dtd
Improved include/exclude pattern matching performance for ends-with type patterns.
Modify (and hopefully fixed) CPD algorithm thanks to a patch from Juan Jesús García de Soria.
Fixed character reference in xml report - thanks to Seko
Enhanced SuspiciousEqualsMethodName rule - thanks to Andy Throgmorton
Add a script to launch CPDGUI on Unix system - thanks to Tom Wheeler
New Java rules:
Basic ruleset: ExtendsObject,CheckSkipResult,AvoidBranchingStatementAsLastInLoop,DontCallThreadRun,DontUseFloatTypeForLoopIndices
Controversial ruleset: AvoidLiteralsInIfCondition, AvoidPrefixingMethodParameters, OneDeclarationPerLine, UseConcurrentHashMap
Coupling ruleset: LoosePackageCoupling,LawofDemeter
Design ruleset: LogicInversion,UseVarargs,FieldDeclarationsShouldBeAtStartOfClass,GodClass
Empty ruleset: EmptyInitializer,EmptyStatementBlock
Import ruleset: UnnecessaryFullyQualifiedName
Optimization ruleset: RedundantFieldInitializer
Naming ruleset: ShortClassName, GenericsNaming
StrictException ruleset: AvoidThrowingNewInstanceOfSameException, AvoidCatchingGenericException, AvoidLosingExceptionInformation
Unnecessary ruleset: UselessParentheses
JUnit ruleset: JUnitTestContainsTooManyAsserts, UseAssertTrueInsteadOfAssertEquals
Logging with Jakarta Commons ruleset: GuardDebugLogging
New Java ruleset:
android.xml: new rules specific to the Android platform
New JSP rules:
Basic ruleset: NoInlineScript
New ECMAScript rules:
Basic ruleset: AssignmentInOperand,ConsistentReturn,InnaccurateNumericLiteral,ScopeForInVariable,UnreachableCode,EqualComparison,GlobalVariable
Braces ruleset: ForLoopsMustUseBraces,IfStmtsMustUseBraces,IfElseStmtsMustUseBraces,WhileLoopsMustUseBraces
Unnecessary ruleset: UnnecessaryParentheses,UnnecessaryBlock
New XML rules:
Basic ruleset: MistypedCDATASection
Add support for Java 7 grammer - thanks to Dinesh Bolkensteyn and SonarSource
Add options --ignore-literals and --ignore-identifiers to the CPD command line task, thanks to Cd-Man
Fixed character reference in xml report - thanks to Seko
Add C# support for CPD - thanks to Florian Bauer
Fix small bug in Rule Designer UI
Improve TooManyMethods rule - thanks to a patch from Riku Nykanen
Improve DoNotCallSystemExit - thanks to a patch from Steven Christou
Fix false negative for UseArraysAsList when the array was passed as method parameter - thanks to Andy Throgmorton
Enhanced SuspiciousEqualsMethodName rule - thanks to Andy Throgmorton
Add a script to launch CPDGUI on Unix system - thanks to Tom Wheeler
New Rule:
Basic ruleset: DontCallThreadRun - thanks to Andy Throgmorton
Logging with Jakarta Commons ruleset: GuardDebugLogging
Fixed bug 2920057 - False + : CloseRessource whith an external getter
Fixed bug 1808110 - Fixed performance issue on PreserveStackTrace
Fixed bug 2832322 - cpd.xml file tag path attribute should be entity-encoded
Fixed bug 2590258 - NPE with nicerhtml output
Fixed bug 2317099 - False + in SimplifyCondition
Fixed bug 2606609 - False "UnusedImports" positive in package-info.java
Fixed bug 2645268 - ClassCastException in UselessOperationOnImmutable.getDeclaration
Fixed bug 2724653 - AvoidThreadGroup reports false positives
Fixed bug 2835074 - False -: DoubleCheckedLocking with reversed null check
Fixed bug 2826119 - False +: DoubleCheckedLocking warning with volatile field
Fixed bug 2904832 - Type resolution not working for ASTType when using an inner class
Modify (and hopefully fixed) CPD algorithm thanks to a patch from Juan Jesús García de Soria.
Correct -benchmark reporting of Rule visits via the RuleChain
Fix issue with Type Resolution incorrectly handling of Classes with same name as a java.lang Class.
The JSP/JSF parser can now parse Unicode input.
The JSP/JSP parser can now handle <script>...</script> tags. The AST HtmlScript node contains the content.
Added Ecmascript as a supported language for CPD.
Improved include/exclude pattern matching performance for ends-with type patterns.
Dependencies updates: asm updated to 3.2
Android ruleset: CallSuperLast rule now also checks for finish() redefinitions
New rule:
Android: DoNotHardCodeSDCard
Controversial : AvoidLiteralsInIfCondition (patch 2591627), UseConcurrentHashMap
StrictExceptions : AvoidCatchingGenericException, AvoidLosingExceptionInformation
Naming : GenericsNaming
JSP: NoInlineScript
Enhanced logging in the ClassTypeResolver to provide more detailed messaging.
Fixed bug 2315623 - @SuppressWarnings("PMD.UseSingleton") has no effect
Fixed bug 2230809 - False +: ClassWithOnlyPrivateConstructorsShouldBeFinal
Fixed bug 2338341 - ArrayIndexOutOfBoundsException in CPD (on Ruby)
Fixed bug 2315599 - False +: UseSingleton with class containing constructor
Fixed bug 1955852 - false positives for UnusedPrivateMethod & UnusedLocalVariable
Fixed bug 2404700 - UseSingleton should not act on enums
Fixed bug 2225474 - VariableNamingConventions does not work with nonprimitives
Fixed bug 1609038 - Xslt report generators break if path contains "java"
Fixed bug - JUnitTestsShouldIncludeAssert now detects Junit 4 Assert.assert... constructs
Fixed bug 2142986 - UselessOverridingMethod doesn't consider annotations
Fixed bug 2027626 - False + : AvoidFinalLocalVariable
New rule:
StrictExceptions : AvoidThrowingNewInstanceOfSameException
New ruleset:
android.xml: new rules specific to the Android platform
Fixed bug 1481051 - false + UnusedNullCheckInEquals (and other false positives too)
Fixed bug 1943204 - Ant task: <ruleset> path should be relative to Ant basedir
Fixed bug 2139720 - Exception in PMD Rule Designer for inline comments in source
Fixed patch 2075906 - Add toString() to the rule UnnecessaryWrapperObjectCreation
Fixed ClassCastException on generic method in BeanMembersShouldSerialize
Fixed ClassCastException in symbol table code
JavaCC generated artifacts updated to JavaCC 4.1d1.
Java grammar enhanced to include AnnotationMethodDeclaration as parent node of method related children of AnnotationTypeMemberDeclaration
Fixes for exclude-pattern
Updates to RuleChain to honor RuleSet exclude-pattern
Upgrading UselessOperationOnImmutable to detect more use cases, especially on String and fix false positives
Fixed bug 1988829 - Violation reported without source file name (actually a fix to ConsecutiveLiteralAppends)
Fixed bug 1989814 - false +: ConsecutiveLiteralAppends
Fixed bug 1977230 - false positive: UselessOverridingMethod
Fixed bug 1998185 - BeanMembersShouldSerialize vs @SuppressWarnings("serial")
Fixed bug 2002722 - false + in UseStringBufferForStringAppends
Fixed bug 2056318 - False positive for AvoidInstantiatingObjectsInLoops
Fixed bug 1977438 - False positive for UselessStringValueOf
Fixed bug 2050064 - False + SuspiciousOctalEscape with backslash literal
Fixed bug 1556594 - Wonky detection of NullAssignment
Optimizations and false positive fixes in PreserveStackTrace
@SuppressWarnings("all") disables all warnings
All comment types are now stored in ASTCompilationUnit, not just formal ones
Fixed false negative in UselessOverridingMethod
Fixed handling of escape characters in UseIndexOfChar and AppendCharacterWithChar
New rule:
Basic ruleset: EmptyInitializer
Fixed false positive in UnusedImports: javadoc comments are parsed to check @see and other tags
Fixed parsing bug: constant fields in annotation classes
Bug fix: NPE in MoreThanOneLogger
UnnecessaryParentheses now checks all expressions, not just return statements
'41' and '42' shortcuts for rulesets added
Fixed bug 1928009 - Error using migration ruleset in PMD 4.2
Fixed bug 1932242 - EmptyMethodInAbstractClassShouldBeAbstract false +
Fixed bug 1808110 - PreserveStackTrace
AvoidDuplicateLiteralRule now has 'skipAnnotations' boolean property
ruleset.dtd and ruleset_xml_schema.xsd added to jar file in rulesets directory
Update RuleSetWriter to handle non-Apache TRAX implementations, add an option to not use XML Namespaces
Added file encoding option to CPD GUI, which already existed for the command line and Ant
bin and java14/bin scripts:
retroweaver version was not correct in java14/bin scripts
support for extra languages in cpd.sh
standard unix scripts can be used with cygwin
Fixed bug 1920155 - CheckResultSet: Does not pass for loop conditionals
Fixed bug 1912831 - False + UnusedPrivateMethod with varargs
Fixed bug 1913536 - Rule Designer does not recognize JSP(XML)
Add -auxclasspath option for specifying Type Resolution classpath from command line and auxclasspath nested element for ant task.
Fixed formatting problems in loggers.
Ant task upgrade:
Added a new attribute 'maxRuleCount' to indicate whether or not to fail the build if PMD finds that much violations.
Fixed bug 1866198 - PMD should not register global Logger
Fixed bug 1843273 - False - on SimplifyBooleanReturns
Fixed bug 1848888 - Fixed false positive in UseEqualsToCompareStrings
Fixed bug 1874313 - Documentation bugs
Fixed bug 1855409 - False + in EmptyMethodInAbstractClassShouldBeAbstract
Fixed bug 1888967 - Updated xpath query to detect more "empty" methods.
Fixed bug 1891399 - Check for JUnit4 test method fails
Fixed bug 1894821 - False - for Test Class without Test Cases
Fixed bug 1882457 - PositionLiteralsFirstInComparisons rule not working OK
Fixed bug 1842505 - XML output incorrect for inner classes
Fixed bug 1808158 - Constructor args could also be final
Fixed bug 1902351 - AvoidReassigningParameters not identify parent field
Fixed other false positives in EmptyMethodInAbstractClassShouldBeAbstract
Fixed other issues in SimplifyBooleanReturns
Modified AvoidReassigningParameter to also check constructor arguments for reassignement
New rules:
Basic ruleset: AvoidMultipleUnaryOperators
Controversial ruleset: DoNotCallGarbageCollectionExplicitly,UseObjectForClearerAPI
Design ruleset : ReturnEmptyArrayRatherThanNull,TooFewBranchesForASwitchStatement,AbstractClassWithoutAnyMethod
Codesize : TooManyMethods
StrictExceptions : DoNotThrowExceptionInFinally
Strings : AvoidStringBufferField
Rule upgrade:
CyclomaticComplexity now can be configured to display only class average complexity or method complexity, or both.
Designer upgrade:
A new panel for symbols and a tooltips on AST node that displays line, column and access node attributes (private,
static, abstract,...)
1.7 added as a valid option for targetjdk.
New elements under <ruleset>: <exclude-pattern> to match files exclude from processing, with <include-pattern> to override.
Rules can now be written which produce violations based upon aggregate file processing (i.e. cross/multiple file violations).
PMD Rule Designer can now shows Symbol Table contents for the selected AST node.
PMD Rule Designer shows position info in tooltip for AST nodes and highlights matching code for selected AST node in code window.
CPD Ant task will report to System.out when 'outputFile' not given.
RuleSetWriter class can be used to Serialize a RuleSet to XML in a standard fashion. Recommend PMD IDE plugins standardize their behavior.
retroweaver updated to version 2.0.5.
Fixed annotation bug: ClassCastException when a formal parameter had multiple annotations
Added a Visual Studio renderer for CPD; just use "--format vs".
Dependencies updates: asm to 3.1, retroweaver to 2.0.2, junit to 4.4
new ant target ("regress") to test regression bugs only
New rules:
Basic ruleset: AvoidUsingHardCodedIP,CheckResultSet
Controversial ruleset: AvoidFinalLocalVariable,AvoidUsingShortType,AvoidUsingVolatile,AvoidUsingNativeCode,AvoidAccessibilityAlteration
Design ruleset: ClassWithOnlyPrivateConstructorsShouldBeFinal,EmptyMethodInAbstractClassShouldBeAbstract
Imports ruleset: TooManyStaticImports
J2ee ruleset: DoNotCallSystemExit, StaticEJBFieldShouldBeFinal,DoNotUseThreads
Strings ruleset: UseEqualsToCompareStrings
Fixed bug 674394 - fixed false positive in DuplicateImports for disambiguation import
Fixed bug 631681 - fixed false positive in UnusedPrivateField when field is accessed by outer class
Fixed bug 985989 - fixed false negative in ConstructorCallsOverridableMethod for inner static classes
Fixed bug 1409944 - fixed false positive in SingularField for lock objects
Fixed bug 1472195 - fixed false positives in PositionLiteralsFirstInComparisons when the string is used as a parameter
Fixed bug 1522517 - fixed false positive in UselessOverridingMethod for clone method
Fixed bug 1744065 - fixed false positive in BooleanInstantiation when a custom Boolean is used
Fixed bug 1765613 - fixed NullPointerException in CloneMethodMustImplementCloneable when checking enum
Fixed bug 1740480 - fixed false positive in ImmutableField when the assignment is inside an 'if'
Fixed bug 1702782 - fixed false positive in UselessOperationOnImmutable when an Immutable on which an operation is performed is compareTo'd
Fixed bugs 1764288/1744069/1744071 - When using Type Resolution all junit test cases will notice if you're using an extended TestCase
Fixed bug 1793215 - pmd-nicerhtml.xsl does not display line numbers
Fixes bug 1796928 - fixed false positive in AvoidThrowingRawExceptionTypes, when a Type name is the same as a RawException.
Fixed bug 1811506 - False - : UnusedFormalParameter (property "checkall" needs to be set)
Fixed false negative in UnnecessaryCaseChange
The Java 1.5 source code parser is now the default for testcode used in PMD's unit tests.
Added TypeResolution to the XPath rule. Use typeof function to determine if a node is of a particular type
Adding a GenericLiteralChecker, a generic rule that require a regex as property. It will log a violation if a Literal is matched by the regex. See the new rule AvoidUsingHardCodedIP for an example.
Adding support for multiple line span String in CPD's AbstractTokenizer, this may change, for the better, CPD's Ruby parsing.
This release adds 'nicehtml', with the plan for the next major release to make nicehtml->html, and html->oldhtml. This feature uses an XSLT transformation, default stylesheet maybe override with '-xslt filename'.
New CPD command line feature : Using more than one directory for sources. You can now have several '--files' on the command line.
SingularField greatly improved to generate very few false positives (none?). Moved from controversial to design. Two options added to restore old behaviour (mostly).
Jaxen updated to 1.1.1, now Literal[@Image='""'] works in XPath expressions.
Fixed bug 1697397 - fixed false positives in ClassCastExceptionWithToArray
Fixed bug 1728789 - removed redundant rule AvoidNonConstructorMethodsWithClassName; MethodWithSameNameAsEnclosingClass is faster and does the same thing.
New rules:
Typeresolution ruleset: SignatureDeclareThrowsException - re-implementation using the new Type Resolution facility (old rule is still available)
Fixed bug 1698550 - CloneMethodMustImplementCloneable now accepts a clone method that throws CloneNotSupportedException in a final class
Fixed bug 1680568 - The new typeresolution SignatureDeclareThrowsException rule now ignores setUp and tearDown in JUnit 4 tests and tests that do not directly extend TestCase
The new typeresolution SignatureDeclareThrowsException rule can now ignore JUnit classes completely by setting the IgnoreJUnitCompletely property
Fixed false positive in UselessOperationOnImmutable
PMD now defaults to using a Java 1.5 source code parser.
New rules:
Strict exception ruleset: DoNotExtendJavaLangError
Basic JSP ruleset: JspEncoding
J2EE ruleset: MDBAndSessionBeanNamingConvention, RemoteSessionInterfaceNamingConvention, LocalInterfaceSessionNamingConvention, LocalHomeNamingConvention, RemoteInterfaceNamingConvention
Optimizations ruleset: AddEmptyString
Naming: BooleanGetMethodName
New rulesets:
Migrating To JUnit4: Rules that help move from JUnit 3 to JUnit 4
Fixed bug 1670717 - 'Copy xml to clipboard' menu command now works again in the Designer
Fixed bug 1618858 - PMD no longer raises an exception on XPath like '//ConditionalExpression//ConditionalExpression'
Fixed bug 1626232 - Commons logging rules (ProperLogger and UseCorrectExceptionLogging) now catch more cases
Fixed bugs 1626201 & 1633683 - BrokenNullCheck now catches more cases
Fixed bug 1626715 - UseAssertSameInsteadOfAssertTrue now correctly checks classes which contain the null constant
Fixed bug 1531216 - ImmutableField. NameOccurrence.isSelfAssignment now recognizes this.x++ as a self assignment
Fixed bug 1634078 - StringToString now recognizes toString on a String Array, rather than an element.
Fixed bug 1631646 - UselessOperationOnImmutable doesn't throw on variable.method().variable.
Fixed bug 1627830 - UseLocaleWithCaseConversions now works with compound string operations
Fixed bug 1613807 - DontImportJavaLang rule allows import to Thread inner classes
Fixed bug 1637573 - The PMD Ant task no longer closes System.out if toConsole is set
Fixed bug 1451251 - A new UnusedImports rule, using typeresolution, finds unused import on demand rules
Fixed bug 1613793 - MissingSerialVersionUID rule now doesn't fire on abstract classes
Fixed bug 1666646 - ImmutableField rule doesn't report against volatile variables
Fixed bug 1693924 - Type resolution now works for implicit imports
Fixed bug 1705716 - Annotation declarations now trigger a new scope level in the symbol table.
Fixed bug 1743938 - False +: InsufficientStringBufferDeclaration with multiply
Fixed bug 1657957 - UseStringBufferForStringAppends now catches self-assignments
Applied patch 1612455 - RFE 1411022 CompareObjectsWithEquals now catches the case where comparison is against new Object
Implemented RFE 1562230 - Added migration rule to check for instantiation of Short/Byte/Long
Implemented RFE 1627581 - SuppressWarnings("unused") now suppresses all warnings in unusedcode.xml
XPath rules are now chained together for an extra speedup in processing
PMD now requires JDK 1.5 to be compiled. Java 1.4 support is provided using Retroweaver
- PMD will still analyze code from earlier JDKs
- to run pmd with 1.4, use the files from the java14 directory (weaved pmd jar and support files)
TypeResolution now looks at some ASTName nodes.
Memory footprint reduced: most renderers now use less memory by generating reports on the fly.
Ant task now takes advantage of multithreading code and on the fly renderers
Ant task now logs more debug info when using -verbose
PMD command line now has -benchmark: output a benchmark report upon completion; default to System.err
New rules:
Basic ruleset: BigIntegerInstantiation, AvoidUsingOctalValues
Codesize ruleset: NPathComplexity, NcssTypeCount, NcssMethodCount, NcssConstructorCount
Design ruleset: UseCollectionIsEmpty
Strings ruleset: StringBufferInstantiationWithChar
Typeresolution ruleset: Loose Coupling - This is a re-implementation using the new Type Resolution facility
Fixed bug 1610730 - MisplacedNullCheck now catches more cases
Fixed bug 1570915 - AvoidRethrowingException no longer reports a false positive for certain nested exceptions.
Fixed bug 1571324 - UselessStringValueOf no longer reports a false positive for additive expressions.
Fixed bug 1573795 - PreserveStackTrace doesn't throw CastClassException on exception with 0 args
Fixed bug 1573591 - NonThreadSafeSingleton doesn't throw NPE when using this keyword
Fixed bug 1371753 - UnnecessaryLocalBeforeReturn is now less aggressive in its reporting.
Fixed bug 1566547 - Annotations with an empty MemberValueArrayInitializer are now parsed properly.
Fixed bugs 1060761 / 1433119 & RFE 1196954 - CloseResource now takes an optional parameter to identify closure methods
Fixed bug 1579615 - OverrideBothEqualsAndHashcode no longer throws an Exception on equals methods that don't have Object as a parameter type.
Fixed bug 1580859 - AvoidDecimalLiteralsInBigDecimalConstructor now catches more cases.
Fixed bug 1581123 - False +: UnnecessaryWrapperObjectCreation.
Fixed bug 1592710 - VariableNamingConventions no longer reports false positives on certain enum declarations.
Fixed bug 1593292 - The CPD GUI now works with the 'by extension' option selected.
Fixed bug 1560944 - CPD now skips symlinks.
Fixed bug 1570824 - HTML reports generated on Windows no longer contain double backslashes. This caused problems when viewing those reports with Apache.
Fixed bug 1031966 - Re-Implemented CloneMethodMustImplementCloneable as a typeresolution rule. This rule can now detect super classes/interfaces which are cloneable
Fixed bug 1571309 - Optional command line options may be used either before or after the mandatory arguments
Applied patch 1551189 - SingularField false + for initialization blocks
Applied patch 1573981 - false + in CloneMethodMustImplementCloneable
Applied patch 1574988 - false + in OverrideBothEqualsAndHashcode
Applied patch 1583167 - Better test code management. Internal JUnits can now be written in XML's
Applied patch 1613674 - Support classpaths with spaces in pmd.bat
Applied patch 1615519 - controversial/DefaultPackage XPath rule is wrong
Applied patch 1615546 - Added option to command line to write directly to a file
Implemented RFE 1566313 - Command Line now takes minimumpriority attribute to filter out rulesets
PMD now requires JDK 1.4 to run
- PMD will still analyze code from earlier JDKs
- PMD now uses the built-in JDK 1.4 regex utils vs Jakarta ORO
- PMD now uses the JDK javax.xml APIs rather than being hardcoded to use Xerces and Xalan
SummaryHTML Report changes from Brent Fisher - now contains linePrefix to support source output from javadoc using "linksource"
Fixed CSVRenderer - had flipped line and priority columns
Fixed bug in Ant task - CSV reports were being output as text.
Fixed false negatives in UseArraysAsList.
Fixed several JDK 1.5 parsing bugs.
Fixed several rules (exceptions on jdk 1.5 and jdk 1.6 source code).
Fixed array handling in AvoidReassigningParameters and UnusedFormalParameter.
Fixed bug in UselessOverridingMethod: false + when adding synchronization.
Fixed false positives in LocalVariableCouldBeFinal.
Fixed false positives in MethodArgumentCouldBeFinal.
Modified annotation suppression to use @SuppressWarning("PMD") to suppress all warnings and @SuppressWarning("PMD.UnusedLocalVariable") to suppress a particular rule's warnings.
Rules can now call RuleContext.getSourceType() if they need to make different checks on JDK 1.4 and 1.5 code.
CloseResource rule now checks code without java.sql import.
ArrayIsStoredDirectly rule now checks Constructors
undo/redo added to text areas in Designer.
Better 'create rule XML' panel in Designer.
use of entrySet to iterate over Maps.
1.6 added as a valid option for targetjdk.
PMD now allows rules to use Type Resolution. This was referenced in patch 1257259.
Renderers use less memory when generating reports.
New DynamicXPathRule class to speed up XPath based rules by providing a base type for the XPath expression.
Multithreaded processing on multi core or multi cpu systems.
Performance Refactoring, XPath rules re-written as Java:
AssignmentInOperand
AvoidDollarSigns
DontImportJavaLang
DontImportSun
MoreThanOneLogger
SuspiciousHashcodeMethodName
UselessStringValueOf
New rules:
Basic ruleset: BrokenNullCheck
Strict exceptions ruleset: AvoidRethrowingException
Optimizations ruleset: UnnecessaryWrapperObjectCreation
Strings ruleset: UselessStringValueOf
Fixed bug 1498910 - AssignmentInOperand no longer has a typo in the message.
Fixed bug 1498960 - DontImportJavaLang no longer reports static imports of java.lang members.
Fixed bug 1417106 - MissingBreakInSwitch no longer flags stmts where every case has either a return or a throw.
Fixed bug 1412529 - UncommentedEmptyConstructor no longer flags private constructors.
Fixed bug 1462189 - InsufficientStringBufferDeclaration now resets when it reaches setLength the same way it does at a Constructor
Fixed bug 1497815 - InsufficientStringBufferDeclaration rule now takes the length of the constructor into account, and adds the length of the initial string to its initial length
Fixed bug 1504842 - ExceptionSignatureDeclaration no longer flags methods starting with 'test'.
Fixed bug 1516728 - UselessOverridingMethod no longer raises an NPE on methods that use generics.
Fixed bug 1522054 - BooleanInstantiation now detects instantiations inside method calls.
Fixed bug 1522056 - UseStringBufferForStringAppends now flags appends which occur in static initializers and constructors
Fixed bug 1526530 - SingularField now finds fields which are hidden at the method or static level
Fixed bug 1529805 - UnusedModifier no longer throws NPEs on JDK 1.5 enums.
Fixed bug 1531593 - UnnecessaryConversionTemporary no longer reports false positives when toString() is invoked inside the call to 'new Long/Integer/etc()'.
Fixed bug 1512871 - Improved C++ tokenizer error messages - now they include the filename.
Fixed bug 1531152 - CloneThrowsCloneNotSupportedException now reports the proper line number.
Fixed bug 1531236 - IdempotentOperations reports fewer false positives.
Fixed bug 1544564 - LooseCoupling rule now checks for ArrayLists
Fixed bug 1544565 - NonThreadSafeSingleton now finds if's with compound statements
Fixed bug 1561784 - AbstractOptimizationRule no longer throws ClassCastExceptions on certain postfix expressions.
Fixed a bug in AvoidProtectedFieldInFinalClass - it no longer reports false positives for protected fields in inner classes.
Fixed a bug in the C++ grammar - the tokenizer now properly recognizes macro definitions which are followed by a multiline comment.
Modified C++ tokenizer to use the JavaCC STATIC option; this results in about a 30% speedup in tokenizing.
Implemented RFE 1501850 - UnusedFormalParameter now catches cases where a parameter is assigned to but not used.
Applied patch 1481024 (implementing RFE 1490181)- NOPMD messages can now be reported with a user specified msg, e.g., //NOPMD - this is expected
Added JSP support to the copy/paste detector.
Placed JSF/JSP ruleset names in rulesets/jsprulesets.properties
Added the image to the ASTEnumConstant nodes.
Added new XSLT stylesheet for CPD XML->HTML from Max Tardiveau.
Refactored UseIndexOfChar to extract common functionality into AbstractPoorMethodCall.
Improved CPD GUI and Designer look/functionality; thanks to Brian Remedios for the changes!
Rewrote the NOPMD mechanism to collect NOPMD markers as the source file is tokenized. This eliminates an entire scan of each source file.
Applied patch from Jason Bennett to enhance CyclomaticComplexity rule to account for conditional or/and nodes, do stmts, and catch blocks.
Applied patch from Xavier Le Vourch to reduce false postives from CloneMethodMustImplementCloneable.
Updated Jaxen library to beta 10.
Performance Refactoring, XPath rules re-written as Java:
BooleanInstantiation
UselessOperationOnImmutable
OverrideBothEqualsAndHashcode
UnnecessaryReturn
UseStringBufferForStringAppends
SingularField
NonThreadSafeSingleton
New rules:
Basic-JSP ruleset: DuplicateJspImport
Design ruleset: PreserveStackTrace
J2EE ruleset: UseProperClassLoader
Implemented RFE 1462019 - Add JSPs to Ant Task
Implemented RFE 1462020 - Add JSPs to Designer
Fixed bug 1461426 InsufficientStringBufferDeclaration does not consider paths
Fixed bug 1462184 False +: InsufficientStringBufferDeclaration - wrong size
Fixed bug 1465574 - UnusedPrivateMethod no longer reports false positives when a private method is called from a method with a parameter of the same name.
Fixed bug 1114003 - UnusedPrivateMethod no longer reports false positives when two methods have the same name and number of arguments but different types. The fix causes PMD to miss a few valid cases, but, c'est la vie.
Fixed bug 1472843 - UnusedPrivateMethod no longer reports false positives when a private method is only called from a method that contains a variable with the same name as that method.
Fixed bug 1461442 - UseAssertSameInsteadOfAssertTrue now ignores comparisons to null; UseAssertNullInsteadOfAssertTrue will report those.
Fixed bug 1474778 - UnnecessaryCaseChange no longer flags usages of toUpperCase(Locale).
Fixed bug 1423429 - ImmutableField no longer reports false positives on variables which can be set via an anonymous inner class that is created in the constructor.
Fixed major bug in CPD; it was not picking up files other than .java or .jsp.
Fixed a bug in CallSuperInConstructor; it now checks inner classes/enums more carefully.
Fixed a bug in VariableNamingConventions; it was not setting the warning message properly.
Fixed bug in C/C++ parser; a '$' is now allowed in an identifier. This is useful in VMS.
Fixed a symbol table bug; PMD no longer crashes on enumeration declarations in the same scope containing the same field name
Fixed a bug in ASTVariableDeclaratorId that triggered a ClassCastException if a annotation was used on a parameter.
Added RuleViolation.getBeginColumn()/getEndColumn()
Added an optional 'showSuppressed' item to the Ant task; this is false by default and toggles whether or not suppressed items are shown in the report.
Added an IRuleViolation interface and modified various code classes (include Renderer implementations and Report) to use it.
Modified JJTree grammar to use conditional node descriptors for various expression nodes and to use node suppression for ASTModifier nodes; this replaces a bunch of DiscardableNodeCleaner hackery. It also fixed bug 1445026.
Modified C/CPP grammar to only build the lexical analyzer; we're not using the parser for CPD, just the token manager. This reduces the PMD jar file size by about 50 KB.
New rules:
Basic ruleset: AvoidThreadGroup
Design ruleset: UnsynchronizedStaticDateFormatter
Strings ruleset: InefficientEmptyStringCheck, InsufficientStringBufferDeclaration
JUnit ruleset: SimplifyBooleanAssertion
Basic-JSF ruleset: DontNestJsfInJstlIteration
Basic-JSP ruleset: NoLongScripts, NoScriptlets, NoInlineStyleInformation, NoClassAttribute, NoJspForward, IframeMissingSrcAttribute, NoHtmlComments
Fixed bug 1414985 - ConsecutiveLiteralAppends now checks for intervening references between appends.
Fixed bug 1418424 - ConsecutiveLiteralAppends no longer flags appends in separate methods.
Fixed bug 1416167 - AppendCharacterWithChar now catches cases involving escaped characters.
Fixed bug 1421409 - Ant task now has setter to allow minimumPriority attribute to be used.
Fixed bug 1416164 - InefficientStringBuffering no longer reports false positives on the three argument version of StringBuffer.append().
Fixed bug 1415326 - JUnitTestsShouldContainAsserts no longer errors out on JDK 1.5 generics.
Fixed bug 1415333 - CyclomaticComplexity no longer errors out on JDK 1.5 enums.
Fixed bug 1415663 - PMD no longer fails to parse abstract classes declared in a method.
Fixed bug 1433439 - UseIndexOfChar no longer reports false positives on case like indexOf('a' + getFoo()).
Fixed bug 1435218 - LoggerIsNotStaticFinal no longer reports false positives for local variables.
Fixed bug 1413745 - ArrayIsStoredDirectly no longer reports false positives for array deferences.
Fixed bug 1435751 - Added encoding type of UTF-8 to the CPD XML file.
Fixed bug 1441539 - ConsecutiveLiteralAppends no longer flags appends() involving method calls.
Fixed bug 1339470 - PMD no longer fails to parse certain non-static initializers.
Fixed bug 1425772 - PMD no longer fails with errors in ASTFieldDeclaration when parsing some JDK 1.5 code.
Fixed bugs 1448123 and 1449175 - AvoidFieldNameMatchingTypeName, SingularField, TooManyFields, and AvoidFieldNameMatchingMethodName no longer error out on enumerations.
Fixed bug 1444654 - migrating_to_14 and migrating_to_15 no longer refer to rule tests.
Fixed bug 1445231 - TestClassWithoutTestCases: no longer flags abstract classes.
Fixed bug 1445765 - PMD no longer uses huge amounts of memory. However, you need to use RuleViolation.getBeginLine(); RuleViolation.getNode() is no more.
Fixed bug 1447295 - UseNotifyAllInsteadOfNotify no longer flags notify() methods that have a parameter.
Fixed bug 1455965 - MethodReturnsInternalArray no longer flags variations on 'return new Object[] {}'.
Implemented RFE 1415487 - Added a rulesets/releases/35.xml ruleset (and similar rulesets for previous releases) contains rules new to PMD v3.5
Wouter Zelle fixed a false positive in NonThreadSafeSingleton.
Wouter Zelle fixed a false positive in InefficientStringBuffering.
The CPD Ant task now supports an optional 'language' attribute.
Removed some ill-advised casts from the parsers.
Fixed bug in CallSuperInConstructor; it no longer flag classes without extends clauses.
Fixed release packaging; now entire xslt/ directory contents are included.
Added more XSLT from Dave Corley - you can use them to filter PMD reports by priority level.
You can now access the name of a MemberValuePair node using getImage().
PositionLiteralsFirstInComparisons was rewritten in XPath.
Added a getVersionString method to the TargetJDKVersion interface.
Added an option '--targetjdk' argument to the Benchmark utility.
Applied a patch from Wouter Zelle to clean up the Ant Formatter class, fix a TextRenderer bug, and make toConsole cleaner.
Rewrote AvoidCallingFinalize in Java; fixed bug and runs much faster, too.
Uploaded ruleset schema to http://pmd.sf.net/ruleset_xml_schema.xsd
UseIndexOfChar now catches cases involving lastIndexOf.
Rules are now run in the order in which they're listed in a ruleset file. Internally, they're now stored in a List vs a Set, and RuleSet.getRules() now returns a Collection.
Upgraded to JUnit version 3.8.2.
New rules:
Basic ruleset: UselessOperationOnImmutable, MisplacedNullCheck, UnusedNullCheckInEquals
Migration ruleset: IntegerInstantiation
JUnit ruleset: UseAssertNullInsteadOfAssertTrue
Strings ruleset: AppendCharacterWithChar, ConsecutiveLiteralAppends, UseIndexOfChar
Design ruleset: AvoidConstantsInterface
Optimizations ruleset: UseArraysAsList, AvoidArrayLoops
Controversial ruleset: BooleanInversion
Fixed bug 1371980 - InefficientStringBuffering no longer flags StringBuffer methods other than append().
Fixed bug 1277373 - InefficientStringBuffering now catches more cases.
Fixed bug 1376760 - InefficientStringBuffering no longer throws a NullPointerException when processing certain expressions.
Fixed bug 1371757 - Misleading example in AvoidSynchronizedAtMethodLevel
Fixed bug 1373510 - UseAssertSameInsteadOfAssertTrue no longer has a typo in its message, and its message is more clear.
Fixed bug 1375290 - @SuppressWarnings annotations are now implemented correctly; they accept one blank argument to suppress all warnings.
Fixed bug 1376756 - UselessOverridingMethod no longer throws an exception on overloaded methods.
Fixed bug 1378358 - StringInstantiation no longer throws ClassCastExceptions on certain allocation patterns.
Fixed bug 1371741 - UncommentedEmptyConstructor no longer flags constructors that consist of a this() or a super() invocation.
Fixed bug 1277373 - InefficientStringBuffering no longer flags concatenations that involve a static final String.
Fixed bug 1379701 - CompareObjectsWithEquals no longer flags comparisons of array elements.
Fixed bug 1380969 - UnusedPrivateMethod no longer flags private static methods that are only invoked in a static context from a field declaration.
Fixed bug 1384594 - Added a 'prefix' property for BeanMembersShouldSerializeRule
Fixed bug 1394808 - Fewer missed hits for AppendCharacterWithChar and InefficientStringBuffering, thanks to Allan Caplan for catching these
Fixed bug 1400754 - A NPE is no longer thrown on certain JDK 1.5 enum usages.
Partially fixed bug 1371753 - UnnecessaryLocalBeforeReturn message now reflects the fact that that rule flags all types
Fixed a bug in UseStringBufferLength; it no longers fails with an exception on expressions like StringBuffer.toString.equals(x)
Fixed a bug in CPD's C/C++ parser so that it no longer fails on multi-line literals; thx to Tom Judge for the nice patch.
CPD now recognizes '--language c' and '--language cpp' as both mapping to the C/C++ parser.
Modified renderers to support disabling printing of suppressed warnings. Introduced a new AbstractRenderer class that all Renderers can extends to get the current behavior - that is, suppressed violations are printed.
Implemented RFE 1375435 - you can now embed regular expressions inside XPath rules, i.e., //ClassOrInterfaceDeclaration[matches(@Image, 'F?o')].
Added current CLASSPATH to pmd.bat.
UnusedFormalParameter now catches unused constructor parameters, and its warning message now reflects whether it caught a method or a constructor param.
Rebuilt JavaCC parser with JavaCC 4.0.
Added jakarta-oro-2.0.8.jar as a new dependency to support regular expression in XPath rules.
Ant task now supports a 'minimumPriority' attribute; only rules with this priority or higher will be run.
Renamed Ant task 'printToConsole' attribute to 'toConsole' and it can only be used inside a formatter element.
Added David Corley's Javascript report, more details are here: http://tomcopeland.blogs.com/juniordeveloper/2005/12/demo_of_some_ni.html
New rules:
Basic ruleset: ClassCastExceptionWithToArray, AvoidDecimalLiteralsInBigDecimalConstructor
Design ruleset: NonThreadSafeSingleton, UncommentedEmptyMethod, UncommentedEmptyConstructor
Controversial ruleset: DefaultPackage
Naming ruleset: MisleadingVariableName
Migration ruleset: ReplaceVectorWithList, ReplaceHashtableWithMap, ReplaceEnumerationWithIterator, AvoidEnumAsIdentifier, AvoidAssertAsIdentifier
Strings ruleset: UseStringBufferLength
Fixed bug 1292745 - Removed unused source file ExceptionTypeChecking.java
Fixed bug 1292609 - The JDK 1.3 parser now correctly handles certain 'assert' usages. Also added a 'JDK 1.3' menu item to the Designer.
Fixed bug 1292689 - Corrected description for UnnecessaryLocalBeforeReturn
Fixed bug 1293157 - UnusedPrivateMethod no longer reports false positives for private methods which are only invoked from static initializers.
Fixed bug 1293277 - Messages that used 'pluginname' had duplicated messages.
Fixed bug 1291353 - ASTMethodDeclaration isPublic/isAbstract methods always return true. The syntactical modifier - i.e., whether or not 'public' was used in the source code in the method declaration - is available via 'isSyntacticallyPublic' and 'isSyntacticallyAbstract'
Fixed bug 1296544 - TooManyFields no longer checks the wrong property value.
Fixed bug 1304739 - StringInstantiation no longer crashes on certain String constructor usages.
Fixed bug 1306180 - AvoidConcatenatingNonLiteralsInStringBuffer no longer reports false positives on certain StringBuffer usages.
Fixed bug 1309235 - TooManyFields no longer includes static finals towards its count.
Fixed bug 1312720 - DefaultPackage no longer flags interface fields.
Fixed bug 1312754 - pmd.bat now handles command line arguments better in WinXP.
Fixed bug 1312723 - Added isSyntacticallyPublic() behavior to ASTFieldDeclaration nodes.
Fixed bug 1313216 - Designer was not displaying 'final' attribute for ASTLocalVariableDeclaration nodes.
Fixed bug 1314086 - Added logging-jakarta-commons as a short name for rulesets/logging-jakarta-commons.xml to SimpleRuleSetNameMapper.
Fixed bug 1351498 - Improved UnnecessaryCaseChange warning message.
Fixed bug 1351706 - CompareObjectsWithEquals now catches more cases.
Fixed bug 1277373 (and 1347286) - InefficientStringBuffering now flags fewer false positives.
Fixed bug 1363447 - MissingBreakInSwitch no longer reports false positives for switch statements where each switch label has a return statement.
Fixed bug 1363458 - MissingStaticMethodInNonInstantiatableClass no longer reports cases where there are public static fields.
Fixed bug 1364816 - ImmutableField no longer reports false positives for fields assigned in an anonymous inner class in a constructor.
Implemented RFE 1311309 (and 1119854) - Suppressed RuleViolation counts are now included in the reports.
Implemented RFE 1220371 - Rule violation suppression via annotations. Per the JLS, @SuppressWarnings can be placed before the following nodes: TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE.
Implemented RFE 1275547 - OverrideBothEqualsAndHashcode now skips Comparator implementations.
Applied patch 1306999 - Renamed CloseConnection to CloseResource and added support for checking Statement and ResultSet objects.
Applied patch 1344754 - EmptyCatchBlock now skips catch blocks that contain comments. This is also requested in RFE 1347884.
Renamed AvoidConcatenatingNonLiteralsInStringBuffer to InefficientStringBuffering; new name is a bit more concise.
Modified LongVariable; now it has a property which can be used to override the minimum reporting value.
Improved CPD XML report.
CPD no longer skips header files when checking C/C++ code.
Reworked CPD command line arguments; old-style arguments will still work for one more version, though.
Lots of documentation improvements.
New rules:
Design: PositionLiteralsFirstInComparisons, UnnecessaryLocalBeforeReturn
Logging-jakarta-commons: ProperLogger
Basic: UselessOverridingMethod
Naming: PackageCase, NoPackage
Strings: UnnecessaryCaseChange
Implemented RFE 1220171 - rule definitions can now contain a link to an external URL for more information on that rule - for example, a link to the rule's web page. Thanks to Wouter Zelle for designing and implementing this!
Implemented RFE 1230685 - The text report now includes parsing errors even if no rule violations are reported
Implemented RFE 787860 - UseSingleton now accounts for JUnit test suite declarations.
Implemented RFE 1097090 - The Report object now contains the elapsed time for running PMD. This shows up in the XML report as an elapsedTime attribute in the pmd element in the format '2m 5s' or '1h 5h 35s' or '25s' .
Implemented RFE 1246338 - CPD now handles SCCS directories and NTFS junction points.
Fixed bug 1226858 - JUnitAssertionsShouldIncludeMessage now checks calls to assertFalse.
Fixed bug 1227001 - AvoidCallingFinalize no longer flags calls to finalize() within finalizers.
Fixed bug 1229755 - Fixed typo in ArrayIsStoredDirectly description.
Fixed bug 1229749 - Improved error message when an external rule is not found.
Fixed bug 1224849 - JUnitTestsShouldContainAsserts no longer skips method declarations which include explicit throws clauses.
Fixed bug 1225492 - ConstructorCallsOverridableMethod now reports the correct method name. dvholten's examples in RFE 1235562 also helped with this a great deal.
Fixed bug 1228589 - DoubleCheckedLocking and ExceptionSignatureDeclaration no longer throw ClassCastExceptions on method declarations that declare generic return types.
Fixed bug 1235299 - NullAssignment no longer flags null equality comparisons in ternary expressions.
Fixed bug 1235300 - NullAssignment no longer flags assignments to final fields.
Fixed bug 1240201 - The UnnecessaryParentheses message is no longer restricted to return statements.
Fixed bug 1242290 - The JDK 1.5 parser no longer chokes on nested enumerations with a constructor.
Fixed bug 1242544 - SimplifyConditional no longer flags null checks that precede an instanceof involving an array dereference.
Fixed bug 1242946 - ArrayIsStoredDirectly no longer reports false positives for equality expression comparisons. As a bonus, its message now includes the variable name :-)
Fixed bug 1232648 - MethodReturnsInternalArray no longer reports false positives on return statement expressions that involve method invocations on an internal array.
Fixed bug 1244428 - MissingStaticMethodInNonInstantiatableClass no longer reports warnings for nested classes. Some inner class cases will be missed, but false positives will be eliminated as well.
Fixed bug 1244443 - EqualsNull now catches more cases.
Fixed bug 1250949 - The JDK 1.5 parser no longer chokes on annotated parameters and annotated local variables.
Fixed bug 1245139 - TooManyFields no longer throws a ClassCastException when processing anonymous classes.
Fixed bug 1251256 - ImmutableField no longer skips assignments in try blocks on methods (which led to false positives).
Fixed bug 1250949 - The JDK 1.5 parser no longer chokes on AnnotationTypeMemberDeclaration with a default value.
Fixed bug 1245367 - ImmutableField no longer triggers on assignments in loops in constructors.
Fixed bug 1251269 - AvoidConcatenatingNonLiteralsInStringBuffer no longer triggers on StringBuffer constructors like 'new StringBuffer(1 + getFoo());'
Fixed bug 1244570 - AvoidConcatenatingNonLiteralsInStringBuffer no longer triggers on certain AST patterns involving local variable declarations inside Statement nodes.
Fixed bug 695344 - StringInstantiation no longer triggers on the String(byte[]) constructor.
Fixed bug 1114754 - UnusedPrivateMethod reports fewer false positives.
Fixed bug 1290718 - Command line parameter documentation is now correct for targetjdk options.
Applied patch 1228834 - XPath rules can now use properties to customize rules. Thanks to Wouter Zelle for another great piece of work!
Fixed a bug in RuleSetFactory that missed some override cases; thx to Wouter Zelle for the report and a fix.
Fixed a bug in the grammar that didn't allow constructors to have type parameters, which couldn't parse some JDK 1.5 constructs.
Fixed a bug in ImportFromSamePackage; now it catches the case where a class has an on-demand import for the same package it is in.
Fixed a bug in CompareObjectsWithEquals; now it catches some local variable cases.
Fixed a bug in CouplingBetweenObjects; it no longer triggers an exception (which is a bug in the symbol table layer) by calling getEnclosingClassScope() when the node in question isn't enclosed by one.
Moved AvoidCallingFinalize from the design ruleset to the finalize ruleset and then deleted redundant ExplicitCallToFinalize rule from the finalize ruleset.
Deleted redundant ExceptionTypeChecking rule from the strictexception ruleset; use AvoidInstanceofChecksInCatchClause in the design ruleset instead.
Added some new XSLT scripts that create nifty HTML output; thanks to Wouter Zelle for the code.
Improved UseCorrectExceptionLogging; thx to Wouter Zelle for the new XPath.
Improved warning message from UnusedPrivateMethod.
Improved EmptyIfStmt; now it catches the case where an IfStatement is followed by an EmptyStatement node.
The Ant task now accepts the short names of rulesets (e.g., unusedcode for rulesets/unusedcode.xml).
Removed unnecessary '.html' suffix from displayed filenames when the linkPrefix attribute is used with the HTML renderer.
Added an optional 'description' attribute to the 'property' element in the ruleset XML files.
Added a simplified SimpleNode.addViolation() method to reduce duplicated rule violation creation code.
Moved from jaxen-1.0-fcs.jar/saxpath-1.0-fcs.jar to jaxen-1.1-beta-7.jar. This yielded a 20% speed increase in the basic ruleset!
New rules: UseCorrectExceptionLogging (logging-jakarta-commons ruleset), AvoidPrintStackTrace (logging-java ruleset), CompareObjectsWithEquals (design ruleset)
Fixed bug 1201577 - PMD now correctly parses method declarations that return generic types.
Fixed bug 1205709 - PMD no longer takes a long time to report certain parsing errors.
Fixed bug 1052356 - ImmutableField no longer triggers on fields which are assigned to in a constructor's try statement.
Fixed bug 1215854 - Package/class/method names are now filled in whenever possible, and the XML report includes all three.
Fixed bug 1209719 - MethodArgumentCouldBeFinal no longer triggers on arguments which are modified using postfix or prefix expressions. A bug in AvoidReassigningParameters was also fixed under the same bug id.
Fixed bug 1188386 - MethodReturnsInternalArray no longer flags returning a local array declaration.
Fixed bug 1172137 - PMD no longer locks up when generating a control flow graph for if statements with labelled breaks.
Fixed bug 1221094 - JUnitTestsShouldContainAsserts no longer flags static methods.
Fixed bug 1217028 - pmd.bat now correctly passes parameters to PMD.
Implemented RFE 1188604 - AvoidThrowingCertainExceptionTypes has been split into AvoidThrowingRawExceptionTypes and AvoidThrowingNullPointerException.
Implemented RFE 1188369 - UnnecessaryBooleanAssertion now checks for things like 'assertTrue(!foo)'. These should be changed to 'assertFalse(foo)' for clarity.
Implemented RFE 1199622 - UnusedFormalParameter now defaults to only checking private methods unless a 'checkall' property is set.
Implemented RFE 1220314 - the symbol table now includes some rudimentary type information.
Break and continue statement labels (if present) are placed in the image field.
Fixed bug which caused MissingSerialVersionUID to trigger on all interfaces that implemented other interfaces.
Modified NullAssignmentRule to catch null assignments in ternary expressions.
Added two new node types - ASTCatchStatement and ASTFinallyStatement.
Modified rule XML definition; it no longer includes a symboltable attribute since the symbol table layer is now run for all files analyzed.
Harden equality of AbstractRule and RuleSet objects (needed for the Eclipse plugin features)
Change RuleSet.getRuleByName. Now return null instead of throwing a RuntimeException when the rule is not found
Add .project and .classpath to the module so that it can be checkout as an Eclipse project
New rules: SimplifyStartsWith, UnnecessaryParentheses, CollapsibleIfStatements, UseAssertEqualsInsteadOfAssertTrue, UseAssertSameInsteadOfAssertTrue, UseStringBufferForStringAppends, SimplifyConditional, SingularField
Fixed bug 1170535 - LongVariable now report variables longer than 17 characters, not 12.
Fixed bug 1182755 - SystemPrintln no longer overreports problems.
Fixed bug 1188372 - AtLeastOneConstructor no longer fires on interfaces.
Fixed bug 1190508 - UnnecessaryBooleanAssertion no longer fires on nested boolean literals.
Fixed bug 1190461 - UnusedLocal no longer misses usages which are on the RHS of a right bit shift operator.
Fixed bug 1188371 - AvoidInstantiatingObjectsInLoops no longer fires on instantiations in loops when the 'new' keyword is preceded by a 'return' or a 'throw'.
Fixed bug 1190526 - TooManyFields now accepts a property setting correctly, and default lower bound is 15 vs 10.
Fixed bug 1196238 - UnusedImports no longer reports false positives for various JDK 1.5 java.lang subpackages.
Fixed bug 1169731 - UnusedImports no longer reports false positives on types used inside generics. This bug also resulted in a bug in ForLoopShouldBeWhileLoop being fixed, thanks Wim!
Fixed bug 1187325 - UnusedImports no longer reports a false positive on imports which are used inside an Annotation.
Fixed bug 1189720 - PMD no longer fails to parse generics that use 'member selectors'.
Fixed bug 1170109 - The Ant task now supports an optional 'targetjdk' attribute that accepts values of '1.3', '1.4', or '1.5'.
Fixed bug 1183032 - The XMLRenderer no longer throws a SimpleDateFormat exception when run with JDK 1.3.
Fixed bug 1097256 - The XMLRenderer now supports optional encoding of UTF8 characters using the 'net.sourceforge.pmd.supportUTF8' environment variable.
Fixed bug 1198832 - AbstractClassWithoutAbstractMethod no longer flags classes which implement interfaces since these can partially implement the interface and thus don't need to explicitly declare abstract methods.
Implemented RFE 1193979 - BooleanInstantiation now catches cases like Boolean.valueOf(true)
Implemented RFE 1171095 - LabeledStatement nodes now contain the image of the label.
Implemented RFE 1176401 - UnusedFormalParameter now flags public methods.
Implemented RFE 994338 - The msg produced by ConstructorCallsOverridableMethod now includes the offending method name.
Modified command line parameters; removed -jdk15 and -jdk13 parameters and added a -'targetjdk [1.3|1.4|1.5]' parameter.
Modified CSVRenderer to include more columns.
Optimized rules: FinalFieldCouldBeStatic (115 seconds to 7 seconds), SuspiciousConstantFieldName (48 seconds to 14 seconds), UnusedModifer (49 seconds to 4 seconds)
New rules: MissingSerialVersionUID, UnnecessaryFinalModifier, AbstractClassDoesNotContainAbstractMethod, MissingStaticMethodInNonInstantiatableClass, AvoidSynchronizedAtMethodLevel, AvoidCallingFinalize, UseNotifyAllInsteadOfNotify, MissingBreakInSwitch, AvoidInstanceofChecksInCatchClause, AvoidFieldNameMatchingTypeName, AvoidFieldNameMatchingMethodName, AvoidNonConstructorMethodsWithClassName, TestClassWithoutTestCases, TooManyFields, CallSuperInConstructor, UnnecessaryBooleanAssertion, UseArrayListInsteadOfVector
Implemented RFE 1058039 - PMD's command line interface now accepts abbreviated names for the standard rulesets; for example 'java net.sourceforge.pmd.PMD /my/source/code/ text basic,unusedcode' would run the rulesets/basic.xml and the rulesets/unusedcode.xml rulesets on the source in /my/source/code and produce a text report.
Implemented RFE 1119851 - PMD's Ant task now supports an 'excludeMarker' attribute.
Fixed bug 994400 - False +: ConstructorCallsOverridableMethodRule, thanks to ereissner for reporting it
Fixed bug 1146116 - JUnitTestsShouldIncludeAssert no longer crashes on inner Interface
Fixed bug 1114625 - UnusedPrivateField no longer throws an NPE on standalone postfix expressions which are prefixed with 'this'.
Fixed bug 1114020 - The Ant task now reports a complete stack trace when run with the -verbose flag.
Fixed bug 1117983 - MethodArgumentCouldBeFinal no longer reports false positives on try..catch blocks.
Fixed bug 797742 - PMD now parses JDK 1.5 source code. Note that it's not perfect yet; more testing/bug reports are welcome!
Fixed a bug - the StatisticalRule no longer 'merges' data points when using the 'topscore' property.
Fixed a bug - the PMD Ant task's failOnRuleViolation attribute no longer causes a BuildException in the case when no rule violations occur.
Modified the XSLT to add a summary section.
Added Ruby support to CPD.
Optimized various rules and wrote a benchmarking application; results are here - http://infoether.com/~tom/pmd_timing.txt
Fixed bug 1113927 - ExceptionAsFlowControl no longer throws NPEs on code where a throw statement exists without a try statement wrapping it.
Fixed bug 1113981 - AvoidConcatenatingNonLiteralsInStringBuffer no longer throws NPEs on code where an append appears as a child of an ExplicitConstructorInvocation node.
Fixed bug 1114039 - AvoidInstantiatingObjectsInLoops's message no longer contains a spelling error.
Fixed bug 1114029 - The 'optimization' rules no longer throw NPEs at various points.
Fixed bug 1114251 - The 'sunsecure' rules no longer throw NPEs at various points.
New rules: LocalVariableCouldBeFinal, MethodArgumentCouldBeFinal, AvoidInstantiatingObjectsInLoops, ArrayIsStoredDirectly, MethodReturnsInternalArray, AssignmentToNonFinalStatic, AvoidConcatenatingNonLiteralsInStringBuffer
Fixed bug 1088459 - JUnitTestsShouldContainAsserts no longer throws ClassCastException on interface, native, and abstract method declarations.
Fixed bug 1100059 - The Ant task now generates a small empty-ish report if there are no violations.
Implemented RFE 1086168 - PMD XML reports now contain a version and timestamp attribute in the <pmd> element.
Implemented RFE 1031950 - The PMD Ant task now supports nested ruleset tags
Fixed a bug in the rule override logic; it no longer requires the "class" attribute of a rule be listed in the overrides section.
Added 'ignoreLiterals' and 'ignoreIdentifiers' boolean options to the CPD task.
Cleaned up a good bit of the symbol table code; thanks much to Harald Gurres for the patch.
CPD now contains a generic copy/paste checker for programs in any language
New rules: AvoidProtectedFieldInFinalClass, SystemPrintln
Fixed bug 1050173 - ImmutableFieldRule no longer reports false positives for static fields.
Fixed bug 1050286 - ImmutableFieldRule no longer reports false positives for classes which have multiple constructors only a subset of which set certain fields.
Fixed bug 1055346 - ImmutableFieldRule no longer reports false positive on preinc/predecrement/postfix expressions.
Fixed bug 1041739 - EmptyStatementNotInLoop no longer reports false positives for nested class declarations in methods.
Fixed bug 1039963 - CPD no longer fails to parse C++ files with multi-line macros.
Fixed bug 1053663 - SuspiciousConstantFieldName no longer reports false positives for interface members.
Fixed bug 1055930 - CouplingBetweenObjectsRule no longer throws a NPE on interfaces
Fixed a possible NPE in dfa.report.ReportTree.
Implemented RFE 1058033 - Renamed run.[sh|bat] to pmd.[sh|bat].
Implemented RFE 1058042 - XML output is more readable now.
Applied patch 1051956 - Rulesets that reference rules using "ref" can now override various properties.
Applied patch 1070733 - CPD's Java checker now has an option to ignore both literals and identifiers - this can help find large duplicate code blocks, but can also result in false positives.
YAHTMLRenderer no longer has dependence on Ant packages.
Modified the AST to correctly include PostfixExpression nodes. Previously a statement like "x++;" was embedded in the parent StatementExpression node.
Moved BooleanInstantiation from the design ruleset to the basic ruleset.
Updated Xerces libraries to v2.6.2.
Many rule names had the word "Rule" tacked on to the end. Various folks thought this was a bad idea, so here are the new names of those rules which were renamed:
- basic.xml: UnnecessaryConversionTemporary, OverrideBothEqualsAndHashcode, DoubleCheckedLocking
- braces.xml: WhileLoopsMustUseBraces, IfElseStmtsMustUseBraces, ForLoopsMustUseBraces
- clone.xml: ProperCloneImplementation
- codesize.xml: CyclomaticComplexity, ExcessivePublicCount
- controversial.xml: UnnecessaryConstructor, AssignmentInOperand, DontImportSun, SuspiciousOctalEscape
- coupling.xml: CouplingBetweenObjects, ExcessiveImports, LooseCoupling
- design.xml: UseSingleton, SimplifyBooleanReturns, AvoidReassigningParameters, ConstructorCallsOverridableMethod, AccessorClassGeneration, CloseConnection, OptimizableToArrayCall, IdempotentOperations. ImmutableField
- junit.xml: JUnitAssertionsShouldIncludeMessage, JUnitTestsShouldIncludeAssert
- logging-java.xml: MoreThanOneLogger, LoggerIsNotStaticFinal
- naming.xml: ShortMethodName, VariableNamingConventions, ClassNamingConventions, AbstractNaming
- strictexception.xml: ExceptionAsFlowControl, AvoidCatchingNPE, AvoidThrowingCertainExceptionTypes
Continued working on JDK 1.5 compatibility - added support for static import statements, varargs, and the new for loop syntax
- still TODO: generics and annotations (note that autoboxing shouldn't require a grammar change)
- Good article on features: http://java.sun.com/developer/technicalArticles/releases/j2se15/
New rules: InstantiationToGetClass, IdempotentOperationsRule, SuspiciousEqualsMethodName, SimpleDateFormatNeedsLocale, JUnitTestsShouldContainAssertsRule, SuspiciousConstantFieldName, ImmutableFieldRule, MoreThanOneLoggerRule, LoggerIsNotStaticFinalRule, UseLocaleWithCaseConversions
Applied patch in RFE 992576 - Enhancements to VariableNamingConventionsRule
Implemented RFE 995910 - The HTML report can now include links to HTMLlized source code - for example, the HTML generated by JXR.
Implemented RFE 665824 - PMD now ignores rule violations in lines containing the string 'NOPMD'.
Fixed bug in SimplifyBooleanExpressions - now it catches more cases.
Fixed bugs in AvoidDuplicateLiterals - now it ignores small duplicate literals, its message is more helpful, and it catches more cases.
Fixed bug 997893 - UnusedPrivateField now detects assignments to members of private fields as a usage.
Fixed bug 1020199 - UnusedLocalVariable no longer flags arrays as unused if an assignment is made to an array slot.
Fixed bug 1027133 - Now ExceptionSignatureDeclaration skips certain JUnit framework methods.
Fixed bug 1008548 - The 'favorites' ruleset no longer contains a broken reference.
Fixed bug 1045583 - UnusedModifier now correctly handles anonymous inner classes within interface field declarations.
Partially fixed bug 998122 - CloseConnectionRule now checks for imports of java.sql before reporting a rule violation.
Applied patch 1001694 - Now PMD can process zip/jar files of source code.
Applied patch 1032927 - The XML report now includes the rule priority.
Added data flow analysis facade from Raik Schroeder.
Added two new optional attributes to rule definitions - symboltable and dfa. These allow the symbol table and DFA facades to be configured on a rule-by-rule basis. Note that if your rule needs the symbol table; you'll need to add symboltable="true" to your rule definition. FWIW, this also results in about a 5% speedup for rules that don't need either layer.
Added a "logging" ruleset - thanks to Miguel Griffa for the code!
Enhanced the ASTViewer - and renamed it 'Designer' - to display data flows.
Moved development environment to Maven 1.0.
Moved development environment to Ant 1.6.2. This is nice because using the new JUnit task attribute "forkmode='perBatch'" cuts test runtime from 90 seconds to 7 seconds. Sweet.
MethodWithSameNameAsEnclosingClass now reports a more helpful line number.
New rules: CloneMethodMustImplementCloneable, CloneThrowsCloneNotSupportedException, EqualsNull, ConfusingTernary
Created new "clone" ruleset and moved ProperCloneImplementationRule over from the design ruleset.
Moved LooseCoupling from design.xml to coupling.xml.
Some minor performance optimizations - removed some unnecessary casts from the grammar, simplified some XPath rules.
Postfix expressions (i.e., x++) are now available in the grammar. To access them, search for StatementExpressions with an image of "++" or "--" - i.e., in XPath, //StatementExpression[@Image="++"]. This is an odd hack and hopefully will get cleared up later.
Ant task and CLI now used BufferedInputStreams.
Converted AtLeastOneConstructor rule from Java code to XPath.
Implemented RFE 743460: The XML report now contains the ruleset name.
Implemented RFE 958714: Private field and local variables that are assigned but not used are now flagged as unused.
Fixed bug 962782 - BeanMembersShouldSerializeRule no longer reports set/is as being a violation.
Fixed bug 977022 - UnusedModifier no longer reports false positives for modifiers of nested classes in interfaces
Fixed bug 976643 - IfElseStmtsMustUseBracesRule no longer reports false positives for certain if..else constructs.
Fixed bug 985961 - UseSingletonRule now fires on classes which contain static fields
Fixed bug 977031 - FinalizeDoesNotCallSuperFinalize no longer reports a false positive when a finalizer contains a call to super.finalize in a try {} finally {} block.
New rules: ExceptionAsFlowControlRule, BadComparisonRule, AvoidThrowingCertainExceptionTypesRule, AvoidCatchingNPERule, OptimizableToArrayCallRule
Major grammar changes - lots of new node types added, many superfluous nodes removed from the runtime AST. Bug 786611 - http://sourceforge.net/tracker/index.php?func=detail&aid=786611&group_id=56262&atid=479921 - explains it a bit more.
Fixed bug 786611 - Expressions are no longer over-expanded in the AST
Fixed bug 874284 - The AST now contains tokens for bitwise or expressions - i.e., "|"
Moved development environment to Maven 1.0-RC2.
Fixed bug 925840 - Messages were no longer getting variable names plugged in correctly
Fixed bug 919308 - XMLRenderer was still messed up; 'twas missing a quotation mark.
Fixed bug 923410 - PMD now uses the default platform character set encoding; optionally, you can pass in a character encoding to use.
Implemented RFE 925839 - Added some more detail to the UseSingletonRule.
Added an optional 'failuresPropertyName' attribute to the Ant task.
Refactored away duplicate copies of XPath rule definitions in regress/, yay!
Removed manifest from jar file; it was only there for the Main-class attribute, and it's not very useful now since PMD has several dependencies.
Began working on JDK 1.5 compatibility - added support for EnumDeclaration nodes.
Fixed bug 895661 - XML reports containing error elements no longer have malformed XML.
Fixed a bug in UnconditionalIfStatement - it no longer flags things like "if (x==true)".
Applied Steve Hawkins' improvements to CPD:
- Various optimizations; now it runs about 4 times faster!
- fixed "single match per file" bug
- tweaked source code slicing
- CSV renderer
Added two new renderers - SummaryHTMLRenderer and PapariTextRenderer.
Moved development environment to Ant 1.6 and JavaCC 3.2.
New rules: DontImportSunRule, EmptyFinalizer, EmptyStaticInitializer, AvoidDollarSigns, FinalizeOnlyCallsSuperFinalize, FinalizeOverloaded, FinalizeDoesNotCallSuperFinalize, MethodWithSameNameAsEnclosingClass, ExplicitCallToFinalize, NonStaticInitializer, DefaultLabelNotLastInSwitchStmt, NonCaseLabelInSwitchStatement, SuspiciousHashcodeMethodName, EmptyStatementNotInLoop, SuspiciousOctalEscapeRule
FinalizeShouldBeProtected moved from design.xml to finalizers.xml.
Added isTrue() to ASTBooleanLiteral.
Added UnaryExpression to the AST.
Added isPackagePrivate() to AccessNode.
New rules: AbstractNamingRule, ProperCloneImplementationRule
Fixed bug 840926 - AvoidReassigningParametersRule no longer reports a false positive when assigning a value to an array slot when the array is passed as a parameter to a method
Fixed bug 760520 - RuleSetFactory is less strict about whitespace in ruleset.xml files.
Fixed bug 826805 - JumbledIncrementorRule no longer reports a false positive when a outer loop incrementor is used as an array index
Fixed bug 845343 - AvoidDuplicateLiterals now picks up cases when a duplicate literal appears in field declarations.
Fixed bug 853409 - VariableNamingConventionsRule no longer requires that non-static final fields be capitalized
Fixed a bug in OverrideBothEqualsAndHashcodeRule; it no longer reports a false positive when equals() is passed the fully qualified name of Object.
Implemented RFE 845348 - UnnecessaryReturn yields more useful line numbers now
Added a ruleset DTD and a ruleset XML Schema.
Added 'ExplicitExtends' and 'ExplicitImplements' attributes to UnmodifiedClassDeclaration nodes.
Relicensed under a BSD-style license.
Fixed bug 822245 - VariableNamingConventionsRule now handles interface fields correctly.
Added new rules: EmptySynchronizedBlock, UnnecessaryReturn
ASTType now has an getDimensions() method.
Added new rule: CloseConnectionRule
Fixed bug 782246 - FinalFieldCouldBeStatic no longer flags fields in interfaces.
Fixed bug 782235 - "ant -version" now prints more details when a file errors out.
Fixed bug 779874 - LooseCouplingRule no longer triggers on ArrayList
Fixed bug 781393 - VariableNameDeclaration no longer throws ClassCastExpression since ASTLocalVariableDeclaration now subclasses AccessNode
Fixed bug 797243 - CPD XML report can no longer contain ]]> (CDEnd)
Fixed bug 690196 - PMD now handles both JDK 1.3 and 1.4 code - i.e., usage of "assert" as an identifier.
Fixed bug 805092 - VariableNamingConventionsRule no longer flags serialVersionUID as a violation
Fixed bug - Specifying a non-existing rule format on the command line no longer results in a ClassNotFoundException.
XPath rules may now include pluggable parameters. This feature is very limited. For now.
Tweaked CPD time display field
Made CPD text fields uneditable
Added more error checking to CPD GUI input
Added "dialog cancelled" check to CPD "Save" function
Added Boris Gruschko's AST viewer.
Added Jeff Epstein's TextPad integration.
ASTType now has an isArray() method.
Fixed bug 781077 - line number "-1" no longer appears for nodes with siblings.
Added new rules: VariableNamingConventionsRule, MethodNamingConventionsRule, ClassNamingConventionsRule, AvoidCatchingThrowable, ExceptionSignatureDeclaration, ExceptionTypeChecking, BooleanInstantiation
Fixed bug 583047 - ASTName column numbers are now correct
Fixed bug 761048 - Symbol table now creates a scope level for anonymous inner classes
Fixed bug 763529 - AccessorClassGenerationRule no longer crashes when given a final inner class
Fixed bug 771943 - AtLeastOneConstructorRule and UnnecessaryConstructorRule no longer reports false positives on inner classes.
Applied patch from Chris Webster to fix another UnnecessaryConstructorRule problem.
Added ability to accept a comma-delimited string of files and directories on the command line.
Added a CSVRenderer.
Added a "-shortfilenames" argument to the PMD command line interface.
Modified grammer to provide information on whether an initializer block is static.
ASTViewer now shows node images and modifiers
ASTViewer now saves last edited text to ~/.pmd_astviewer
Moved the PMD Swing UI into a separate module - pmd-swingui.
Updated license.txt to point to new location.
Added new rules: FinalizeShouldBeProtected, FinalFieldCouldBeStatic, BeanMembersShouldSerializeRule
Removed "verbose" attribute from PMD and CPD Ant tasks; now they use built in logging so you can do a "ant -verbose cpd" or "ant -verbose pmd". Thanks to Philippe T'Seyen for the code.
Added "excludes" feature to rulesets; thanks to Gael Marziou for the suggestion.
Removed "LinkedList" from LooseCouplingRule checks; thx to Randall Schulz for the suggestion.
CPD now processes PHP code.
Added VBHTMLRenderer; thanks to Vladimir Bossicard for the code.
Added "Save" item to CPD GUI; thanks to mcclain looney for the patch.
Fixed bug 732592 - Ant task now accepts a nested classpath element.
Fixed bug 744915 - UseSingletonRule no longer fires on abstract classes, thanks to Pablo Casado for the bug report.
Fixed bugs 735396 and 735399 - false positives from ConstructorCallsOverridableMethodRule
Fixed bug 752809 - UnusedPrivateMethodRule now catches unused private static methods, thanks to Conrad Roche for the bug report.
Added new rules: ReturnFromFinallyBlock, SimplifyBooleanExpressions
Added a new Ant task for CPD; thanks to Andy Glover for the code.
Added ability to specify a class name as a renderer on the command line or in the formatter "type" attribute of the Ant task.
Brian Ewins completely rewrote CPD using a portion of the Burrows-Wheeler Transform - it's much, much, much faster now.
Rebuilt parser with JavaCC 3.0; made several parser optimizations.
The Ant task now accepts a <classpath> element to aid in loading custom rulesets. Thanks to Luke Francl for the suggestion.
Fixed several bugs in UnnecessaryConstructorRule; thanks to Adam Nemeth for the reports and fixes.
All test-data classes have been inlined into their respective JUnit tests.
Added new rules: ConstructorCallsOverridableMethodRule, AtLeastOneConstructorRule, JUnitAssertionsShouldIncludeMessageRule, DoubleCheckedLockingRule, ExcessivePublicCountRule, AccessorClassGenerationRule
The Ant task has been updated; if you set "verbose=true" full stacktraces are printed. Thx to Paul Roebuck for the suggestion.
Moved JUnit rules into their own package - "net.sourceforge.pmd.rules.junit".
Incorporated new ResourceLoader; thanks to Dave Fuller
Incorporated new XPath-based rule definitions; thanks to Dan Sheppard for the excellent work.
Fixed bug 697187 - Problem with nested ifs
Fixed bug 699287 - Grammar bug; good catch by David Whitmore
Added new rules: CyclomaticComplexityRule, AssignmentInOperandRule
Added numbering to the HTMLRenderer; thx to Luke Francl for the code.
Added an optional Ant task attribute 'failOnRuleViolation'. This stops the build if any rule violations are found.
Added an XSLT script for processing the PMD XML report; thx to Mats for the code.
The Ant task now determines whether the formatter toFile attribute is absolute or relative and routes the report appropriately.
Moved several rules into a new "controversial" ruleset.
Fixed bug 672742 - grammar typo was hosing up ASTConstructorDeclaration which was hosing up UseSingletonRule
Fixed bug 674393 - OnlyOneReturn rule no longer counts returns that are inside anonymous inner classes as being inside the containing method. Thx to C. Lamont Gilbert for the bug report.
Fixed bug 674420 - AvoidReassigningParametersRule no longer counts parameter field reassignment as a violation. Thx to C. Lamont Gilbert for the bug report.
Fixed bug 673662 - The Ant task's "failOnError" attribute works again. Changed the semantics of this attribute, though, so it fails the build if errors occurred. A new attribute 'failOnRuleViolation' serves the purpose of stopping the build if rule violations are found.
Fixed bug 676340 - Symbol table now creates new scope level when it encounters a switch statement. See the bug for code details; generally, this bug would have triggered runtime exceptions on certain blocks of code.
Fixed bug 683465 - JavaCC parser no longer has ability to throw java.lang.Error; now it only throws java.lang.RuntimeExceptions. Thx to Gunnlaugur Thor Briem for a good discussion on this topic.
Fixed bug in OverrideBothEqualsAndHashcodeRule - it no longer bails out with a NullPtrException on interfaces that declare a method signature "equals(Object)". Thx to Don Leckie for catching that.
Added new rules: ImportFromSamePackageRule, SwitchDensityRule, NullAssignmentRule, UnusedModifierRule, ForLoopShouldBeWhileLoopRule
Updated LooseCouplingRule to check for usage of Vector; thx to Vladimir for the good catch.
Updated AvoidDuplicateLiteralsRule to report the line number of the first occurrence of the duplicate String.
Modified Ant task to use a formatter element; this lets you render a report in several formats without having to rerun PMD.
Added a new Ant task attribute - shortFilenames.
Modified Ant task to ignore whitespace in the ruleset attribute
Added rule priority settings.
Added alternate row colorization to HTML renderer.
Fixed bug 650623 - the Ant task now uses relative directories for the report file
Fixed bug 656944 - PMD no longer prints errors to System.out, instead it just rethrows any exceptions
Fixed bug 660069 - this was a symbol table bug; thanks to mcclain looney for the report.
Fixed bug 668119 - OverrideBothEqualsAndHashcodeRule now checks the signature on equals(); thanks to mcclain looney for the report.
Fixed bug 633879: EmptyFinallyBlockRule now handles multiple catch blocks followed by a finally block.
Fixed bug 633892: StringToStringRule false positive exposed problem in symbol table usage to declaration code.
Fixed bug 617971: Statistical rules no longer produce tons of false positives due to accumulated results.
Fixed bug 633209: OnlyOneReturn rule no longer requires the return stmt to be the last statement.
Enhanced EmptyCatchBlockRule to flag multiple consecutive empty catch blocks.
Renamed AvoidStringLiteralsRule to AvoidDuplicateLiteralsRule.
Modified Ant task to truncate file paths to make the HTML output neater.
Added new rules: StringToStringRule, AvoidReassigningParametersRule, UnnecessaryConstructorRule, AvoidStringLiteralsRule
Fixed bug 631010: AvoidDeeplyNestedIfStmtsRule works correctly with if..else stmts now
Fixed bug 631605: OnlyOneReturn handles line spillover now.
Moved AvoidDeeplyNestedIfStmts from the braces ruleset to the design ruleset.
Moved several rules from the design ruleset to the codesize ruleset.
Added a new "favorites" ruleset.
Added new rules: OnlyOneReturnRule, JumbledIncrementerRule, AvoidDeeplyNestedIfStmtsRule
PMD is now built and tested with JUnit 3.8.1 and Ant 1.5.
Added support for IntelliJ's IDEAJ.
Fixed bug 610018 - StringInstantiationRule now allows for String(byte[], int, int) usage.
Fixed bug 610693 - UnusedPrivateInstanceVariable handles parameter shadowing better.
Fixed bug 616535 - Command line interface input checking is better now.
Fixed bug 616615 - Command line interface allows the text renderer to be used now
Fixed a bug - the statistics rules now handle interfaces better.
Added new rules: JUnitSpellingRule, JUnitStaticSuiteRule, StringInstantiationRule
Added new rulesets - junit, strings.
Added a printToConsole attribute to the Ant task so that you can see the report right there in the Ant output.
Fixed bug in PMD GUI - rules are now saved correctly.
Fixed bug 597916 - CPD line counts are accurate now.
Added new rules: UnusedImportsRule, EmptySwitchStmtRule, SwitchStmtsShouldHaveDefaultRule, IfStmtsMustUseBracesRule
Fixed bug 597813 - Rule properties are now parsed correctly
Fixed bug 597905 - UseSingletonRule now resets its state correctly
Moved several rules into a new ruleset - braces.
Improved CPD by removing import statements and package statements from the token set.
Added Metrics API to the Report.
Updated PMD GUI.
Added new rules: LongParameterListRule, SimplifyBooleanReturnsRule
Enhanced statistics rules to support various ways of triggering rule violations
Added rule customization via XML parameters
Enhanced CopyAndPasteDetector; added a GUI
Fixed bug 592060 - UnusedPrivateInstanceVariable handles explicitly referenced statics correctly
Fixed bug 593849 - UnusedPrivateInstanceVariable handles nested classes better
Added new rule: UnusedFormalParameterRule
Fixed bug 588083 - ForLoopsNeedBraces rule correctly handles a variety of for statement formats
Added prototype of the copy and paste detector
Added new rules: UnusedPrivateMethodRule, WhileLoopsMustUseBracesRule, ForLoopsMustUseBracesRule, LooseCouplingRule
Fixed bug 583482 - EmptyCatchBlock and EmptyFinallyBlock no longer report an incorrect line number.
Added new rules: ExcessiveClassLength, ExcessiveMethodLength
DuplicateImportsRule now reports the correct line number.
Fixed bug 582639 - Rule violations are now reported on the proper line
Fixed bug 582509 - Removed unneeded throws clause
Fixed bug 583009 - Now rulesets.properties is in the jar file
Added new rules: DontImportJavaLangRule, DuplicateImportsRule
Added new ruleset: rulesets/imports.xml
Changed sorting of RuleViolations to group Files together.
Changed XML Renderer to improved format.
Created DVSL Stylesheet for the new format.
Moved the Cougaar rules out of the PMD core.
Fixed bug 580093 - OverrideBothEqualsAndHashcodeRule reports a more correct line number.
Fixed bug 581853 - UnusedLocalVariableRule now handles anonymous inner classes correctly.
Fixed bug 580278 - this was a side effect of bug 581853.
Fixed bug 580123 - UnusedPrivateInstanceVariable now checks for instance variable usage in inner classes.
Added new rules: OverrideBothEqualsAndHashcodeRule, EmptyTryBlock, EmptyFinallyBlock
Reports are now sorted by line number
RuleSets can now reference rules in other RuleSets
Fixed bug 579718 - made 'ruleset not found' error message clearer.
Added new rules: UseSingletonRule, ShortVariableRule, LongVariableRule, ShortMethodNameRule
Moved rules into RuleSets which are defined in XML files in the ruleset directory
Ant task:
-Added a 'failonerror' attribute
-Changed 'rulesettype' to 'rulesetfiles'
-Removed 'text' report format; only 'html' and 'xml' are available now
Added new rules: IfElseStmtsMustUseBracesRule, EmptyWhileStmtRule
Modified command line interface to accept a rule set
Fixed bug in EmptyCatchBlockRule
Fixed typo in UnnecessaryConversionTemporaryRule
Moved Ant task to the net.sourceforge.pmd.ant package
Added new HTML report format
Initial release