[java] Support module import declarations (JEP 476)

- new JModuleSymbol
- UnnecessaryImportRule also supports module imports
- module-info.class can be loaded by ClasspathClassLoader
- Support annotations on modules
- Verify that exported packages are loaded
This commit is contained in:
Andreas Dangel
2024-07-20 17:51:31 +02:00
parent 176e522721
commit 47470b5d0c
50 changed files with 852 additions and 105 deletions

View File

@@ -12,6 +12,11 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.CodeSource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
@@ -220,6 +225,27 @@ public abstract class RuleTst {
return runTestFromString(test.getCode(), rule, test.getLanguageVersion());
}
private static final Path PATH_TO_JRT_FS_JAR;
static {
// find jrt-fs.jar to be added to auxclasspath
// Similar logic like jdk.internal.jrtfs.SystemImage
CodeSource codeSource = Object.class.getProtectionDomain().getCodeSource();
if (codeSource == null) {
PATH_TO_JRT_FS_JAR = Paths.get(System.getProperty("java.home"), "lib", "jrt-fs.jar");
} else {
URL location = codeSource.getLocation();
if (!"file".equalsIgnoreCase(location.getProtocol())) {
throw new IllegalStateException("Object.class loaded in unexpected way from " + location);
}
try {
PATH_TO_JRT_FS_JAR = Paths.get(location.toURI());
} catch (URISyntaxException e) {
throw new IllegalStateException(e);
}
}
}
/**
* Run the rule on the given code and put the violations in the report.
*/
@@ -229,6 +255,8 @@ public abstract class RuleTst {
configuration.setDefaultLanguageVersion(languageVersion);
configuration.setThreads(0); // don't use separate threads
configuration.prependAuxClasspath(".");
configuration.prependAuxClasspath(PATH_TO_JRT_FS_JAR.toString());
try (PmdAnalysis pmd = PmdAnalysis.create(configuration)) {
pmd.files().addFile(TextFile.forCharSeq(code, FileId.fromPathLikeString("file"), languageVersion));