PMD Core - The foundational library module providing essential infrastructure for PMD static code analysis including AST handling, rule execution, configuration management, and reporting mechanisms.
npx @tessl/cli install tessl/maven-net-sourceforge-pmd--pmd-core@7.13.00
# PMD Core
1
2
PMD Core is the foundational library module of PMD, providing essential infrastructure for static code analysis across multiple programming languages. It offers a comprehensive framework for parsing source code into Abstract Syntax Trees (ASTs), executing configurable rules, managing language modules, collecting violations, and rendering reports in various formats.
3
4
## Package Information
5
6
- **Package Name**: pmd-core
7
- **Group ID**: net.sourceforge.pmd
8
- **Package Type**: maven
9
- **Language**: Java
10
- **Installation**: Add to Maven dependencies:
11
```xml
12
<dependency>
13
<groupId>net.sourceforge.pmd</groupId>
14
<artifactId>pmd-core</artifactId>
15
<version>7.13.0</version>
16
</dependency>
17
```
18
19
## Core Imports
20
21
```java
22
import net.sourceforge.pmd.PMDConfiguration;
23
import net.sourceforge.pmd.PmdAnalysis;
24
import net.sourceforge.pmd.lang.Language;
25
import net.sourceforge.pmd.lang.LanguageRegistry;
26
import net.sourceforge.pmd.lang.rule.Rule;
27
import net.sourceforge.pmd.lang.rule.RuleSet;
28
import net.sourceforge.pmd.reporting.Report;
29
import net.sourceforge.pmd.renderers.Renderer;
30
```
31
32
## Basic Usage
33
34
```java
35
import net.sourceforge.pmd.*;
36
import net.sourceforge.pmd.lang.rule.*;
37
import net.sourceforge.pmd.reporting.*;
38
39
// Create PMD configuration
40
PMDConfiguration config = new PMDConfiguration();
41
config.setThreads(4);
42
config.addInputPath(Paths.get("src/main/java"));
43
config.addRuleSet("rulesets/java/quickstart.xml");
44
config.setReportFormat("text");
45
46
// Run analysis
47
try (PmdAnalysis analysis = PmdAnalysis.create(config)) {
48
// Add files for analysis
49
analysis.files().addDirectory(Paths.get("src/main/java"));
50
51
// Load rulesets
52
RuleSetLoader loader = analysis.newRuleSetLoader();
53
analysis.addRuleSet(loader.loadFromResource("rulesets/java/quickstart.xml"));
54
55
// Execute analysis and collect report
56
Report report = analysis.performAnalysisAndCollectReport();
57
58
// Process violations
59
List<RuleViolation> violations = report.getViolations();
60
for (RuleViolation violation : violations) {
61
System.out.printf("%s:%d - %s%n",
62
violation.getFilename(),
63
violation.getBeginLine(),
64
violation.getDescription());
65
}
66
67
System.out.printf("Found %d violations%n", violations.size());
68
}
69
```
70
71
## Architecture
72
73
PMD Core is organized around several key architectural components:
74
75
- **Analysis Engine**: `PmdAnalysis` orchestrates the complete analysis workflow from configuration to report generation
76
- **Configuration Management**: `PMDConfiguration` and `AbstractConfiguration` handle runtime settings and options
77
- **Language Framework**: `Language` and `LanguageRegistry` provide modular support for different programming languages
78
- **Rule System**: `Rule`, `RuleSet`, and related classes define and manage analysis rules with priorities and properties
79
- **AST Processing**: `Node` interface and related classes enable navigation and analysis of Abstract Syntax Trees
80
- **Reporting Infrastructure**: `Report`, `RuleViolation`, and listener interfaces collect and structure analysis results
81
- **Rendering System**: `Renderer` implementations format reports for various output formats (XML, HTML, JSON, etc.)
82
- **Properties Framework**: Type-safe configuration system for rules and components
83
- **Copy-Paste Detection**: Specialized engine for identifying code duplications
84
85
## Capabilities
86
87
### Core PMD Analysis
88
89
Main entry point for programmatic PMD analysis with comprehensive configuration options and lifecycle management.
90
91
```java { .api }
92
// Primary analysis interface
93
class PmdAnalysis implements AutoCloseable {
94
static PmdAnalysis create(PMDConfiguration config);
95
FileCollector files();
96
RuleSetLoader newRuleSetLoader();
97
void addRuleSet(RuleSet ruleSet);
98
Report performAnalysisAndCollectReport();
99
void performAnalysis();
100
void close();
101
}
102
103
// Core configuration class
104
class PMDConfiguration extends AbstractConfiguration {
105
PMDConfiguration();
106
PMDConfiguration(LanguageRegistry languageRegistry);
107
void setThreads(int threads);
108
void addRuleSet(String rulesetPath);
109
void setMinimumPriority(RulePriority minimumPriority);
110
void setReportFormat(String reportFormat);
111
Renderer createRenderer();
112
}
113
```
114
115
[Core PMD Analysis](./core-analysis.md)
116
117
### Rule System
118
119
Comprehensive rule management system with priorities, properties, and lifecycle support for defining static analysis rules.
120
121
```java { .api }
122
// Core rule interface
123
interface Rule extends PropertySource {
124
Language getLanguage();
125
void setLanguage(Language language);
126
String getName();
127
void setName(String name);
128
RulePriority getPriority();
129
void setPriority(RulePriority priority);
130
String getMessage();
131
void setMessage(String message);
132
void apply(Node target, RuleContext ctx);
133
Rule deepCopy();
134
}
135
136
// Rule priority enumeration
137
enum RulePriority {
138
HIGH(1), MEDIUM_HIGH(2), MEDIUM(3), MEDIUM_LOW(4), LOW(5);
139
int getPriority();
140
String getName();
141
static RulePriority valueOf(int priority);
142
}
143
```
144
145
[Rule System](./rule-system.md)
146
147
### Language Framework
148
149
Modular language support system enabling PMD to analyze multiple programming languages with version-specific handling.
150
151
```java { .api }
152
// Core language interface
153
interface Language extends Comparable<Language> {
154
String getName();
155
String getShortName();
156
String getId();
157
List<String> getExtensions();
158
boolean hasExtension(String extensionWithoutDot);
159
List<LanguageVersion> getVersions();
160
LanguageVersion getLatestVersion();
161
LanguageVersion getDefaultVersion();
162
boolean hasVersion(String version);
163
LanguageVersion getVersion(String version);
164
}
165
166
// Language registry for collections
167
final class LanguageRegistry implements Iterable<Language> {
168
static final LanguageRegistry PMD;
169
static final LanguageRegistry CPD;
170
LanguageRegistry(Set<? extends Language> languages);
171
Language getLanguageById(String langId);
172
Language getLanguageByFullName(String languageName);
173
}
174
```
175
176
[Language Framework](./language-framework.md)
177
178
### AST Processing
179
180
Abstract Syntax Tree navigation and processing capabilities for analyzing parsed source code structures.
181
182
```java { .api }
183
// Core AST node interface
184
interface Node {
185
String getXPathNodeName();
186
Node getParent();
187
Node getChild(int index);
188
int getNumChildren();
189
List<? extends Node> getChildren();
190
Node getFirstChild();
191
Node getLastChild();
192
Node getNextSibling();
193
Node getPreviousSibling();
194
<T extends Node> List<T> findDescendantsOfType(Class<T> type);
195
<T extends Node> T getFirstDescendantOfType(Class<T> type);
196
NodeStream<? extends Node> descendants();
197
TextRegion getTextRegion();
198
String getText();
199
}
200
```
201
202
[AST Processing](./ast-processing.md)
203
204
### Reporting System
205
206
Comprehensive reporting infrastructure for collecting violations, errors, and metrics with event-driven processing.
207
208
```java { .api }
209
// Main report class
210
final class Report {
211
static Report buildReport(Consumer<? super FileAnalysisListener> lambda);
212
List<RuleViolation> getViolations();
213
List<SuppressedViolation> getSuppressedViolations();
214
List<ProcessingError> getProcessingErrors();
215
Report filterViolations(Predicate<RuleViolation> filter);
216
Report union(Report other);
217
ReportStats getStats();
218
boolean isEmpty();
219
}
220
221
// Rule violation interface
222
interface RuleViolation {
223
Rule getRule();
224
String getDescription();
225
boolean isSuppressed();
226
String getFilename();
227
int getBeginLine();
228
int getBeginColumn();
229
int getEndLine();
230
int getEndColumn();
231
}
232
```
233
234
[Reporting System](./reporting-system.md)
235
236
### Rendering System
237
238
Extensible rendering framework for formatting analysis reports in various output formats including XML, HTML, JSON, and text.
239
240
```java { .api }
241
// Core renderer interface
242
interface Renderer extends PropertySource {
243
String getName();
244
void setName(String name);
245
String getDescription();
246
String defaultFileExtension();
247
void setShowSuppressedViolations(boolean show);
248
void setWriter(Writer writer);
249
GlobalAnalysisListener newListener();
250
void start();
251
void end();
252
void flush();
253
}
254
```
255
256
[Rendering System](./rendering-system.md)
257
258
### Properties System
259
260
Type-safe configuration framework for rules and components with validation, serialization, and factory methods.
261
262
```java { .api }
263
// Property source interface
264
interface PropertySource {
265
<T> T getProperty(PropertyDescriptor<T> propertyDescriptor);
266
<T> void setProperty(PropertyDescriptor<T> propertyDescriptor, T value);
267
boolean hasDescriptor(PropertyDescriptor<?> descriptor);
268
List<PropertyDescriptor<?>> getPropertyDescriptors();
269
Map<PropertyDescriptor<?>, Object> getPropertiesByPropertyDescriptor();
270
}
271
272
// Property descriptor interface
273
interface PropertyDescriptor<T> {
274
String name();
275
String description();
276
Class<T> type();
277
T defaultValue();
278
boolean isRequired();
279
T valueFrom(String propertyString);
280
String errorFor(T value);
281
}
282
```
283
284
[Properties System](./properties-system.md)
285
286
### Copy-Paste Detection
287
288
Specialized engine for detecting code duplications across files with configurable token-based analysis.
289
290
```java { .api }
291
// Main CPD class
292
class CPD {
293
CPD(CPDConfiguration configuration);
294
void go();
295
Iterator<Match> getMatches();
296
int getNumberOfTokens(String file);
297
Map<String, Integer> getTokenCounts();
298
}
299
300
// Duplication match representation
301
final class Match {
302
int getTokenCount();
303
int getLineCount();
304
List<Mark> getMarkSet();
305
String getSourceCodeSlice();
306
}
307
```
308
309
[Copy-Paste Detection](./copy-paste-detection.md)
310
311
### Utilities and Support Classes
312
313
Essential utility classes for assertions, string manipulation, file handling, and other common operations.
314
315
```java { .api }
316
// Assertion utilities
317
final class AssertionUtil {
318
static <T> T requireParamNotNull(String paramName, T param);
319
static <T> void requireContainsNoNullValue(String paramName, Collection<T> collection);
320
static AssertionError shouldNotReachHere();
321
static AssertionError shouldNotReachHere(String message);
322
}
323
324
// String manipulation utilities
325
final class StringUtil {
326
static boolean isEmpty(String str);
327
static boolean isNotEmpty(String str);
328
static boolean isBlank(String str);
329
static boolean isNotBlank(String str);
330
static List<String> split(String str, char separator);
331
}
332
```
333
334
[Utilities and Support Classes](./utilities.md)
335
336
## Essential Types
337
338
```java { .api }
339
// Abstract base configuration
340
abstract class AbstractConfiguration {
341
Charset getSourceEncoding();
342
void setSourceEncoding(Charset sourceEncoding);
343
LanguagePropertyBundle getLanguageProperties(Language language);
344
LanguageRegistry getLanguageRegistry();
345
PmdReporter getReporter();
346
void setReporter(PmdReporter reporter);
347
LanguageVersion getForceLanguageVersion();
348
void setForceLanguageVersion(LanguageVersion version);
349
List<Path> getInputPathList();
350
void setInputPathList(List<Path> inputPaths);
351
void addInputPath(Path inputPath);
352
Path getReportFilePath();
353
void setReportFile(Path reportFile);
354
boolean isFailOnViolation();
355
void setFailOnViolation(boolean failOnViolation);
356
}
357
358
// File collection interface
359
interface FileCollector extends AutoCloseable {
360
void addFile(Path file);
361
void addDirectory(Path dir);
362
void addZipFile(Path zipFile);
363
void addSourceURI(URI uri);
364
List<TextFile> getCollectedFiles();
365
void filterLanguages(Set<Language> languages);
366
}
367
368
// Text file representation
369
interface TextFile {
370
FileId getFileId();
371
String getDisplayName();
372
LanguageVersion getLanguageVersion();
373
TextDocument readOnlyDocument();
374
void writeToPath(Path destination, Charset charset);
375
boolean isReadOnly();
376
}
377
378
// Rule set collection
379
class RuleSet implements ChecksumAware {
380
RuleSet(RuleSet rs);
381
static RuleSet forSingleRule(Rule rule);
382
static RuleSetBuilder create();
383
String getFileName();
384
String getName();
385
String getDescription();
386
List<Rule> getRules();
387
Rule getRuleByName(String ruleName);
388
boolean applies(FileId file);
389
boolean applies(LanguageVersion languageVersion);
390
int size();
391
Iterator<Rule> iterator();
392
}
393
394
// Rule set loading
395
final class RuleSetLoader {
396
static RuleSetLoader fromPmdConfig(PMDConfiguration configuration);
397
RuleSet loadFromResource(String ruleSetReferenceId);
398
List<RuleSet> loadFromResources(List<String> ruleSetReferenceIds);
399
RuleSetBuilder newRuleSetBuilder();
400
RuleSetLoader filterAbovePriority(RulePriority minimumPriority);
401
List<RuleSetLoadException> getLoadExceptions();
402
}
403
404
// Analysis listener interfaces
405
interface GlobalAnalysisListener extends AutoCloseable {
406
ListenerInitializer initializer();
407
FileAnalysisListener startFileAnalysis(TextFile file);
408
void onConfigError(Report.ConfigurationError error);
409
static GlobalAnalysisListener noop();
410
static GlobalAnalysisListener tee(List<? extends GlobalAnalysisListener> listeners);
411
}
412
413
interface FileAnalysisListener {
414
void onRuleViolation(RuleViolation violation);
415
void onSuppressedRuleViolation(Report.SuppressedViolation violation);
416
void onError(Report.ProcessingError error);
417
}
418
419
// Version information
420
final class PMDVersion {
421
static final String VERSION;
422
static String getNextMajorRelease();
423
static boolean isUnknown();
424
static boolean isSnapshot();
425
static String getFullVersionName();
426
}
427
```