Many of you probably have already seen the new logo, but now it’s time to actually ship it. The new logowas long ago decided (see#1663).
We decided it’s time to have a modernized logo and get rid of the gun. This allows to includethe logo anywhere without offense.
The official logo is also without a tagline (such as “Code Quality Matters!”) as the tagline created somecontroversies. Without a tagline, we are not limited in the direction of future development of PMD.

The new logo is available from theLogo Project Page.
The Java grammar has been refactored substantially in order to make it easier to maintain and more correctregarding the Java Language Specification. It supports now also the edge-cases where PMD 6 was failing(e.g. annotations were not supported everywhere). Changing the grammar entails a changed AST and therefore changedrules. The PMD built-in rules have all been upgraded and many bugs have been fixed on the way.Unfortunately, if you are using custom rules, you will most probably need to accommodate these changes yourself.
The type resolution framework has been rewritten from scratch and should now cover the entire Java spec correctly.The same is true for the symbol table.PMD 6 on the other hand has always had problems with advanced type inference, e.g. with lambdas and call chains.Since it was built on the core reflection API, it also was prone to linkage errors and classloader leaks for instance.PMD 7 does not need to load classes, and does not have these problems.
The AST exposes much more semantic information now. For instance, you can jump from a method call tothe declaration of the method being called, or from a field access to the field declaration. Theseimprovements allow interesting rules to be written that need precise knowledge of the typesin the program, for instance to detectUnnecessaryBoxingorUseDiamondOperator.These are just a small preview of the new rules we will be adding in the PMD 7 release cycle.
Overall, the changes to the parser, AST, type resolution and symbol table code has made PMD forJavasignificantly faster. On average, we have seen ~2-3X faster analysis, but as usual, this may changedepending on your workload, configuration and ruleset.
Contributors:Clément Fournier (@oowekyala),Andreas Dangel (@adangel),Juan Martín Sotuyo Dodero (@jsotuyod)
Note:The full detailed documentation of the changes to the Java AST are available in theMigration Guide for PMD 7
PMD now ships with a unified Command Line Interface for both Linux/Unix and Windows. Instead of having a collectionof scripts for the different utilities shipped with PMD, a single scriptpmd (pmd.bat for Windows) can nowlaunch all utilities using subcommands, e.g.pmd check,pmd designer. All commands and options are thoroughlydocumented in the help, with full color support where available. Moreover, efforts were made to provide consistencyin the usage of all PMD utilities.
$Usage: pmd[-hV][COMMAND]-h,--help Show thishelpmessage and exit.-V,--version Print version information and exit.Commands: check The PMD standardsourcecode analyzer cpd Copy/Paste Detector - find duplicate code designer The PMD visual rule designer cpd-gui GUIforthe Copy/Paste Detector Warning: May not support the full CPD featuresetast-dump Experimental: dumps the AST of parsingsourcecodeExit Codes: 0 Successful analysis, no violations found 1 An unexpected error occurred during execution 2 Usage error, please refer to thecommand help4 Successful analysis, at least 1 violation foundFor instance, where you previously would have run
run.sh pmd-d src-R ruleset.xmlyou should now use
pmd check-d src-R ruleset.xmlor even better, omit using-d /--dir and simply pass the sources at the end of the parameter list
pmd check-R ruleset.xml srcMultiple source directories can be passed, such as:
pmd check-R ruleset.xml src/main/java src/test/javaAnd the exact same applies to CPD:
pmd cpd--minimum-tokens 100 src/main/javaAdditionally, the CLI for thecheck command has been enhanced with a progress bar, which interactively displays thecurrent progress of the analysis.

This can be disabled with the--no-progress flag.
Finally, we now provide a completion script for Bash/Zsh to further help daily usage.To use it, edit your~/.bashrc /~/.zshrc file and add the following line:
source <(pmd generate-completion)Contributors:Juan Martín Sotuyo Dodero (@jsotuyod)
PMD 6 only supported JavaCC based grammars, but withAntlr parserscan be generated as well. Languages backed by an Antlr grammar are now fully supported. This means, it’s nowpossible not only to use Antlr grammars for CPD, but we can actually build full-fledged PMD rules for them as well.Both the traditional Java visitor rules, and the simpler XPath rules are available to users. This allowsto leverage existing grammars.
We expect this to enable both our dev team and external contributors to largely extend PMD usage for more languages.
Two languages (Swift and Kotlin) already use this new possibility.
See the documentation pageAdding a new language with ANTLRfor instructions on how to use this new feature.
Contributors:Lucas Soncini (@lsoncini),Matías Fraga (@matifraga),Tomás De Lucca (@tomidelucca)
This PMD release ships a new version of the pmd-designer. The designer artifact has beenrenamed from “pmd-ui” to “pmd-designer”. While the designer still works with Java 8, therecommended Java Runtime is Java 11 (or later) with OpenJFX 17 (or later).
For the detailed changes, see
Thanks to @mohan-chinnappan-n a new CPD report format has been added which features a data table.It uses an XSLT stylesheet to convert CPD’s XML format into HTML.
Contributors:Mohan Chinnappan (@mohan-chinnappan-n)
PMD supported Apache Velocity for a very long time, but the CPD integration never got finished.This is now done and CPD supports Apache Velocity Template language for detecting copy and paste.It is shipped in the modulepmd-velocity.
Thanks to a contribution, CPD now supports Coco, a modern programming languagedesigned specifically for building event-driven software. It is shipped in the newmodulepmd-coco.
Contributors:Wener (@wener-tiobe)
Thanks to a contribution, CPD now supports the Julia language. It is shippedin the new modulepmd-julia.
Contributors:Wener (@wener-tiobe)
Thanks to a contribution, CPD now supports the TypeScript language. It is shippedwith the rest of the JavaScript support in the modulepmd-javascript.
Contributors:Paul Guyot (@pguyot)
This release of PMD brings support for Java 21 and 22. There are the following new standard language features,that are supported now:
PMD also supports the following preview language features:
In order to analyze a project with PMD that uses these preview language features,you’ll need to enable it via the environment variablePMD_JAVA_OPTS and select the new languageversion22-preview:
export PMD_JAVA_OPTS=--enable-previewpmd check --use-version java-22-preview ...Note: Support for Java 19 and Java 20 preview language features have been removed. The versions “19-preview” and“20-preview” are no longer available.
PMD now supports Kotlin as an additional language for analyzing source code. It is based onthe official kotlin Antlr grammar for Kotlin 1.8. Java-based rules and XPath-based rules are supported.
We are shipping the following rules:
FunctionNameTooShort finds functions with a tooshort name.OverrideBothEqualsAndHashcode finds classes with onlyeitherequals orhashCode overridden, but not both. This leads to unexpected behavior once instancesof such classes are used in collections (Lists, HashMaps, …).Contributors:Jeroen Borgers (@jborgers),Peter Paul Bakker (@stokpop)
Given the full Antlr support, PMD now fully supports Swift for creating rules. Previously only CPD was supported.
Note: There is only limited support for newer Swift language features in the parser, e.g. Swift 5.9 (Macro Expansions)are supported, but other features are not.
We are pleased to announce we are shipping a number of rules starting with PMD 7.
ForceCast flags all force casts, making sure you aredefensively considering all types. Having the application crash shouldn’t be an option.ForceTry flags all force tries, making sure you aredefensively handling exceptions. Having the application crash shouldn’t be an option.ProhibitedInterfaceBuilder flags any usage of interfacebuilder. Interface builder files are prone to merge conflicts, and are impossible to code review, so largerteams usually try to avoid it or reduce its usage.UnavailableFunction flags any function throwingafatalError not marked as@available(*, unavailable) to ensure no calls are actually performed inthe codebase.Contributors:Lucas Soncini (@lsoncini),Matías Fraga (@matifraga),Tomás De Lucca (@tomidelucca)
When PMD added Apex support with version 5.5.0, it utilized the Apex Jorje library to parse Apex sourceand generate an AST. This library is however a binary-blob provided as part of theSalesforce Extensions for VS Code, and it is closed-source.
This causes problems, if binary blobs are not allowed by e.g. a company-wide policy. In that case, the Jorjelibrary prevented that PMD Apex could be used at all.
Also having access to the source code, enhancements and modifications are easier to do.
Under the hood, we use two open source libraries instead:
Although the parsers is completely switched, there are only little known changes to the AST.These are documented in theMigration Guide for PMD 7: Apex AST.With the new Apex parser, the new language constructs likeUser Mode Database Operationsand the newNull Coalescing Operator??can be parsed now. PMD should be able to parse Apex code up to version 60.0 (Spring ‘24).
See#3766 for details.
Contributors:Aaron Hurst (@aaronhurst-google),Edward Klimoshenko (@eklimo)
--ignore-sequences.--ignore-literal-sequences, onlyliterals were ignored. The new option additionally ignores identifiers as well in sequences.CPD-ON/CPD-OFF comment pairs.Support for HTML was introduced in PMD 6.55.0 as an experimental feature. With PMD 7.0.0 thisis now considered stable.
The JS specific parser options have been removed. The parser now always retains comments and uses version ES6.The language module registers a couple of different versions. The latest version, which supports ES6 and also somenew constructs (seeRhino), is the default. This should be fine for mostuse cases.
We revisited the versions that were defined by each language module. Now many more versions are defined for eachlanguage. In general, you can expect that PMD can parse all these different versions. There might be situationswhere this fails and this can be considered a bug. Usually the latest version is selected as the defaultlanguage version.
The language versions can be used to mark rules to be useful only for a specific language version viatheminimumLanguageVersion andmaximumLanguageVersion attributes. While this feature is currently only used bythe Java module, listing all possible versions enables other languages as well to use this feature.
Related issue:[core] Explicitly name all language versions (#4120)
IntProperty andStringProperty have been removed. Please usePropertyFactory to create properties.,) as a delimiter. The previous default was apipe character (|). The delimiter is not configurable anymore. If needed, the comma can be escapedwith a backslash.min andmax attributes in property definitions in the XML are now optional and can appear separatelyor be omitted.The module was named just “vm” which was not a good name. Its module name, language id andpackage names have been renamed to “velocity”.
If you import rules, you also need to adjust the paths, e.g.
category/vm/... ➡️category/velocity/...There was an inconsistency between the naming of the maven module and the language id. The language idused the abbreviation “vf”, while the maven module used the longer name “visualforce”. This has beensolved by renaming the language module to its full name “visualforce”. The java packages havebeen renamed as well.
If you import rules, you also need to adjust the paths, e.g.
category/vf/security.xml ➡️category/visualforce/security.xmlApex
OperationWithHighCostInLoop finds Schema class methods called in a loop, which is apotential performance issue.UnusedMethod finds unused methods in your code.Java
UnnecessaryBoxing reports boxing and unboxing conversions that may be made implicit.UseExplicitTypes reports usages ofvar keyword, which was introduced with Java 10.Kotlin
FunctionNameTooShort finds functions with a too short name.OverrideBothEqualsAndHashcode finds classes with onlyeitherequals orhashCode overridden, but not both. This leads to unexpected behavior once instancesof such classes are used in collections (Lists, HashMaps, …).Swift
ForceCast flags all force casts, making sure you aredefensively considering all types. Having the application crash shouldn’t be an option.ForceTry flags all force tries, making sure you aredefensively handling exceptions. Having the application crash shouldn’t be an option.ProhibitedInterfaceBuilder flags any usage of interfacebuilder. Interface builder files are prone to merge conflicts, and are impossible to code review, so largerteams usually try to avoid it or reduce its usage.UnavailableFunction flags any function throwingafatalError not marked as@available(*, unavailable) to ensure no calls are actually performed inthe codebase.XML
MissingEncoding finds XML files without explicit encoding.General changes
topscore andsigma have been removed. The propertyminimum is still there, however the type is nota decimal number anymore but has been changed to an integer. This affects rules in the languages Apex, Java, PLSQLand Velocity Template Language (velocity):ExcessiveClassLength,ExcessiveParameterList,ExcessivePublicCount,NcssConstructorCount,NcssMethodCount,NcssTypeCountExcessiveImports,ExcessiveParameterList,ExcessivePublicCount,SwitchDensityExcessiveMethodLength,ExcessiveObjectLength,ExcessivePackageBodyLength,ExcessivePackageSpecificationLength,ExcessiveParameterList,ExcessiveTypeLength,NcssMethodCount,NcssObjectCount,NPathComplexityExcessiveTemplateLengthviolationSuppressXPath which is available for all rules tosuppress warnings now uses XPath version 3.1 by default.This version of the XPath language is mostly identical to XPath 2.0. In PMD 6, XPath 1.0 has been used.If you upgrade from PMD 6, you need to verify yourviolationSuppressXPath properties.Apex General changes
cc_categories,cc_remediation_points_multiplier,cc_block_highlighting have been removedfrom all rules. These properties have been deprecated since PMD 6.13.0.Seeissue #1648 for more details.Apex Codestyle
MethodNamingConventions: The deprecated rule propertyskipTestMethodUnderscores hasbeen removed. It was actually deprecated since PMD 6.15.0, but was not mentioned in the release notesback then. Use the propertytestPattern instead to configure valid names for test methods.Java General changes
Violations reported on methods or classes previously reported the line range of the entire methodor class. With PMD 7.0.0, the reported location is now just the identifier of the method or class.This affects various rules, e.g.CognitiveComplexity.
The report location is controlled by the overrides of the methodNode#getReportLocationin different node types.
Seeissue #4439 andissue #730for more details.
Java Best Practices
ArrayIsStoredDirectly: Violations are now reported on the assignment and notanymore on the formal parameter. The reported line numbers will probably move.AvoidReassigningLoopVariables: This rule might not report anymore allreassignments of the control variable in for-loops when the propertyforReassign is set toskip.Seeissue #4500 for more details.LooseCoupling: The rule has a new property to allow some types to be coupledto (allowedTypes).UnusedLocalVariable: This rule has some important false-negatives fixedand finds many more cases now. For details see issues#2130,#4516, and#4517.Java Codestyle
MethodNamingConventions: The propertycheckNativeMethods has been removed. Theproperty was deprecated since PMD 6.3.0. Use the propertynativePattern to control whether native methodsshould be considered or not.ShortVariable: This rule now also reports short enum constant names.UseDiamondOperator: The propertyjava7Compatibility has been removed. The rule nowhandles Java 7 properly without a property.UnnecessaryFullyQualifiedName: The rule has two new properties,to selectively disable reporting on static field and method qualifiers. The rule also has been improvedto be more precise.UselessParentheses: The rule has two new properties which control how strictthe rule should be applied. WithignoreClarifying (default: true) parentheses that are strictly speakingnot necessary are allowed, if they separate expressions of different precedence.The other propertyignoreBalancing (default: true) is similar, in that it allows parentheses that helpreading and understanding the expressions.EmptyControlStatement: The rule has a new property to allow empty blocks whenthey contain a comment (allowCommentedBlocks).Java Design
CyclomaticComplexity: The propertyreportLevel has been removed. The property wasdeprecated since PMD 6.0.0. The report level can now be configured separated for classes and methods usingclassReportLevel andmethodReportLevel instead.ImmutableField: The propertyignoredAnnotations has been removed. The property wasdeprecated since PMD 6.52.0.LawOfDemeter: The rule has a new propertytrustRadius. This defines the maximum degreeof trusted data. The default of 1 is the most restrictive.NPathComplexity: The propertyminimum has been removed. It was deprecated since PMD 6.0.0.Use the propertyreportLevel instead.SingularField: The propertiescheckInnerClasses anddisallowNotAssignment have been removed.The rule is now more precise and will check these cases properly.UseUtilityClass: The propertyignoredAnnotations has been removed.Java Documentation
CommentContent: The propertiescaseSensitive anddisallowedTerms are removed. Thenew propertyforbiddenRegex can be used now to define the disallowed terms with a single regularexpression.CommentRequired:@Overrideannotation. This is relevant for the propertymethodWithOverrideCommentRequirement.See alsopull request #3757.headerCommentRequirement has been removed. Use the propertyclassCommentRequirementinstead.CommentSize: When determining the line-length of a comment, the leading commentprefix markers (e.g.* or//) are ignored and don’t add up to the line-length.See alsopull request #4369.Java Error Prone
AvoidDuplicateLiterals: The propertyexceptionfile has been removed. The property wasdeprecated since PMD 6.10.0. Use the propertyexceptionList instead.DontImportSun:sun.misc.Signal is not special-cased anymore.EmptyCatchBlock:CloneNotSupportedException andInterruptedException are notspecial-cased anymore. Rename the exception parameter toignored to ignore them.ImplicitSwitchFallThrough: Violations are now reported on the case statementsrather than on the switch statements. This is more accurate but might result in more violations now.NonSerializableClass: The deprecated propertyprefix has been removedwithout replacement. In a serializable class all fields have to be serializable regardless of the name.In PMD 7.0.0, there are no deprecated rules.
The following previously deprecated rules have been finally removed:
Apex
OperationWithLimitsInLoopOperationWithLimitsInLoopOperationWithLimitsInLoopFieldNamingConventions,FormalParameterNamingConventions,LocalVariableNamingConventions,orPropertyNamingConventionsApexCSRFJava
ClassNamingConventionsFormalParameterNamingConventionsComparisonWithNaNNonSerializableClassUnnecessaryBoxingandPrimitiveWrapperInstantiationUnnecessaryBoxingandPrimitiveWrapperInstantiationUnusedAssignmentCommentDefaultAccessModifierDoNotTerminateVMUnnecessaryImportUnnecessaryImportEmptyControlStatementEmptyControlStatementEmptyControlStatementEmptyControlStatementUnnecessarySemicolonEmptyControlStatementEmptyControlStatementEmptyControlStatementEmptyControlStatementNcssCountNcssCountControlStatementBracesControlStatementBracesControlStatementBracesUnnecessaryImportUnnecessaryBoxingandPrimitiveWrapperInstantiationInvalidLogMessageFormatProperLoggerUnnecessaryBoxingandPrimitiveWrapperInstantiationFieldNamingConventions,FormalParameterNamingConventions,orLocalVariableNamingConventionsImplicitSwitchFallThroughCyclomaticComplexityNcssCountNcssCountNcssCountLiteralsFirstInComparisonsLiteralsFirstInComparisonsReturnEmptyCollectionRatherThanNullUnnecessaryBoxingandPrimitiveWrapperInstantiationSimplifiableTestAssertionCyclomaticComplexityFieldNamingConventionsUnnecessaryBoxingUnsynchronizedStaticFormatterUnnecessaryImportSimplifiableTestAssertionSimplifiableTestAssertionSimplifiableTestAssertionSimplifiableTestAssertionFieldNamingConventions,FormalParameterNamingConventions, orLocalVariableNamingConventionsControlStatementBracesThe following previously deprecated rulesets have been removed. These were the left-over rulesets from PMD 5.The rules have been moved into categories with PMD 6.
Note:The full detailed documentation of the changes are available in theMigration Guide for PMD 7
run.sh pmd ... ➡️pmd check ...,run.sh cpd ... ➡️pmd cpd ...).violationSuppressXPath now requires XPath 3.1: Custom rulesets needto be reviewed.AbstractRule#buildTargetSelectorusingRuleTargetSelector#forTypes.The asset filenames of PMD onGitHub Releases arenowpmd-dist-<version>-bin.zip,pmd-dist-<version>-src.zip andpmd-dist-<version>-doc.zip.Keep that in mind, if you have an automated download script.
The structure inside the ZIP files stay the same, e.g. we still provide inside the binary distributionZIP file the base directorypmd-bin-<version>.
pmd-core has been moved into its own modulepmd-ant,which needs to be added explicitly now as an additional dependency.pmd-core into its own modulepmd-cli. The old entry point, themain classPMD is gone.The API of PMD has been growing over the years and needed some cleanup. The goal is, tohave a clear separation between a well-defined API and the implementation, which is internal.This should help us in future development.
This however entails some incompatibilities and deprecations.
SeeADR 3 - API evolution principles andAPI changes below.
#1648: [apex,vf] Remove CodeClimate dependency -Robert SösemannProperties “cc_categories”, “cc_remediation_points_multiplier”, “cc_block_highlighting” can no longer be overridden in rulesets.They were deprecated without replacement.
The old GUI applications accessible throughrun.sh designerold andrun.sh bgastviewer(and corresponding Batch scripts) have been removed from the PMD distribution. Please use the newer rule designerwithpmd designer. The corresponding classes in packagesjava.net.sourceforge.pmd.util.viewer andjava.net.sourceforge.pmd.util.designer have all been removed.
All API related to XPath support has been moved to the packagenet.sourceforge.pmd.lang.rule.xpath.This includes API that was previously dispersed overnet.sourceforge.pmd.lang,net.sourceforge.pmd.lang.ast.xpath,net.sourceforge.pmd.lang.rule.xpath,net.sourceforge.pmd.lang.rule, and various language-specific packages(which were made internal).
The implementation of the Ant integration has been moved from the modulepmd-core to a new modulepmd-ant.This involves classes in packagenet.sourceforge.pmd.ant. The ant CPDTask classnet.sourceforge.pmd.cpd.CPDTaskhas been moved into the same packagenet.sourceforge.pmd.ant. You’ll need to update your taskdef entries in yourbuild.xml files with the FQCNnet.sourceforge.pmd.ant.CPDTask if you use it anywhere.
Utility classes innet.sourceforge.pmd.util, that have previously marked as@InternalApi have been finallymoved to an internal sub package and are now longer available.This includes ClasspathClassLoader, FileFinder, FileUtil, and IOUtil.
net.sourceforge.pmd.util are now considered public API:AntlrCpdLexer andJavaccCpdLexer frominternal package into packagenet.sourceforge.pmd.cpd.impl. These two classes are part of the API andare base classes for CPD language implementations. Since 7.0.0-rc2.Note: These two classes have been previously called “AntlrTokenizer” and “JavaCCTokenizer”.AntlrBaseRule is gone in favor ofAbstractVisitorRule. Since 7.0.0-rc2.net.sourceforge.pmd.lang.kotlin.ast.KotlinInnerNode andnet.sourceforge.pmd.lang.swift.ast.SwiftInnerNode are package-private now. Since 7.0.0-rc2.Support for XPath versions 1.0, 1.0-compatibility, 2.0 was removed. The default(and only) supported XPath version is now XPath 3.1. This version of the XPath language is mostly identical toXPath 2.0.
Notable changes:
This version includes a powerful API to navigate trees, similar in usage to the Java 8 Stream API:
node.descendants(ASTMethodCall.class).filter(m->"toString".equals(m.getMethodName())).map(m->m.getQualifier()).filter(q->TypeTestUtil.isA(String.class,q)).foreach(System.out::println);A pipeline like shown here traverses the tree lazily, which is more efficient than traversing eagerly to put alldescendants in a list. It is also much easier to change than the old imperative way.
To make this API as accessible as possible, theNode interface has been fitted with newmethods producing node streams. Those methods replace previous tree traversal methods likeNode#findDescendantsOfType.In all cases, they should be more efficient and more convenient.
SeeNodeStream for more details.
Contributors:Clément Fournier (@oowekyala)
The metrics framework has been made simpler and more general.
The metric interface takes an additional type parameter, representing the result type of the metric. This isusuallyInteger orDouble. It avoids widening the result to adouble just to narrow it down.
This makes it so, thatDouble.NaN is not an appropriate sentinel value to represent “not supported” anymore.Instead,computeFor may returnnull in that case (or a garbage value). The valuenull may have causedproblems with the narrowing casts, which through unboxing, might have thrown an NPE. But when we deprecatedthe language-specific metrics façades to replace them with the genericMetricsUtil,we took care of makingthe new methods throw an exception if the metric cannot be computed on the parameter. This forces you to guardcalls toMetricsUtil#computeMetric (and other overloads)with something likeif (metric.supports(node)). If you’re followingthis pattern, then you won’t observe the undefined behavior.
TheMetricKey interface is not so useful and has been merged into theMetricinterface and removed. So theMetric interface has the new methoddisplayName.
The framework is not tied to at most 2 node types per language anymore. Previously those were nodes forclasses and for methods/constructors. Instead, many metrics support more node types. For example, NCSS canbe computed on any code block.
For that reason, keeping around a hard distinction between “class metrics” and “operation metrics” is notuseful. So in the Java framework for example, we removed the interfacesJavaClassMetric,JavaOperationMetric,abstract classes for those,JavaClassMetricKey, andJavaOperationMetricKey. Metric constants are now allinside theJavaMetrics utility class. The same was done in the Apex framework.
We don’t really need abstract classes for metrics now. SoAbstractMetric is also removed from pmd-core.There is a factory method on theMetric interface to create a metric easily.
This makes it so, thatLanguageMetricsProvider does not need type parameters.It can just return aSet<Metric<?, ?>> to list available metrics.
Signatures, their implementations, and the interfaceSignedNode have beenremoved. Node streams allow replacing their usages very easily.
net.sourceforge.pmd.testframework.PMDTestRunnernet.sourceforge.pmd.testframework.RuleTestRunnernet.sourceforge.pmd.testframework.TestDescriptorSimpleAggregatorTst orPmdRuleTst work as before without change, but usenow JUnit5 under the hood. If you added additional JUnit4 tests to your rule test classes, then you’llneed to upgrade them to use JUnit5.The documentation page has been updated:Adding a new language with JavaCCandAdding a new language with ANTLR
Related issue:[core] Language lifecycle (#3782)
IntProperty andStringProperty have been removed. Please usePropertyFactory to create properties.,) as a delimiter. The previous default was apipe character (|). The delimiter is not configurable anymore. If needed, the comma can be escapedwith a backslash.min andmax attributes in property definitions in the XML are now optional and can appear separatelyor be omitted.This release introduces a new programmatic API to replace the old classCPD. The new API uses a similar model toPmdAnalysis and is calledCpdAnalysis. Programmatic execution of CPD should now bedone with aCPDConfiguration and aCpdAnalysis, for instance:
CPDConfigurationconfig=newCPDConfiguration();config.setMinimumTileSize(100);config.setOnlyRecognizeLanguage(config.getLanguageRegistry().getLanguageById("java"));config.setSourceEncoding(StandardCharsets.UTF_8);config.addInputPath(Path.of("src/main/java")config.setIgnoreAnnotations(true);config.setIgnoreLiterals(false);config.setRendererName("text");try(CpdAnalysiscpd=CpdAnalysis.create(config)){// note: don't use `config` once a CpdAnalysis has been created.// optional: add more filescpd.files().addFile(Paths.get("src","main","more-java","ExtraSource.java"));cpd.performAnalysis();}CPD can of course still be called via command line or using the modulepmd-cli. But for tight integrationthis new programmatic API is recommended.
SeePR #4397 for details.
These are the changes between 7.0.0-rc4 and final 7.0.0.
pmd-java
ASTPattern,ASTRecordPattern,ASTTypePattern,ASTUnnamedPatterngetParenthesisDepth() has been removed.ASTTemplateFragment: To get the content of the template, use nowgetContent or@Content instead ofgetImage()/@Image.ASTUnnamedPattern is not experimental anymore. The language featurehas been standardized with Java 22.New API
The API aroundTreeRenderer has been declared as stable. It was previouslyexperimental. It can be used via the CLI subcommandast-dump or programmatically, as describedonCreating XML dump of the AST.
General AST Changes to avoid@Image
SeeGeneral AST Changes to avoid @Imagein the migration guide for details.
XPath Rules
version was already deprecated and has finally been removed. Please don’t define the versionproperty anymore in your custom XPath rules. By default, the latest XPath version will be used, whichis XPath 3.1.Moved classes/consolidated packages
net.sourceforge.pmd into subpackagenet.sourceforge.pmd.lang.rulenet.sourceforge.pmd into subpackagenet.sourceforge.pmd.reportingXPathRule has been moved into subpackagenet.sourceforge.pmd.lang.rule.xpath.net.sourceforge.pmd.lang.html.ast.HtmlCpdLexer moved into packagecpd:HtmlCpdLexer.net.sourceforge.pmd.lang.test:AbstractMetricTestRule (moved fromnet.sourceforge.pmd.test.AbstractMetricTestRule)BaseTextComparisonTest (moved fromnet.sourceforge.pmd.test.BaseTextComparisonTest)CpdTextComparisonTest (moved fromnet.sourceforge.pmd.cpd.test.CpdTextComparisonTest)BaseTreeDumpTest (moved fromnet.sourceforge.pmd.lang.ast.test.BaseTreeDumpTest)net.sourceforge.pmd.lang.ast.test tonet.sourceforge.pmd.lang.test.ScalaCpdLexer (moved fromnet.sourceforge.pmd.lang.scala.cpd.ScalaCpdLexer)ScalaTokenAdapter (moved fromnet.sourceforge.pmd.lang.scala.cpd.ScalaTokenAdapter)AbstractRuleSetFactoryTest (moved fromnet.sourceforge.pmd.lang.rule.AbstractRuleSetFactoryTest)AbstractAntTestHelper (moved fromnet.sourceforge.pmd.ant.AbstractAntTestHelper)AbstractLanguageVersionTest (moved fromnet.sourceforge.pmd.AbstractLanguageVersionTest)PmdRuleTst (moved fromnet.sourceforge.pmd.testframework.PmdRuleTst)RuleTst (moved fromnet.sourceforge.pmd.testframework.RuleTst)SimpleAggregatorTst (moved fromnet.sourceforge.pmd.testframework.SimpleAggregatorTst)PomLanguageModule (moved fromnet.sourceforge.pmd.lang.pom.PomLanguageModule)WsdlLanguageModule (moved fromnet.sourceforge.pmd.lang.wsdl.WsdlLanguageModule)XslLanguageModule (moved fromnet.sourceforge.pmd.lang.xsl.XslLanguageModule)net.sourceforge.pmd.lang.vf has been renamed tonet.sourceforge.pmd.lang.visualforce.visualforce (it was previously just “vf”)category/vf/security.xml ➡️category/visualforce/security.xmlnet.sourceforge.pmd.lang.vm has been renamed tonet.sourceforge.pmd.lang.velocity.velocity (it was previously just “vm”)category/vm/... ➡️category/velocity/...Vm, e.g.VmLanguageModule. This has been changed to beVtl:Internalized classes and interfaces and methods
The following classes/methods have been marked as @InternalApi before and are now moved into ainternalpackage or made (package) private and arenot accessible anymore.
net.sourceforge.pmd.cache.AbstractAnalysisCache (moved to internal, now package private)net.sourceforge.pmd.cache.AnalysisCache (moved to internal)net.sourceforge.pmd.cache.AnalysisCacheListener (moved to internal)net.sourceforge.pmd.cache.AnalysisResult (moved to internal)net.sourceforge.pmd.cache.CachedRuleMapper (moved to internal, now package private)net.sourceforge.pmd.cache.CachedRuleViolation (moved to internal, now package private)net.sourceforge.pmd.cache.ChecksumAware (moved to internal)net.sourceforge.pmd.cache.FileAnalysisCache (moved to internal)net.sourceforge.pmd.cache.NoopAnalysisCache (moved to internal)net.sourceforge.pmd.util.ResourceLoader (moved to internal)net.sourceforge.pmd.cpd.Tokensnet.sourceforge.pmd.lang.LanguageProcessor.AnalysisTaskwithFiles(java.util.List) is now package private. Note: it was not previously marked with @InternalApi.net.sourceforge.pmd.lang.rule.RuleTargetSelectorisRuleChain() has been removed.net.sourceforge.pmd.renderers.AbstractAccumulatingRendererrenderFileReport - this method is now finaland can’t be overridden anymore.net.sourceforge.pmd.reporting.ReportaddRuleViolation,addConfigError,addError are now private.net.sourceforge.pmd.reporting.RuleContextgetRule() is now package private.create(FileAnalysisListener listener, Rule rule) has been removed.net.sourceforge.pmd.rules.RuleFactory: moved into subpackagelang.rule and made package private.It has now been hidden completely from public API.lang.rule.internal.net.sourceforge.pmd.RuleSetReferencenet.sourceforge.pmd.RuleSetReferenceIdnet.sourceforge.pmd.RuleSetsnet.sourceforge.pmd.lang.rule.ParametricRuleViolation is now package private and moved tonet.sourceforge.pmd.reporting.ParametricRuleViolation.The only public API isRuleViolation.net.sourceforge.pmd.lang.rule.RuleSetapplies(Rule,LanguageVersion) is now package private.applies(TextFile) has been removed.applies(FileId) is now package private.net.sourceforge.pmd.lang.rule.RuleSetLoaderloadRuleSetsWithoutException(java.util.List) is now package private.net.sourceforge.pmd.lang.rule.RuleSetLoadExceptionnet.sourceforge.pmd.lang.ast.LexException - the constructorLexException(boolean, String, int, int, String, char) is now package private.It is only used by JavaCC-generated token managers.net.sourceforge.pmd.PMDConfigurationsetAnalysisCache(AnalysisCache) is now package private. UsesetAnalysisCacheLocation instead.getAnalysisCache() is now package private.net.sourceforge.pmd.lang.document.FileCollectornewCollector(LanguageVersionDiscoverer, PmdReporter) is now package private.newCollector(PmdReporter) is now package private.files instead.net.sourceforge.pmd.lang.rule.xpath.AttributereplacementIfDeprecated() is now package private.net.sourceforge.pmd.properties.PropertyTypeId - moved in subpackageinternal.net.sourceforge.pmd.properties.PropertyDescriptor - methodgetTypeId() is now package private.pmd-doc is now considered internal API even though it was not declared so before.It’s used to generate the rule documentation for the built-in rules.net.sourceforge.pmd.doc.internal.net.sourceforge.pmd.ant.FormattergetRenderer() has been removed.start(String) is private now.end(Report) has been removed.isNoOutputSupplied() is now package private.newListener(Project) is now package private.net.sourceforge.pmd.ant.PMDTaskgetRelativizeRoots() has been removed.net.sourceforge.pmd.ant.ReportException is now package private. Note: It was not marked with @InternalApi before.net.sourceforge.pmd.lang.apex.ast.ApexNodegetNode() has been removed. It was only deprecated before and not marked with @InternalApi.However, it gave access to the wrapped Jorje node and was thus internal API.net.sourceforge.pmd.lang.apex.ast.AbstractApexNodegetNode() is now package private.net.sourceforge.pmd.lang.apex.multifile.ApexMultifileAnalysisnet.sourceforge.pmd.lang.apex.rule.design.AbstractNcssCountRule (now package private)net.sourceforge.pmd.lang.apex.rule.AbstractApexUnitTestRule (moved to packagenet.sourceforge.pmd.apex.rule.bestpractices, now package private)net.sourceforge.pmd.lang.java.rule.AbstractIgnoredAnnotationRule (moved to internal)net.sourceforge.pmd.lang.java.types.ast.LazyTypeResolver (moved to internal)net.sourceforge.pmd.lang.java.types.JMethodSiginternalApi() has been removed.net.sourceforge.pmd.lang.java.types.TypeOpsisSameTypeInInference(JTypeMirror,JTypeMirror) is now package private.net.sourceforge.pmd.lang.jsp.ast.JspParsergetTokenBehavior() has been removed.net.sourceforge.pmd.lang.modelica.ast.InternalApiBridge renamed fromInternalModelicaNodeApi.net.sourceforge.pmd.lang.modelica.resolver.InternalApiBridge renamed fromInternalModelicaResolverApi.net.sourceforge.pmd.lang.modelica.resolver.ModelicaSymbolFacade has been removed.net.sourceforge.pmd.lang.modelica.resolver.ResolutionContext (moved to internal)net.sourceforge.pmd.lang.modelica.resolver.ResolutionState (moved to internal). Note: it was not previously marked with @InternalApi.net.sourceforge.pmd.lang.modelica.resolver.Watchdog (moved to internal). Note: it was not previously marked with @InternalApi.net.sourceforge.pmd.lang.plsql.rule.design.AbstractNcssCountRule is now package private.net.sourceforge.pmd.lang.scala.ScalaLanguageModuledialectOf(LanguageVersion) has been removed.Removed classes and members (previously deprecated)
The annotation@DeprecatedUntil700 has been removed.
CpdLanguageProperties. The fieldDEFAULT_SKIP_BLOCKS_PATTERN has been removed.BaseAntlrNode - methodjoinTokenText() has been removed.Node - many methods have been removed:getNthParent(int) - Useancestors instead, e.g.node.ancestors().get(n-1)getFirstParentOfType(Class) - Useancestors instead, e.g.node.ancestors(parentType).first()getParentsOfType(Class) - Useancestors instead, e.g.node.ancestors(parentType).toList()findChildrenOfType(Class) - Usechildren instead, e.g.node.children(childType).toList()findDescendantsOfType(Class) - Usedescendants instead, e.g.node.descendants(targetType).toList()findDescendantsOfType(Class,boolean) - Usedescendants instead, e.g.node.descendants(targetType).crossFindBoundaries(b).toList()getFirstChildOfType(Class) - UsefirstChild insteadgetFirstDescendantOfType(Class) - Usedescendants instead, e.g.node.descendants(targetType).first()hasDescendantOfType(Class) - Usedescendants instead, e.g.node.descendants(targetType).nonEmpty()findChildNodesWithXPath(String) - Use theNodeStream API instead.GenericNode - methodgetNthParent(int) has been removed. Useancestors instead, e.g.node.ancestors().get(n-1)FileCollector - methodaddZipFile(java.nio.file.Path) has been removed. UseaddZipFileWithContent insteadTextDocument - methodreadOnlyString(CharSequence,String,LanguageVersion) has been removed.UsereadOnlyString instead.TextFile - methoddataSourceCompat(DataSource,PMDConfiguration) has been removed.UseTextFile directly, e.g.forPathXPathVersionXPATH_1_0XPATH_1_0_COMPATIBILITYXPATH_2_0XPATH_3_1.net.sourceforge.pmd.lang.rule.AbstractDelegateRule removed. It has been merged withRuleReference.AbstractRule - the following methods have been removed:deepCopyValuesTo(AbstractRule) - usedeepCopy instead.addRuleChainVisit(Class) - overridebuildTargetSelector in order to register nodes for rule chain visits.addViolation(...) - useaddViolation instead, e.g. viaasCtx(data).addViolation(...).Note: These methods were only marked as deprecated in javadoc.addViolationWithMessage(...) - useaddViolationWithMessage instead, e.g. viaasCtx(data).addViolationWithMessage(...). Note: These methods were only marked as deprecated in javadoc.RuleReference - the following methods have been removed:setRuleSetReference(RuleSetReference) - without replacement. Just construct newRuleReference instead.hasOverriddenProperty(PropertyDescriptor) - useisPropertyOverridden instead.XPathRuleXPATH_DESCRIPTOR has been made private and is not accessible anymore.Language - methodgetTerseName() removed. UsegetId instead.LanguageModuleBase - methodgetTerseName() removed. UsegetId instead.LanguageRegistry - the following methods have been removed:getLanguage(String) - usegetLanguageByFullNameviaPMD orCPD instead.findLanguageByTerseName(String) - usegetLanguageByIdviaPMD orCPD instead.findByExtension(String) - removed without replacement.LanguageVersionDiscoverer - methodgetLanguagesForFile(java.io.File) removed.UsegetLanguagesForFile instead.AbstractPropertySourcepropertyDescriptors has been made private and is not accessible anymore.UsegetPropertyDescriptors instead.propertyValuesByDescriptor has been made private and is not accessible anymore.UsegetPropertiesByPropertyDescriptororgetOverriddenPropertiesByPropertyDescriptor instead.copyPropertyDescriptors() has been removed. UsegetPropertyDescriptors instead.copyPropertyValues() has been removed. UsegetPropertiesByPropertyDescriptororgetOverriddenPropertiesByPropertyDescriptor instead.Reportable - the following methods have been removed. UsegetReportLocation insteadgetBeginLine()getBeginColumn()getEndLine()getEndColumn()net.sourceforge.pmd.util.datasource.DataSource - useTextFile instead.net.sourceforge.pmd.util.datasource.FileDataSourcenet.sourceforge.pmd.util.datasource.ReaderDataSourcenet.sourceforge.pmd.util.datasource.ZipDataSourceCollectionUtilinvertedMapFrom(...) has been removed.mapFrom(...) has been removed.AbstractConfiguration - the following methods have been removed:setIgnoreFilePath(String) - usesetIgnoreFilePath instead.setInputFilePath(String) - usesetInputFilePath instead.setInputPaths(String) - usesetInputPathList oraddInputPath instead.setInputUri(String) - usesetInputUri instead.PMDConfiguration - the following methods have been removedprependClasspath(String) - useprependAuxClasspath instead.getRuleSets() - usegetRuleSetPaths instead.setRuleSets(String) - usesetRuleSets oraddRuleSet instead.setReportFile(String) - usesetReportFile instead.getReportFile() - usegetReportFilePath instead.Report - methodmerge(Report) has been removed. Useunion instead.RuleSetLoader - methodtoFactory() has been made package private and is not accessible anymore.RuleViolation - the following methods have been removed:getPackageName() - usegetAdditionalInfo withPACKAGE_NAME instead, e.g.getAdditionalInfo().get(PACKAGE_NAME).getClassName() - usegetAdditionalInfo withCLASS_NAME instead, e.g.getAdditionalInfo().get(CLASS_NAME).getMethodName() - usegetAdditionalInfo withMETHOD_NAME instead, e.g.getAdditionalInfo().get(METHOD_NAME).getVariableName() - usegetAdditionalInfo withVARIABLE_NAME instead, e.g.getAdditionalInfo().get(VARIABLE_NAME).ApexNode andASTApexFile#getApexVersion(): In PMD 6, this method has been deprecated but was defined in the classApexRootNode.The version returned is always “Version.CURRENT”, as the apex compiler integrationdoesn’t use additional information which Apex version actually is used. Therefore, this method can’t beused to determine the Apex version of the project that is being analyzed.
If the current version is needed, thenNode.getTextDocument().getLanguageVersion() can be used. Thisis the version that has been selected via CLI--use-version parameter.
ApexNodejjtAccept() has been removed.UseacceptVisitor instead.getNode() has been removed. The underlying node is only available in AST nodes, but not in rule implementations.AbstractApexNode - methodgetNode() is now package private.AST nodes still have access to the underlying Jorje node via the protected propertynode.net.sourceforge.pmd.lang.apex.ast.ApexParserVisitorUseApexVisitor orApexVisitorBase instead.net.sourceforge.pmd.lang.apex.ast.ApexParserVisitorAdapterASTAssignmentExpression - methodgetOperator() removed.UsegetOp instead.ASTBinaryExpression - methodgetOperator() removed.UsegetOp instead.ASTBooleanExpression - methodgetOperator() removed.UsegetOp instead.ASTPostfixExpression - methodgetOperator() removed.UsegetOp instead.ASTPrefixExpression - methodgetOperator() removed.UsegetOp instead.net.sourceforge.pmd.lang.apex.rule.security.Helper removed. This was actually internal API.AbstractPackageNameModuleDirective - methodgetImage() has been removed.UsegetPackageName instead.AbstractTypeDeclaration - methodgetImage() has been removed.UsegetSimpleName() instead.ASTAnnotation - methodgetAnnotationName() has been removed.ASTClassTypeASTClassType(java.lang.String) has been removed.getImage() has been removed.isReferenceToClassSameCompilationUnit() has been removed.ASTFieldDeclaration - methodgetVariableName() has been removed.ASTLiteral - the following methods have been removed:isStringLiteral() - usenode instanceof ASTStringLiteral instead.isCharLiteral() - usenode instanceof ASTCharLiteral instead.isNullLiteral() - usenode instanceof ASTNullLiteral instead.isBooleanLiteral() - usenode instanceof ASTBooleanLiteral instead.isNumericLiteral() - usenode instanceof ASTNumericLiteral instead.isIntLiteral() - useisIntLiteral instead.isLongLiteral() - useisLongLiteral instead.isFloatLiteral() - useisFloatLiteral instead.isDoubleLiteral() - useisDoubleLiteral instead.ASTMethodDeclaration - methodsgetImage() andgetMethodName() have been removed.UsegetName instead.ASTMethodReference - methodgetImage() has been removed.ASTModuleName - methodgetImage() has been removed.ASTPrimitiveType - methodgetImage() has been removed.ASTTypegetTypeImage() has been removed.getArrayDepth() has been removed. It’s only available for arrays:getArrayDepth.isPrimitiveType() - usenode instanceof ASTPrimitiveType instead.isArrayType() - usenode instanceof ASTArrayType instead.isClassOrInterfaceType() - usenode instanceof ASTClassType instead.ASTTypeDeclaration - methodgetImage() has been removed.ASTUnaryExpression - methodisPrefix() has been removed.UsegetOperator.isPrefix() instead.ASTVariableId - methodsgetImage() andgetVariableName() have been removed.UsegetName instead.JavaComment - methodgetImage() has been removed.UsegetText instead.JavaNode - methodjjtAccept() has been removed.UseacceptVisitor instead.net.sourceforge.pmd.lang.java.ast.JavaParserVisitorUseJavaVisitor orJavaVisitorBase instead.net.sourceforge.pmd.lang.java.ast.JavaParserVisitorAdapterModifierOwnerisFinal() - This is still available in various subtypes, where it makes sense, e.g.isFinal.isAbstract() - This is still available in subtypes, e.g.isAbstract.isStrictfp() - UsehasModifiers instead, e.g.hasModifiers(STRICTFP).isSynchronized() - UsehasModifiers instead, e.g.hasModifiers(SYNCHRONIZED).isNative() - UsehasModifiers instead, e.g.hasModifiers(NATIVE).isStatic() - This is still available in subtypes, e.g.isStatic.isVolatile() - UsehasModifiers instead, e.g.hasModifiers(VOLATILE).isTransient() - UsehasModifiers instead, e.g.hasModifiers(TRANSIENT).isPrivate() - UsegetVisibility instead, e.g.getVisibility() == Visibility.V_PRIVATE.isPublic() - UsegetVisibility instead, e.g.getVisibility() == Visibility.V_PUBLIC.isProtected() - UsegetVisibility instead, e.g.getVisibility() == Visibility.V_PROTECTED.isPackagePrivate() - UsegetVisibility instead, e.g.getVisibility() == Visibility.V_PACKAGE.isSyntacticallyAbstract() - UsehasExplicitModifiers instead, e.g.hasExplicitModifiers(ABSTRACT).isSyntacticallyPublic() - UsehasExplicitModifiers instead, e.g.hasExplicitModifiers(PUBLIC).isSyntacticallyStatic() - UsehasExplicitModifiers instead, e.g.hasExplicitModifiers(STATIC).isSyntacticallyFinal() - UsehasExplicitModifiers instead, e.g.hasExplicitModifiers(FINAL).TypeNode - methodgetType() has been removed. UsegetTypeMirror instead.AbstractEcmascriptNode - methodgetNode() has been removed.AST nodes still have access to the underlying Rhino node via the protected propertynode.ASTFunctionNode - methodgetBody(int) removed.UsegetBody instead.ASTTryStatementisCatch() has been removed. UsehasCatch instead.isFinally() has been removed. UsehasFinally instead.EcmascriptNodejjtAccept() has been removed. UseacceptVisitor instead.getNode() has been removed. The underlying node is only available in AST nodes, but not in rule implementations.net.sourceforge.pmd.lang.ecmascript.ast.EcmascriptParserVisitorUseEcmascriptVisitor orEcmascriptVisitorBase instead.net.sourceforge.pmd.lang.ecmascript.ast.EcmascriptParserVisitorAdapternet.sourceforge.pmd.lang.jsp.ast.JspParserVisitorUseJspVisitor orJspVisitorBase instead.net.sourceforge.pmd.lang.jsp.ast.JspParserVisitorAdapterJspNode - methodjjtAccept() has been removed.UseacceptVisitor instead.net.sourceforge.pmd.lang.modelica.ast.ModelicaParserVisitorUseModelicaVisitor orModelicaVisitorBase instead.net.sourceforge.pmd.lang.modelica.ast.ModelicaParserVisitorAdapterModelicaNode - methodjjtAccept() has been removed.UseacceptVisitor instead.net.sourceforge.pmd.lang.modelica.rule.AmbiguousResolutionRuleUseAmbiguousResolutionRule instead.net.sourceforge.pmd.lang.modelica.rule.ConnectUsingNonConnectorUseConnectUsingNonConnectorRulenet.sourceforge.pmd.lang.plsql.ast.PLSQLParserVisitorUsePlsqlVisitor orPlsqlVisitorBase instead.net.sourceforge.pmd.lang.plsql.ast.PLSQLParserVisitorAdapterPLSQLNode - methodjjtAccept() has been removed.UseacceptVisitor instead.pmd-scala has been removed. Usepmd-scala_2.13 orpmd-scala_2.12 instead.ScalaNodeaccept() has been removed. UseacceptVisitor instead.getNode() has been removed. The underlying node is only available in AST nodes, but not in rule implementations.AbstractScalaNode - methodgetNode() has been removed. AST nodes still have accessto the underlying Scala node via the protected propertynode.VfNode - methodjjtAccept() has been removed.UseacceptVisitor instead.net.sourceforge.pmd.lang.vf.ast.VfParserVisitorUseVfVisitor orVfVisitorBase instead.net.sourceforge.pmd.lang.vf.ast.VfParserVisitorAdapterDataType - methodfromBasicType(BasicType) has been removed.UsefromTypeName instead.VtlNode - methodjjtAccept() has been removed.UseacceptVisitor instead.net.sourceforge.pmd.lang.vm.ast.VmParserVisitorUseVtlVisitor orVtlVisitorBase instead.net.sourceforge.pmd.lang.vm.ast.VmParserVisitorAdapterRemoved classes, interfaces and methods (not previously deprecated)
isSynthetic() inASTMethod has been removed.With the switch from Jorje to Summit AST as underlying parser, no synthetic methods are generated by theparser anymore. This also means, that there is no XPath attribute@Synthetic anymore.STATIC_INITIALIZER_METHOD_NAME inFieldDeclarationsShouldBeAtStartRulehas been removed. It was used to filter out synthetic methods, but these are not generated anymore with thenew parser.getContext() inASTReferenceExpression has been removed.It was not used and always returnednull.getNamespace() in all AST nodes (defined inApexNode) hasbeen removed, as it was never fully implemented. It always returned an empty string.getNameSpace() inApexQualifiedName has been removed.net.sourceforge.pmd.lang.apex.ast.ASTBridgeMethodCreator has been removed. This was a node that hasbeen generated by the old Jorje parser only.net.sourceforge.pmd.util.Predicate has been removed. It was marked as Experimental before. Usejava.util.function.Predicate instead.FinalizableNode (introduced in 7.0.0-rc1) has been removed.Its methodisFinal() has been moved down to thenodes where needed, e.g.ASTLocalVariableDeclaration#isFinal.isPackagePrivate() inASTClassDeclaration (formerly ASTClassOrInterfaceDeclaration)has been removed.UsehasVisibility instead,which can correctly differentiate between local and package private classes.Renamed classes, interfaces, methods
MessageReporter has been renamed toPmdReporterTokenMgrError has been renamed toLexExceptionTokenizer has been renamed toCpdLexer. Along with this rename,all the implementations have been renamed as well (Tokenizer ->CpdLexer), e.g. “CppCpdLexer”, “JavaCpdLexer”.This affects all language modules.AnyTokenizer has been renamed toAnyCpdLexer.AccessNode has been renamed toModifierOwner. This is only relevantfor Java rules, which use that type directly e.g. through downcasting.Or when using the XPath functionpmd-java:nodeIs().ASTClassOrInterfaceType has been renamed toASTClassType. XPath rulesneed to be adjusted.ASTClassOrInterfaceDeclaration has been renamed toASTClassDeclaration.XPath rules need to be adjusted.ASTAnyTypeDeclaration has been renamed toASTTypeDeclaration.This is only relevant for Java rules, which use that type directly, e.g. through downcasting.Or when using the XPath functionpmd-java:nodeIs().ASTMethodOrConstructorDeclaration has been renamed toASTExecutableDeclaration. This is only relevant for Java rules, which use that typedirectly, e.g. through downcasting. Or when using the XPath functionpmd-java:nodeIs().ASTVariableDeclaratorId has been renamed toASTVariableId. XPath rulesneed to be adjusted.ASTClassOrInterfaceBody has been renamed toASTClassBody. XPath rulesneed to be adjusted.ScalaParserVisitor has been renamed toScalaVisitor in orderto align the naming scheme for the different language modules.ScalaParserVisitorAdapter has been renamed toScalaVisitorBase in orderto align the naming scheme for the different language modules.New API
These were annotated with@Experimental, but can now be considered stable.
CPDReport#filterMatchesAntlrToken#getKindAbstractJjtreeNodeTokenDocumentAstInfo#getSuppressionCommentsAstInfo#withSuppressMapGenericToken#getKindFileCollector#addZipFileWithContentnet.sourceforge.pmd.lang.documentLanguageVersionHandler#getLanguageMetricsProviderLanguageVersionHandler#getDesignerBindingsPlainTextLanguagePropertyConstraint#getXmlConstraintPropertyConstraint#toOptionalConstraintPropertyConstraint#fromPredicatePropertyConstraint#fromPredicateAbstractRenderer#setReportFileRenderer#setReportFileDesignerBindingsDesignerBindings.TreeIconIdRelatedNodesSelectorReport#filterViolationsReport#unionRemoved functionality
--no-ruleset-compatibility has been removed. It was only used to allow loadingsome rulesets originally written for PMD 5 also in PMD 6 without fixing the rulesets.RuleSetFactoryCompatibility has been removed without replacement.The different ways to enable/disable this filter inPMDConfiguration(Property “RuleSetFactoryCompatibilityEnabled”) andPMDTask (Property “noRuleSetCompatibility”) have been removed as well.textcolor renderer (TextColorRenderer) now renders always in color.The propertycolor has been removed. The possibility to override this with the system propertypmd.colorhas been removed as well. If you don’t want colors, usetext renderer (TextRenderer).pmd-java
Rule properties
IntProperty andStringProperty have been removed. Please usePropertyFactory to create properties.,) as a delimiter. The previous default was apipe character (|). The delimiter is not configurable anymore. If needed, the comma can be escapedwith a backslash.min andmax attributes in property definitions in the XML are now optional and can appear separatelyor be omitted.New Programmatic API for CPD
SeeDetailed Release Notes for PMD 7andPR #4397 for details.
Removed classes and methods
The following previously deprecated classes have been removed:
net.sourceforge.pmd.cpd.AbstractTokenizer ➡️ useAnyCpdLexer instead (previously known as AnyTokenizer)net.sourceforge.pmd.cpd.CPD ➡️ usePmdCli frompmd-cli module for CLI support or useCpdAnalysis for programmatic APInet.sourceforge.pmd.cpd.GridBagHelper (now package private)net.sourceforge.pmd.cpd.TokenEntry.Statenet.sourceforge.pmd.lang.document.CpdCompatnet.sourceforge.pmd.properties.BooleanMultiPropertynet.sourceforge.pmd.properties.BooleanPropertynet.sourceforge.pmd.properties.CharacterMultiPropertynet.sourceforge.pmd.properties.CharacterPropertynet.sourceforge.pmd.properties.DoubleMultiPropertynet.sourceforge.pmd.properties.DoublePropertynet.sourceforge.pmd.properties.EnumeratedMultiPropertynet.sourceforge.pmd.properties.EnumeratedPropertynet.sourceforge.pmd.properties.EnumeratedPropertyDescriptornet.sourceforge.pmd.properties.FileProperty (note: without replacement)net.sourceforge.pmd.properties.FloatMultiPropertynet.sourceforge.pmd.properties.FloatPropertynet.sourceforge.pmd.properties.IntegerMultiPropertynet.sourceforge.pmd.properties.IntegerPropertynet.sourceforge.pmd.properties.LongMultiPropertynet.sourceforge.pmd.properties.LongPropertynet.sourceforge.pmd.properties.MultiValuePropertyDescriptornet.sourceforge.pmd.properties.NumericPropertyDescriptornet.sourceforge.pmd.properties.PropertyDescriptorFieldnet.sourceforge.pmd.properties.RegexPropertynet.sourceforge.pmd.properties.SingleValuePropertyDescriptornet.sourceforge.pmd.properties.StringMultiPropertynet.sourceforge.pmd.properties.StringPropertynet.sourceforge.pmd.properties.ValueParsernet.sourceforge.pmd.properties.ValueParserConstantsnet.sourceforge.pmd.properties.builders.MultiNumericPropertyBuildernet.sourceforge.pmd.properties.builders.MultiPackagedPropertyBuildernet.sourceforge.pmd.properties.builders.MultiValuePropertyBuildernet.sourceforge.pmd.properties.builders.PropertyDescriptorBuildernet.sourceforge.pmd.properties.builders.PropertyDescriptorBuilderConversionWrappernet.sourceforge.pmd.properties.builders.PropertyDescriptorExternalBuildernet.sourceforge.pmd.properties.builders.SingleNumericPropertyBuildernet.sourceforge.pmd.properties.builders.SinglePackagedPropertyBuildernet.sourceforge.pmd.properties.builders.SingleValuePropertyBuildernet.sourceforge.pmd.properties.modules.EnumeratedPropertyModulenet.sourceforge.pmd.properties.modules.NumericPropertyModuleThe following previously deprecated methods have been removed:
net.sourceforge.pmd.properties.PropertyBuilder.GenericCollectionPropertyBuilder#delim(char)net.sourceforge.pmd.properties.PropertySource#setProperty(...)net.sourceforge.pmd.properties.internal.PropertyTypeId#factoryFor(...)net.sourceforge.pmd.properties.internal.PropertyTypeId#typeIdFor(...)net.sourceforge.pmd.properties.PropertyDescriptor: removed methods errorFor, type, isMultiValue,uiOrder, compareTo, isDefinedExternally, valueFrom, asDelimitedStringThe following methods have been removed:
CPDConfiguration#sourceCodeFor(File),#postConstruct(),#tokenizer(),#filenameFilter() removedMark#getSourceSlice(),#setLineCount(int),#getLineCount(),#setSourceCode(SourceCode) removed#getBeginColumn(),#getBeginLine(),#getEndLine(),#getEndColumn() removed➡️ usegetLocation insteadMatch#LABEL_COMPARATOR removed#setMarkSet(...),#setLabel(...),#getLabel(),#addTokenEntry(...) removed#getSourceCodeSlice() removed➡️ useCPDReport#getSourceCodeSlice insteadTokenEntry#getEOF(),#clearImages(),#getIdentifier(),#getIndex(),#setHashCode(int) removed#EOF removed ➡️ useisEof insteadParser.ParserTask#getFileDisplayName() removed ➡️ usegetFileId instead(getFileId().getAbsolutePath())The following classes have been removed:
net.sourceforge.pmd.cpd.AbstractLanguagenet.sourceforge.pmd.cpd.AnyLanguagenet.sourceforge.pmd.cpd.Languagenet.sourceforge.pmd.cpd.LanguageFactorynet.sourceforge.pmd.cpd.MatchAlgorithm (now package private)net.sourceforge.pmd.cpd.MatchCollector (now package private)net.sourceforge.pmd.cpd.SourceCode (and all inner classes likeFileCodeLoader, …)net.sourceforge.pmd.cpd.token.TokenFilterMoved packages
NumericConstraints (old package:net.sourceforge.pmd.properties.constraints.NumericConstraints)PropertyConstraint (old package:net.sourceforge.pmd.properties.constraints.PropertyConstraint)ReportException (old package:net.sourceforge.pmd.cpd, moved to modulepmd-ant)CPDReportRenderer (old package:net.sourceforge.pmd.cpd.renderer)AntlrTokenFilter (old package:net.sourceforge.pmd.cpd.token)BaseTokenFilter (old package:net.sourceforge.pmd.cpd.token.internal)JavaCCTokenFilter (old package:net.sourceforge.pmd.cpd.token)Changed types and other changes
PropertyDescriptor is now a class (was an interface)and it is not comparable anymore.AbstractConfiguration#setSourceEncodingPMDConfiguration andCPDConfigurationAbstractConfigurationCPDListener#addedFileFile parameter anymoreCPDReport#getNumberOfTokensPerFile returns aMap ofFileId,Integer instead ofStringCPDReport#filterMatches now takes ajava.util.function.Predicateas parameterCpdLexerPropertyDescriptor instead ofString,to be used as language propertiestokenizechanged parameters. Now takes aTextDocument and aTokenFactory(instead ofSourceCode andTokens).Language#createProcessor(LanguagePropertyBundle) moved toPmdCapableLanguageStringUtil#linesWithTrimIndent now takes aCharsinstead of aString.net.sourceforge.pmd.lang.<langId>.cpdCpdCapableLanguage#getInstance()ID,TERSE_NAME orNAME. UsegetInstance().getName() etc. insteadInternal APIs
net.sourceforge.pmd.properties.internal.PropertyTypeIdDeprecated API
Language#getTerseName ➡️ usegetId instead
The methodASTPattern#getParenthesisDepth has been deprecated and will be removed.It was introduced for supporting parenthesized patterns, but that was removed with Java 21. It is only used whenparsing code as java-19-preview.
Experimental APIs
ASTRecordPatternASTPatternList (Note: it was renamed fromASTComponentPatternList)ASTGuard (Note: it was renamed fromASTSwitchGuard)PMD Distribution
The asset filenames of PMD onGitHub Releases arenowpmd-dist-<version>-bin.zip,pmd-dist-<version>-src.zip andpmd-dist-<version>-doc.zip.Keep that in mind, if you have an automated download script.
The structure inside the ZIP files stay the same, e.g. we still provide inside the binary distributionZIP file the base directorypmd-bin-<version>.
CLI
--stress (or-stress) has been removed without replacement.--minimum-priority was changed with 7.0.0-rc1 to only take the following values:High, Medium High, Medium, Medium Low, Low. With 7.0.0-rc2 compatibility has been restored, so that the equivalentinteger values (1 to 5) are supported as well.pmd-core
ReplacedRuleViolation::getFilename with newRuleViolation#getFileId, that returns aFileId. This is an identifier for aTextFileand could represent a path name. This allows to have a separate display name, e.g. renderers useFileNameRenderer to either display the full path name or a relative path name(seeRenderer#setFileNameRenderer andConfigurableFileNameRenderer). Many places where we used a simple String fora path-like name before have been adapted to use the newFileId.
SeePR #4425 for details.
Removed classes and methods
The following previously deprecated classes have been removed:
net.sourceforge.pmd.PMDnet.sourceforge.pmd.cli.PMDCommandLineInterfacenet.sourceforge.pmd.cli.PMDParametersnet.sourceforge.pmd.cli.PmdParametersParseResultCLI
--minimum-priority was changed with 7.0.0-rc1 to only take the following values:High, Medium High, Medium, Medium Low, Low. With 7.0.0-rc2 compatibility has been restored, so that the equivalentinteger values (1 to 5) are supported as well.CLI
--stress (or-stress) has been removed without replacement.--minimum-priority now takes one of the following values instead of an integer:High, Medium High, Medium, Medium Low, Low.Go
Java
net.sourceforge.pmd.lang.java.ast.ASTGuardedPattern has been removed.PMD CLI
--relativize-paths-with flag (or short-z), which replaces--short-names.It serves the same purpose: Shortening the pathnames in the reports. However, with the new flag it’s possibleto explicitly define one or more pathnames that should be used as the base when creating relative paths.The old flag--short-names is deprecated.Deprecated APIs
For removal
ApexRootNode#getApexVersion() has been deprecated for removal. The version returned isalwaysVersion.CURRENT, as the apex compiler integration doesn’t use additional information which Apex versionactually is used. Therefore, this method can’t be used to determine the Apex version of the projectthat is being analyzed.CPDConfiguration#setEncoding andCPDConfiguration#getEncoding. Use the methodsgetSourceEncoding andsetSourceEncoding instead. Both are availableforCPDConfiguration which extendsAbstractConfiguration.BaseCLITest andBaseCPDCLITest have been deprecated for removal withoutreplacement. CLI tests should be done in pmd-core only (and in PMD7 in pmd-cli). Individual language modulesshouldn’t need to test the CLI integration logic again. Instead, the individual language modules should test theirfunctionality as unit tests.FileCollector#addZipFile has been deprecated. It is replacedbyFileCollector#addZipFileWithContent which directly adds thecontent of the zip file for analysis.
PMDConfiguration#setReportShortNames andPMDConfiguration#isReportShortNames have been deprecated for removal.UseAbstractConfiguration#addRelativizeRoot instead.Internal APIs
CSVWriterAbstractAntTestHelperExperimental APIs
filterMatches creates a new CPD reportwith some matches removed with a given predicate based filter.Deprecated APIs
For removal
These classes / APIs have been deprecated and will be removed with PMD 7.0.0.
ExcessiveLengthRule (Java)PMD CLI
PMD now supports a new--use-version flag, which receives a language-version pair (such asjava-8 orapex-54).This supersedes the usage of-language /-l and-version /-v, allowing for multiple versions to be set in a single run.PMD 7 will completely remove support for-language and-version in favor of this new flag.
Support for-V is being deprecated in favor of--verbose in preparation for PMD 7.In PMD 7,-v will enable verbose mode and-V will show the PMD version for consistency with most Unix/Linux tools.
Support for-min is being deprecated in favor of--minimum-priority for consistency with most Unix/Linux tools, where-min would be equivalent to-m -i -n.
CPD CLI
-d or--dir as an alias to--files, in favor of consistency with PMD.PMD 7 will remove support for--files in favor of these new flags.Linux run.sh parameters
Usingrun.sh cpdgui will now warn about it being deprecated. Userun.sh cpd-gui instead.
The old designer (run.sh designerold) is completely deprecated and will be removed in PMD 7. Switch to the new JavaFX designer:run.sh designer.
The old visual AST viewer (run.sh bgastviewer) is completely deprecated and will be removed in PMD 7. Switch to the new JavaFX designer:run.sh designer for a visual tool, or userun.sh ast-dump for a text-based alternative.
Deprecated API
PMD andPMD.StatusCode - PMD 7 will ship with a revamped CLI split from pmd-core. To programmatically launch analysis you can usePmdAnalysis.PMDConfiguration#getAllInputPaths - It is now superseded byPMDConfiguration#getInputPathListPMDConfiguration#setInputPaths - It is now superseded byPMDConfiguration#setInputPathListPMDConfiguration#addInputPath - It is now superseded byPMDConfiguration#addInputPathPMDConfiguration#getInputFilePath - It is now superseded byPMDConfiguration#getInputFilePMDConfiguration#getIgnoreFilePath - It is now superseded byPMDConfiguration#getIgnoreFilePMDConfiguration#setInputFilePath - It is now superseded byPMDConfiguration#setInputFilePathPMDConfiguration#setIgnoreFilePath - It is now superseded byPMDConfiguration#setIgnoreFilePathPMDConfiguration#getInputUri - It is now superseded byPMDConfiguration#getUriPMDConfiguration#setInputUri - It is now superseded byPMDConfiguration#setInputUriPMDConfiguration#getReportFile - It is now superseded byPMDConfiguration#getReportFilePathPMDConfiguration#setReportFile - It is now superseded byPMDConfiguration#setReportFilePMDConfiguration#isStressTest andPMDConfiguration#setStressTest - Will be removed with no replacement.PMDConfiguration#isBenchmark andPMDConfiguration#setBenchmark - Will be removed with no replacement, the CLI will still support it.CPD andCPD.StatusCode - PMD 7 will ship with a revamped CLI split from pmd-core. An alternative to programmatically launch CPD analysis will be added in due time.DataType#fromBasicTypehas been deprecated. The equivalent methodfromTypeName should be used instead.No changes.
CPD CLI
--ignore-literal-sequences argument when analyzing Lua code.Deprecated API
ASTAssignmentExpression#getOperatorASTBinaryExpression#getOperatorASTBooleanExpression#getOperatorASTPostfixExpression#getOperatorASTPrefixExpression#getOperatorAll these classes have now a newgetOp() method. Existing code should be refactored to use this method instead.It returns the new enums, likeAssignmentOperator, and avoidsthe dependency to Jorje.
CPD CLI
--debug. This option has the same behavior as in PMD. It enables more verboselogging output.Rule Test Framework
isRegressionTest oftest-code is deprecated. The newattributedisabled should be used instead for defining whether a rule test should be skipped or not.reinitializeRule anduseAuxClasspath oftest-code are deprecated and assumed true.They will not be replaced.focused oftest-code allows disabling all tests except the focused one temporarily.Deprecated API
net.sourceforge.pmd.lang.java.ast.ASTGuardedPattern has been deprecated andwill be removed. It was introduced for Java 17 and Java 18 Preview as part of pattern matching for switch,but it is no longer supported with Java 19 Preview.CPDRenderer is deprecated. For custom CPD renderersthe new interfaceCPDReportRenderer should be used.TestDescriptor is deprecated, replaced withRuleTestDescriptor.RuleTst have been deprecated as internal API.Experimental APIs
Internal API
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.
CPDConfiguration#setRendererCPDConfiguration#setCPDRendererCPDConfiguration#getRendererCPDConfiguration#getCPDRendererCPDConfiguration#getRendererFromStringCPDConfiguration#getCPDRendererFromStringCPDRendererAdapterNo changes.
Deprecated ruleset references
Ruleset references with the following formats are now deprecated and will produce a warningwhen used on the CLI or in a ruleset XML file:
<lang-name>-<ruleset-name>, egjava-basic, which resolves torulesets/java/basic.xml600, which resolves torulesets/releases/600.xmlUse the explicit forms of these references to be compatible with PMD 7.
Deprecated API
toString is now deprecated. The format of thismethod will remain the same until PMD 7. The deprecation is intended to steer usersaway from relying on this format, as it may be changed in PMD 7.getInputPaths andsetInputPaths are now deprecated.A new set of methods have been added, which use lists and do not rely on comma splitting.Internal API
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 eitherCPD#runCpd orCPD#mainshould be used.BaseCPDCLITest have been deprecated with replacements.Formatter#start,Formatter#end,Formatter#getRenderer,andFormatter#isNoOutputSupplied have been internalized.Experimental APIs
Report#filterViolations creates a new report withsome 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 packagenet.sourceforge.pmd.lang.html should be used cautiously.Deprecated API
PMD have been newly deprecated, including:PMD#EOL: useSystem#lineSeparator()PMD#SUPPRESS_MARKER: useDEFAULT_SUPPRESS_MARKERPMD#processFiles: use the new programmatic APIPMD#getApplicableFiles: is internalPMDConfiguration#prependClasspath is deprecatedin favour ofprependAuxClasspath.PMDConfiguration#setRuleSets andgetRuleSets are deprecated. Use insteadsetRuleSets,addRuleSet,andgetRuleSetPaths.BaseCLITest have been deprecated with replacements.Several members ofPMDCommandLineInterface have been explicitly deprecated.The whole class however was deprecated long ago already with 6.30.0. It is internal API and shouldnot be used.
AmbiguousResolutionRuleandConnectUsingNonConnector have been deprecated,since they didn’t comply to the usual rule class naming conventions yet.The replacements are in the subpackagebestpractices.Experimental APIs
Together with the new programmatic API the interfaceTextFile has been added asexperimental. It intendsto replaceDataSource andSourceCode in the long term.
This interface will change in PMD 7 to support read/write operationsand other things. You don’t need to use it in PMD 6, asFileCollectordecouples you from this. A file collector is available throughPmdAnalysis#files.
Deprecated API
Some API deprecations were performed in core PMD classes, to improve compatibility with PMD 7.
Report: the constructor and other construction methods like addViolation or createReportRuleContext: all constructors, getters and setters. A new setof stable methods, matching those in PMD 7, was added to replace theaddViolationoverloads ofAbstractRule. In PMD 7,RuleContext willbe the API to report violations, and it can already be used as such in PMD 6.configuration is unused and will be removed.Internal API
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, includingapply,start,end,removeDysfunctionalRulesAbstractAccumulatingRenderer#renderFileReport is internal APIand should not be overridden in own renderers.Changed API
It is now forbidden to report a violation:
null nodenull messagenull set of format arguments (prefer a zero-length array)Note that the message is set from the XML rule declaration, so this is only relevantif you instantiate rules manually.
RuleContext now requires setting the current rule before callingapply. This isdone automatically byRuleSet#apply and such. Creating and configuring aRuleContext manually is strongly advised against, as the lifecycle ofRuleContextwill change drastically in PMD 7.
No changes.
Command Line Interface
The command line options for PMD and CPD now use GNU-style long options format. E.g. instead of-rulesets thepreferred 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 surprisingcompared 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 |
Experimental APIs
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 forASTCatchBlockStatement and used by the ruleEmptyCatchBlock.This information is also available via XPath attribute@ContainsComment.No changes.
No changes.
PMD CLI
PMD 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 disabledand all files are tried to be parsed with the given language. Parsing errors are ignored and unparsable filesare skipped.
This option allows to use the xml language for files, that don’t use xml as extension.See also the examples onPMD CLI reference.
Experimental APIs
ASTClassOrInterfaceDeclaration#isSealed,ASTClassOrInterfaceDeclaration#isNonSealed,ASTClassOrInterfaceDeclaration#getPermittedSubclassesASTPermitsListInternal API
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.No changes.
Deprecated API
PMD#doPMD is deprecated.UsePMD#runPmd instead.PMD#run is deprecated.UsePMD#runPmd instead.ThreadSafeReportListener and the methods to use them inReport(addListener,getListeners,addListeners)are deprecated. This functionality will be replaced by another TBD mechanism in PMD 7.No changes.
No changes.
Experimental APIs
ASTTypeTestPattern has been renamed toASTTypePatternin order to align the naming to the JLS.ASTRecordConstructorDeclaration has been renamed toASTCompactConstructorDeclarationin order to align the naming to the JLS.ASTVariableId#isPatternBindingASTPatternASTTypePatternASTRecordDeclarationASTRecordComponentListASTRecordComponentASTRecordBodyASTCompactConstructorDeclarationInternal API
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.
AvoidUsingHardCodedIPRuleare deprecated and considered to be internal API. They will be removed with PMD 7.Deprecated API
AbstractDomXmlRuleAbstractWsdlRuleAbstractXmlRuleExperimental APIs
GenericToken#getKind has been added as experimental. Thisunifies the token interface for both JavaCC and Antlr. The already existing methodAntlrToken#getKind is therefore experimental as well. Thereturned constant depends on the actual language and might change whenever the grammarof the language is changed.Deprecated API
Around RuleSet parsing
RuleSetFactory andRulesetsFactoryUtils have been deprecated in favor ofRuleSetLoader. This is easier to configure, and more maintainable than the multiple overloads ofRulesetsFactoryUtils.RuleSet for simple cases, egforSingleRule. These replace some counterparts inRuleSetFactoryRuleSets is also deprecated, many APIs that require a RuleSets instance now are deprecated, and have a counterpart that expects aList<RuleSet>.RuleSetReferenceId,RuleSetReference,RuleSetFactoryCompatibility are deprecated. They are most likely not relevant outside of the implementation of pmd-core.Around thePMD class
Many classes around PMD’s entry point (PMD) have been deprecated as internal, including:
net.sourceforge.pmd.cli in pmd-core,net.sourceforge.pmd.processorSourceCodeProcessorPMD (the class will be made a utility class)Miscellaneous
ASTPackageDeclaration#getPackageNameImage,ASTTypeParameter#getParameterNameand the corresponding XPath attributes. In both cases they’re replaced with a new methodgetName,the attribute is@Name.ASTClassOrInterfaceBody#isAnonymousInnerClass,andASTClassOrInterfaceBody#isEnumChild,refs#905Internal API
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.ecmascript.Ecmascript3Handlernet.sourceforge.pmd.lang.ecmascript.Ecmascript3ParserEcmascriptParser#parserOptionsEcmascriptParser#getSuppressMapnet.sourceforge.pmd.lang.rule.ParametricRuleViolationParserOptions#suppressMarkernet.sourceforge.pmd.lang.modelica.rule.ModelicaRuleViolationFactoryNo changes.
Deprecated API
For removal
net.sourceforge.pmd.RuleViolationComparator. UseRuleViolation#DEFAULT_COMPARATOR instead.net.sourceforge.pmd.cpd.AbstractTokenizer. Usenet.sourceforge.pmd.cpd.AnyCpdLexer instead (previously called AnyTokenizer).net.sourceforge.pmd.cpd.FortranTokenizer. Was replaced by anAnyCpdLexer. UseFortranLanguageModule#createCpdLexer anyway.net.sourceforge.pmd.cpd.PerlTokenizer. Was replaced by anAnyCpdLexer. UsePerlLanguageModule#createCpdLexer anyway.net.sourceforge.pmd.cpd.RubyTokenizer. Was replaced by anAnyCpdLexer. UseRubyLanguageModule#createCpdLexer anyway.RuleReference#getOverriddenLanguage andRuleReference#setLanguagenet.sourceforge.pmd.lang.cs.antlr4.CSharpLexer will be moved to packagenet.sourceforge.pmd.lang.cs.ast with PMD 7.net.sourceforge.pmd.lang.dart.antlr4.Dart2Lexer will be renamed toDartLexer and moved to packagenet.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 packagenet.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 toKotlinLexer and moved to packagenet.sourceforge.pmd.lang.kotlin.ast with PMD 7.net.sourceforge.pmd.lang.lua.antlr4.LuaLexer will be moved to packagenet.sourceforge.pmd.lang.lua.ast with PMD 7. All other classes in the old package will be removed.language attribute will be required on allruleelements that declare a new rule. Some base rule classes set the language implicitly in theirconstructor, and so this is not required in all cases for the rule to work. But thisbehavior will be discontinued in PMD 7, so missinglanguage attributes are nowreported as a forward compatibility warning.Deprecated API
For removal
Rule#getParserOptionsParser#getParserOptionsAbstractParserRuleContext#removeAttributeRuleContext#getAttributeRuleContext#setAttributeApexParserOptionsASTThrowStatement#getFirstClassOrInterfaceTypeImageEcmascriptParserOptionsEcmascriptXPathRuleXmlParserOptionsXmlXPathRuleProperties ofAbstractXmlRule
net.sourceforge.pmd.Report.ReadableDurationMany methods ofnet.sourceforge.pmd.Report. They are replaced by accessorsthat produce a List. For example,iterator()(and implementing Iterable) andisEmpty() are bothreplaced bygetViolations().
ASTJspDeclarationsASTJspDocumentScalaParserVisitorAdapter#zeroScalaParserVisitorAdapter#combineApexParserVisitorReducedAdapterTypeHelper is deprecated infavor ofTypeTestUtil, which has thesame functionality, but a slightly changed API.net.sourceforge.pmd.lang.java.symboltableare deprecated as internal API.Deprecated API
For removal
RuleChainVisitor and all implementations in language modulesAbstractRuleChainVisitorLanguage#getRuleChainVisitorClassBaseLanguageModule#<init>ImportWrapperThe maven modulenet.sourceforge.pmd:pmd-scala is deprecated. Usenet.sourceforge.pmd:pmd-scala_2.13ornet.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 changesin PMD 7.0.0 and onwards.
Deprecated APIs
Internal API
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)ApexParserApexHandlerRuleChainRuleSetsRulesetsFactoryUtils#getRuleSetsFor removal
TokenEntry#TokenEntryAbstractTokenizerTest. Use CpdTextComparisonTest in module pmd-lang-test instead.For details seeTesting your implementationin the developer documentation.ASTAnnotation#suppresses (Apex)ApexXPathRule (Apex)SymbolTableTestRule (Java)InefficientStringBufferingRule#isInStringBufferOperationDeprecated APIs
BaseLanguageModule#addVersion(String, LanguageVersionHandler, boolean)TokenMgrError, in particular, a new constructor is availablethat should be preferred to the old onesANTLRSyntaxErrorExperimental APIs
Note: Experimental APIs are identified with the annotationExperimental,see its javadoc for details
BaseLanguageModule have been replaced by adefinitive API.Deprecated APIs
Internal API
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.
In ASTs
As part of the changes we’d like to do to AST classes for 7.0.0, we would like tohide some methods and constructors that rule writers should not have access to.The following usages are now deprecated in theApex,Javascript,PL/SQL,Scala andVisualforce 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.VfNode orNode, or the other published interfaces in this package,to refer to nodes generically.Parser (egVfParser) are deprecated and should not be used directly.UseLanguageVersionHandler#getParser instead.TokenManager (egVfTokenManager) 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.
net.sourceforge.pmd.lang.apex.astnet.sourceforge.pmd.lang.ecmascript.astnet.sourceforge.pmd.lang.plsql.astnet.sourceforge.pmd.lang.scala.astnet.sourceforge.pmd.lang.vf.astThese deprecations have already been rolled out in a previous version for thefollowing languages:
net.sourceforge.pmd.lang.java.astnet.sourceforge.pmd.lang.jsp.astnet.sourceforge.pmd.lang.vm.astOutside of these packages, these changes also concern the following TokenManagerimplementations, and their corresponding Parser if it exists (in the same package):
CppTokenManagerJavaTokenManagerEcmascript5TokenManagerJspTokenManagerMatlabTokenManagerModelicaTokenManagerObjectiveCTokenManagerPLSQLTokenManagerPythonTokenManagerVfTokenManagerVmTokenManagerIn theJava AST the following attributes are deprecated and will issue a warning when used in XPath rules:
ASTAdditiveExpression#getImage - usegetOperator() insteadASTVariableDeclaratorId#getImage - usegetName() insteadASTVariableDeclaratorId#getVariableName - usegetName() insteadFor removal
Parser#getTokenManagerTokenManager#setFileNameAbstractTokenManager#setFileNameAbstractTokenManager#getFileNameAntlrToken#getType - usegetKind() instead.ImmutableLanguageMockRuleNode#getFirstParentOfAnyTypeNode#getAsDocumentAbstractNode#hasDescendantOfAnyTypeASTRecordDeclaration#getComponentListXPathRule. See javadoc for details.Deprecated APIs
Internal API
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.
JavaLanguageHandlerJavaLanguageParserJavaDataFlowHandlerRuleViolationFactory in eachlanguage module, egJavaRuleViolationFactory.See javadoc ofRuleViolationFactory.Implementations ofRuleViolation in each language module,egJavaRuleViolation. See javadoc ofRuleViolation.
RuleFactoryRuleBuilderRuleSetFactory, use factory methods fromRulesetsFactoryUtils insteadAbstractApexNodeAbstractApexNodeBase, and the relatedvisitmethods onApexParserVisitor and its implementations.UseApexNode instead, now considers comments too.For removal
DFAGraphRule and its implementationsDFAGraphMethodNode interfaceandAbstractNode 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 andprobably not used directly outside of PMD. UseMetricsUtil asa replacement for the language-specific façades too.QualifiableNode,QualifiedNameAbstractJavaParserAbstractJavaHandlerASTAnyTypeDeclaration.TypeKindASTAnyTypeDeclaration#getTypeKindJavaQualifiedNameASTCatchStatement#getBlockASTCompilationUnit#declarationsAreInDefaultPackageJavaQualifiableNodenet.sourceforge.pmd.lang.java.qname and its contentsMethodLikeNodeASTMethodOrConstructorDeclaration,ASTLambdaExpression.ASTAnyTypeDeclaration#getImage will be removed. Please usegetSimpleName()instead. This affectsASTAnnotationTypeDeclaration#getImage,ASTClassOrInterfaceDeclaration#getImage, andASTEnumDeclaration#getImage.ASTTryStatement, replacements with other nameshave been added. This includes the XPath attribute@Finally, replace it with a test forchild::FinallyStatement.getGuardExpressionNode are replaced withgetCondition. This affects thefollowing nodes: WhileStatement, DoStatement, ForStatement, IfStatement, AssertStatement, ConditionalExpression.ASTYieldStatement will not implementTypeNodeanymore come 7.0.0. Test the type of the expression nested within it.JavaMetrics,JavaMetricsComputerASTArguments#getArgumentCount.Usesize instead.ASTFormalParameters#getParameterCount.Usesize instead.In ASTs (JSP)
As part of the changes we’d like to do to AST classes for 7.0.0, we would like tohide some methods and constructors that rule writers should not have access to.The following usages are now deprecatedin 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.JspNode orNode, or the other published interfaces in this package,to refer to nodes generically.JspParser is deprecated and should not be used directly.UseLanguageVersionHandler#getParser instead.Please look atnet.sourceforge.pmd.lang.jsp.ast to find out the full list of deprecations.
In ASTs (Velocity)
As part of the changes we’d like to do to AST classes for 7.0.0, we would like tohide some methods and constructors that rule writers should not have access to.The following usages are now deprecatedin 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.VtlNode orNode, or the other published interfaces in this package,to refer to nodes generically.net.sourceforge.pmd.lang.vm.directive as well as the classesDirectiveMapper andLogUtil are deprecatedfor removal. They were only used internally during parsing.VmParser is deprecated and should not be used directly.UseLanguageVersionHandler#getParser instead.Please look atnet.sourceforge.pmd.lang.vm.ast to find out the full list of deprecations.
PLSQL AST
The production and nodeASTCursorBody was unnecessary, not used and has been removed. Cursors have been alreadyparsed asASTCursorSpecification.
Deprecated APIs
Internal API
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.
JavaLanguageHandlerJavaLanguageParserJavaDataFlowHandlerRuleViolationFactory in eachlanguage module, egJavaRuleViolationFactory.See javadoc ofRuleViolationFactory.Implementations ofRuleViolation in each language module,egJavaRuleViolation. See javadoc ofRuleViolation.
RuleFactoryRuleBuilderRuleSetFactory, use factory methods fromRulesetsFactoryUtils insteadAbstractApexNodeAbstractApexNodeBase, and the relatedvisitmethods onApexParserVisitor and its implementations.UseApexNode instead, now considers comments too.
CharStream,JavaCharStream,SimpleCharStream: these are APIs used by our JavaCCimplementations and that will be moved/refactored for PMD 7.0.0. They should notbe used, extended or implemented directly.JJTJavaParserState.This includes token classes, which will be replaced with a single implementation, andsubclasses ofParseException, whose usages will be replacedby just that superclass.For removal
Node interfaceandAbstractNode base class. See their javadoc for details.Node#isFindBoundary is deprecated for XPath queries.AbstractJavaParserAbstractJavaHandlerASTAnyTypeDeclaration.TypeKindASTAnyTypeDeclaration#getTypeKindJavaQualifiedNameASTCatchStatement#getBlockASTCompilationUnit#declarationsAreInDefaultPackageJavaQualifiableNodenet.sourceforge.pmd.lang.java.qname and its contentsMethodLikeNodeASTMethodOrConstructorDeclaration,ASTLambdaExpression.ASTAnyTypeDeclaration#getImage will be removed. Please usegetSimpleName()instead. This affectsASTAnnotationTypeDeclaration#getImage,ASTClassOrInterfaceDeclaration#getImage, andASTEnumDeclaration#getImage.ASTTryStatement, replacements with other nameshave been added. This includes the XPath attribute@Finally, replace it with a test forchild::FinallyStatement.getGuardExpressionNode are replaced withgetCondition. This affects thefollowing nodes: WhileStatement, DoStatement, ForStatement, IfStatement, AssertStatement, ConditionalExpression.ASTYieldStatement will not implementTypeNodeanymore come 7.0.0. Test the type of the expression nested within it.No changes.
Deprecated APIs
For removal
net.sourceforge.pmd.dcd and its subpackages. SeeDCD.LanguageRegistry:RuleSet#getExcludePatterns. Use the new methodgetFileExclusions instead.RuleSet#getIncludePatterns. Use the new methodgetFileInclusions instead.Parser#canParseParser#getSuppressMapRuleBuilder#RuleBuilder. Use the new constructor with the correct ResourceLoader instead.RuleFactory#RuleFactory. Use the new constructor with the correct ResourceLoader instead.CanSuppressWarnings and its implementationsisSupressedInternal APIs
net.sourceforge.pmd.util and its subpackages,exceptnet.sourceforge.pmd.util.datasource andnet.sourceforge.pmd.util.database.GridBagHelperColumnDescriptorChanges to Renderer
Each renderer has now a new methodRenderer#setUseShortNames whichis used for implementing the “shortnames” CLI option. The method is automatically called by PMD, if thisCLI option is in use. When rendering filenames to the report, the new helper methodAbstractRenderer#determineFileName should be used. This will changethe 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 theCLI option “shortnames”.
Deprecated APIs
For removal
ASTImportDeclaration#getImportedNameNode andASTImportDeclaration#getPackage have been deprecated andwill be removed with PMD 7.0.0.RuleContext#setSourceCodeFilename has been deprecatedand will be removed. The already existing methodRuleContext#setSourceCodeFileshould be used instead. The methodRuleContext#getSourceCodeFilename stillexists and returns just the filename without the full path.AbstractPMDProcessor#filenameFrom has beendeprecated. It was used to determine a “short name” of the file being analyzed, so that the reportcan use short names. However, this logic has been moved to the renderers.Report#metrics andReport#hasMetrics havebeen deprecated. They were leftovers from a previous deprecation round targetingStatisticalRule.Internal APIs
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, includingsubpackages, exceptTypeHelper andJavaTypeDefinition.ASTCompilationUnit#getClassTypeResolverNo changes.
Deprecated APIs
Reminder: Please don’t use members marked with the annotation
InternalApi, as they willlikely be removed, hidden, or otherwise intentionally broken with 7.0.0.
In ASTs
As part of the changes we’d like to do to AST classes for 7.0.0, we would like tohide some methods and constructors that rule writers should not have access to.The following usages are now deprecatedin the Java AST (with other languages to come):
InternalApi. Nodes should only be obtained from the parser, which for rules, meansthat never need to instantiate node themselves. Those constructors will be made package private with 7.0.0.Please look atnet.sourceforge.pmd.lang.java.ast to find out the full listof deprecations.
Deprecated APIs
For removal
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.DumpFacadenet.sourceforge.pmd.lang.java.ast.DumpFacadenet.sourceforge.pmd.lang.ecmascript.ast.DumpFacadenet.sourceforge.pmd.lang.jsp.ast.DumpFacadenet.sourceforge.pmd.lang.plsql.ast.DumpFacadenet.sourceforge.pmd.lang.vf.ast.DumpFacadenet.sourceforge.pmd.lang.vm.ast.AbstractVmNode#dumpnet.sourceforge.pmd.lang.xml.ast.DumpFacadeLanguageVersionHandler#getDumpFacade will beremoved as well. It is deprecated, along with all its implementations in the subclasses ofLanguageVersionHandler.No changes.
Command Line Interface
The start scriptsrun.sh,pmd.bat andcpd.bat support the new environment variablePMD_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 asOPTS orHEAPSIZE are deprecated and will be removed with PMD 7.0.0.
Deprecated API
CodeClimateRule is deprecated in 7.0.0 because it was unused for 2 years andcreated an unwanted dependency.Properties “cc_categories”, “cc_remediation_points_multiplier”, “cc_block_highlighting” will also be removed.See#1702 for more.
The Apex rulesetrulesets/apex/ruleset.xml has been deprecated and will be removed in 7.0.0. Please use the newquickstart rulesetrulesets/apex/quickstart.xml instead.
No changes.
StatisticalRule and the related helper classes and base rule classesare deprecated for removal in 7.0.0. This includes all ofnet.sourceforge.pmd.stat andnet.sourceforge.pmd.lang.rule.stat,and alsoAbstractStatisticalJavaRule,AbstractStatisticalApexRule and the like.The methodsReport#addMetric andmetricAddedwill also be removed.setProperty is deprecated,becauseMultiValuePropertyDescriptor is deprecated as well.Properties framework
The properties framework is about to get a lifting, and for that reason, we need to deprecate a lot of APIsto remove them in 7.0.0. The proposed changes to the API are describedon the wiki
Changes to how you define properties
Construction of property descriptors has been possible through builders since 6.0.0. The 7.0.0 API will only allowconstruction through builders. The builder hierarchy, currently found in the packagenet.sourceforge.pmd.properties.builders,is being replaced by the simplerPropertyBuilder. Their APIs enjoy a high degree of source compatibility.
Concrete property classes likeIntegerProperty andStringMultiProperty will graduallyall be deprecated until 7.0.0. Their usages should be replaced by direct usage of thePropertyDescriptorinterface, e.g.PropertyDescriptor<Integer> orPropertyDescriptor<List<String>>.
Instead of spreading properties across countless classes, the utility classPropertyFactory will becomefrom 7.0.0 on the only provider for property descriptor builders. Each current property type will be replacedby a corresponding method onPropertyFactory:
IntegerProperty is replaced byPropertyFactory#intPropertyIntegerMultiProperty is replaced byPropertyFactory#intListPropertyFloatProperty andDoubleProperty are both replaced byPropertyFactory#doubleProperty.Having a separate property for floats wasn’t that useful.FloatMultiProperty andDoubleMultiProperty are replaced byPropertyFactory#doubleListProperty.StringProperty is replaced byPropertyFactory#stringPropertyStringMultiProperty is replaced byPropertyFactory#stringListPropertyRegexProperty is replaced byPropertyFactory#regexProperty
EnumeratedProperty is replaced byPropertyFactory#enumPropertyEnumeratedProperty is replaced byPropertyFactory#enumListPropertyBooleanProperty is replaced byPropertyFactory#booleanPropertyBooleanMultiProperty, is not replaced, because it doesn’t have a use case.CharacterProperty is replaced byPropertyFactory#charPropertyCharacterMultiProperty is replaced byPropertyFactory#charListPropertyLongProperty is replaced byPropertyFactory#longIntPropertyLongMultiProperty is replaced byPropertyFactory#longIntListPropertyMethodProperty,FileProperty,TypeProperty and their multi-valued counterpartsare 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:IntegerPropertymyProperty=newIntegerProperty("score","Top score value",1,100,40,3.0f);IntegerPropertymyProperty=IntegerProperty.named("score").desc("Top score value").range(1,100).defaultValue(40).uiOrder(3.0f);// They both map to the following in 7.0.0PropertyDescriptor<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.
Architectural simplifications
EnumeratedPropertyDescriptor,NumericPropertyDescriptor,PackagedPropertyDescriptor,and the related builders (innet.sourceforge.pmd.properties.builders) will be removed.These specialized interfaces allowed additional constraints to be enforced on thevalue of a property, but made the property class hierarchy very large and impracticalto maintain. Their functionality will be mapped uniformly toPropertyConstraints,which will allow virtually any constraint to be defined, and improve documentation and error reporting. Therelated methodsPropertyTypeId#isPropertyNumeric andPropertyTypeId#isPropertyPackaged are also deprecated.
MultiValuePropertyDescriptor andSingleValuePropertyDescriptorare deprecated. 7.0.0 will introduce a new XML syntax which will remove the need for such a dividebetween single- and multi-valued properties. The methodPropertyDescriptor#isMultiValue will be removedaccordingly.
Changes to the PropertyDescriptor interface
preferredRowCount is deprecated with no intended replacement. It was never implemented, and does not belongin this interface. The methodsuiOrder andcompareTo(PropertyDescriptor) are deprecated for thesame reason. These methods mix presentation logic with business logic and are not necessary for PropertyDescriptors to work.PropertyDescriptor will not extendComparable<PropertyDescriptor> anymore come 7.0.0.propertyErrorFor is deprecated and will be removed with no intendedreplacement. It’s really just a shortcut forprop.errorFor(rule.getProperty(prop)).TvalueFrom(String) andStringasDelimitedString(T) are deprecated and will be removed. These wereused to serialize and deserialize properties to/from a string, but 7.0.0 will introduce a more flexibleXML syntax which will make them obsolete.isMultiValue andtype are deprecated and won’t be replaced. The new XML syntax will remove the needfor 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 anew way to document these properties exhaustively will be added with 7.0.0.errorFor is deprecated as its return type will be changed toOptional<String> with the shift to Java 8.Deprecated APIs
For internalization
The implementation of the adapters for the XPath engines Saxon and Jaxen (packagenet.sourceforge.pmd.lang.ast.xpath)are now deprecated. They’ll be moved to an internal package come 7.0.0. OnlyAttribute remains public API.
The classesPropertyDescriptorField,PropertyDescriptorBuilderConversionWrapper, and the methodsPropertyDescriptor#attributeValuesById,PropertyDescriptor#isDefinedExternally andPropertyTypeId#getFactory.These were used to read and write properties to and from XML, but were not intended as public API.
The classValueParserConstants and the interfaceValueParser.
All classes fromnet.sourceforge.pmd.lang.java.metrics.impl.visitors are now considered internal API. They’re deprecatedand 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()
For removal
All classes fromnet.sourceforge.pmd.properties.modules will be removed.
The interfaceDimensionable 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 fromASTLocalVariableDeclaration andASTFieldDeclaration havealso been deprecated:
ASTFieldDeclaration won’t be aTypeNode come 7.0.0, sogetType andgetTypeDefinition are deprecated.
The methodgetVariableName on those two nodes will be removed, too.
All these are deprecated because those nodes may declare several variables at once, possiblywith different types (and obviously with different names). They both implementIterator<ASTVariableId>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 writecomposable visitors, used in the metrics framework, but they didn’t prove cost-effective.
Innet.sourceforge.pmd.lang.java.ast:JavaParserDecoratedVisitor,JavaParserControllessVisitor,JavaParserControllessVisitorAdapter, andJavaParserVisitorDecorator are deprecated with no intended replacement.
The LanguageModules of several languages, that only support CPD execution, have been deprecated. These languagesare not fully supported by PMD, so having a language module does not make sense. The functionality of CPD isnot affected by this change. The following classes have been deprecated and will be removed with PMD 7.0.0:
CppHandlerCppLanguageModuleCppParserCsLanguageModuleFortranLanguageModuleGroovyLanguageModuleMatlabHandlerMatlabLanguageModuleMatlabParserObjectiveCHandlerObjectiveCLanguageModuleObjectiveCParserPhpLanguageModulePythonHandlerPythonLanguageModulePythonParserRule:isDfa(),isTypeResolution(),isMultifile() and theirrespective setters.RuleSet:usesDFA(Language),usesTypeResolution(Language),usesMultifile(Language)RuleSets:usesDFA(Language),usesTypeResolution(Language),usesMultifile(Language)LanguageVersionHandler:getDataFlowFacade(),getSymbolFacade(),getSymbolFacade(ClassLoader),getTypeResolutionFacade(ClassLoader),getQualifiedNameResolutionFacade(ClassLoader)No changes.
A couple of methods and fields innet.sourceforge.pmd.properties.AbstractPropertySource have beendeprecated, as they are replaced by already existing functionality or expose internal implementationdetails:propertyDescriptors,propertyValuesByDescriptor,copyPropertyDescriptors(),copyPropertyValues(),ignoredProperties(),usesDefaultValues(),useDefaultValueFor().
Some methods innet.sourceforge.pmd.properties.PropertySource have been deprecated as well:usesDefaultValues(),useDefaultValueFor(),ignoredProperties().
The classnet.sourceforge.pmd.lang.rule.AbstractDelegateRule has been deprecated and willbe removed with PMD 7.0.0. It is internally only in use by RuleReference.
The default constructor ofnet.sourceforge.pmd.lang.rule.RuleReference has been deprecatedand will be removed with PMD 7.0.0. RuleReferences should only be created by providing a Rule anda RuleSetReference. Furthermore, the following methods are deprecated:setRuleReference(),hasOverriddenProperty(),usesDefaultValues(),useDefaultValueFor().
All classes in the packagenet.sourceforge.pmd.lang.dfa.report have been deprecated and will be removedwith PMD 7.0.0. This includes the classnet.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 forYAHTMLRenderer, 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 andmake ShiftExpression inconsistent. The operator of a ShiftExpression is now accessible throughShiftExpression#getOperator.
The utility classCommentUtil has been deprecated and will be removedwith PMD 7.0.0. Its methods have been intended to parse javadoc tags. A more useful solution will be addedaround the AST nodeFormalComment, which contains as childrenJavadocElement nodes, which inturn provide access to theJavadocTag.
All comment AST nodes (FormalComment,MultiLineComment,SingleLineComment) have a new methodgetFilteredComment() which provide access to the comment text without the leading/* markers.
The methodAbstractCommentRule.tagsIndicesIn() has been deprecated and will be removed withPMD 7.0.0. It is not very useful, since it doesn’t extract the informationin a useful way. You would still need check, which tags have been found, and with whichdata they might be accompanied.
net.sourceforge.pmd.benchmark have been deprecated:Benchmark,Benchmarker,BenchmarkReport,BenchmarkResult,RuleDuration,StringBuilderCR andTextReport. Their API is not supported anymoreand is disconnected from the internals of PMD. Use the newer API based aroundTimeTracker instead, which can be foundin the same package.TypeOfFunction has been deprecated. Use the newerTypeIsFunction in the same package.typeof methods inJavaFunctions have been deprecated.Use the newertypeIs method in the same class instead.isA,isEither andisNeither ofTypeHelper.Use the newisExactlyAny andisExactlyNone methods in the same class instead.The static methodPMDParameters#transformParametersIntoConfiguration is now deprecated,for removal in 7.0.0. The new instance methodtoConfiguration replaces it.
The methodASTConstructorDeclaration#getParameters has been deprecated in favor of the new methodgetFormalParameters. This method is available for bothASTConstructorDeclaration andASTMethodDeclaration.
getXPathNodeName is added to theNode interface, which removes theuse oftoString of a node to get its XPath element name (see#569).AbstractNode, will be removed with 7.0.0Node.toString method will not necessarily provide its XPath nodename anymore.The interfacenet.sourceforge.pmd.cpd.Renderer has been deprecated. A new interfaceCPDRenderer has been introduced to replace it. The maindifference is that the new interface is meant to render directly to ajava.io.Writerrather than to a String. This allows to greatly reduce the memory footprint of CPD, as onlarge projects, with many duplications, it was causingOutOfMemoryErrors (see#795).
net.sourceforge.pmd.cpd.FileReporter has also been deprecated as part of this change, as it’s no longer needed.
PMD#VERSION has been deprecated and will be removed with PMD 7.0.0.Please usePMDVersion#VERSION instead.isFindBoundary should not be an attributen.s.pmd.reporting packagen.s.pmd.lang.rule packagecolor and system propertypmd.color inTextColorRenderer--no-ruleset-compatibilityClasspathClassLoader::getResource child first--file-list is specified--ignore-literals and--ignore-identifiers workLanguage specific fixes:
@SuppressWarnings with constants instead of literalsisOverridden in ASTMethodDeclarationfoo.bar().size()Throwable.addSuppressed(...)new BigDecimal(Expression)this.run()foo.bar.run()foo.notify(bar)--file-list is specified -Wener (@wener-tiobe)