GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||
GeezerVison is showing docs.pmd-code.org — Introduction to writing PMD rules | PMD Source Code Analyzer
Release date: 28-December-2026
Introduction to writing PMD rulesWriting your own PMD rules
Table of ContentsPMD is a framework to perform code analysis. You can create your own rules to check for patterns specific to your codebase, or the coding practices of your team. How rules work: the ASTBefore running rules, PMD parses the source file into a data structure called an abstract syntax tree (AST). This tree represents the syntactic structure of the code, and encodes syntactic relations between source code elements. For instance, in Java, method declarations belong to a class: in the AST, the nodes representing method declarations will be descendants of a node representing the declaration of their enclosing class. This representation is thus much richer than the original source code (which, for a program, is just a chain of characters), or the token chain produced by a lexer. For example:
Conceptually, PMD rules work by matching a “pattern” against the AST of a file. Rules explore the AST and find nodes that satisfy some conditions that are characteristic of the specific thing the rule is trying to flag. Rules then report a violation on these nodes. Discovering the ASTASTs are represented by Java classes deriving from The structure of the AST can be discovered through
Writing new rulesPMD supports two ways to define rules: using an XPath query, or using a Java visitor. XPath rules are much easier to set up, since they’re defined directly in your ruleset XML, and are expressive enough for nearly any task. On the other hand, some parts of PMD’s API are only accessible from Java, e.g. accessing the usages of a declaration. And Java rules allow you to do some complicated processing, to which an XPath rule couldn’t scale. In the end, choosing one strategy or the other depends on the difficulty of what your rule does. I’d advise to keep to XPath unless you have no other choice. Note: Despite that fact, the Java rules are written in Java, any language that PMD supports can be analyzed. E.g. you can write a Java rule to analyze Apex source code. XML rule definitionNew rules must be declared in a ruleset before they’re referenced. This is the
case for both XPath and Java rules. To do this, the
Example for Java rule: Example for XPath rule: Note Since PMD 7, the Resource indexTo learn how to write a rule:
To go further:
| ||||
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |