Path: blob/master/test/langtools/tools/all/RunCodingRules.java
41145 views
/*1* Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/*24* @test25* @bug 804364326* @summary Run the langtools coding rules over the langtools source code.27* @modules jdk.compiler/com.sun.tools.javac.util28*/293031import java.io.*;32import java.lang.reflect.Method;33import java.net.URL;34import java.net.URLClassLoader;35import java.nio.file.Files;36import java.nio.file.Path;37import java.nio.file.Paths;38import java.nio.file.StandardOpenOption;39import java.util.*;40import java.util.stream.Collectors;41import java.util.stream.Stream;4243import javax.tools.Diagnostic;44import javax.tools.DiagnosticListener;45import javax.tools.JavaCompiler;46import javax.tools.JavaFileObject;47import javax.tools.StandardJavaFileManager;48import javax.tools.ToolProvider;4950import com.sun.tools.javac.util.Assert;5152/**53* This is a test to verify specific coding standards for source code in the langtools repository.54*55* As such, it is not a standard unit, regression or functional test, and will56* automatically skip if the langtools source code is not available.57*58* If the source code is available, it will find and compile the coding59* style analyzers found in langtools/make/tools/crules/*.java, and run the resulting60* code on all source files under langtools/src/share/classes. Any coding style61* violations will cause the test to fail.62*/63public class RunCodingRules {64public static void main(String... args) throws Exception {65new RunCodingRules().run();66}6768public void run() throws Exception {69Path testSrc = Paths.get(System.getProperty("test.src", "."));70Path targetDir = Paths.get(".");71List<Path> sourceDirs = null;72Path crulesDir = null;73Path mainSrcDir = null;74for (Path d = testSrc; d != null; d = d.getParent()) {75if (Files.exists(d.resolve("TEST.ROOT"))) {76d = d.getParent();77Path toolsPath = d.resolve("make/tools");78if (Files.exists(toolsPath)) {79mainSrcDir = d.resolve("src");80crulesDir = toolsPath;81sourceDirs = Files.walk(mainSrcDir, 1)82.map(p -> p.resolve("share/classes"))83.filter(p -> Files.isDirectory(p))84.collect(Collectors.toList());85break;86}87}88}8990if (sourceDirs == null || crulesDir == null) {91System.err.println("Warning: sources not found, test skipped.");92return ;93}9495JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();96try (StandardJavaFileManager fm = javaCompiler.getStandardFileManager(null, null, null)) {97DiagnosticListener<JavaFileObject> noErrors = diagnostic -> {98Assert.check(diagnostic.getKind() != Diagnostic.Kind.ERROR, diagnostic.toString());99};100String FS = File.separator;101String PS = File.pathSeparator;102103//compile crules:104List<File> crulesFiles = Files.walk(crulesDir)105.filter(entry -> entry.getFileName().toString().endsWith(".java"))106.filter(entry -> entry.getParent().endsWith("crules"))107.map(entry -> entry.toFile())108.collect(Collectors.toList());109110Path crulesTarget = targetDir.resolve("crules");111Files.createDirectories(crulesTarget);112List<String> crulesOptions = Arrays.asList(113"--add-exports", "jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED",114"--add-exports", "jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED",115"--add-exports", "jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED",116"--add-exports", "jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED",117"--add-exports", "jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED",118"-d", crulesTarget.toString());119javaCompiler.getTask(null, fm, noErrors, crulesOptions, null,120fm.getJavaFileObjectsFromFiles(crulesFiles)).call();121Path registration = crulesTarget.resolve("META-INF/services/com.sun.source.util.Plugin");122Files.createDirectories(registration.getParent());123try (Writer metaInfServices = Files.newBufferedWriter(registration, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) {124metaInfServices.write("crules.CodingRulesAnalyzerPlugin\n");125}126127//generate CompilerProperties.java:128List<File> propertiesParserFiles =129Files.walk(crulesDir.resolve("propertiesparser"))130.filter(entry -> entry.getFileName().toString().endsWith(".java"))131.map(entry -> entry.toFile())132.collect(Collectors.toList());133134Path propertiesParserTarget = targetDir.resolve("propertiesParser");135Files.createDirectories(propertiesParserTarget);136List<String> propertiesParserOptions = Arrays.asList(137"-d", propertiesParserTarget.toString());138javaCompiler.getTask(null, fm, noErrors, propertiesParserOptions, null,139fm.getJavaFileObjectsFromFiles(propertiesParserFiles)).call();140141Path genSrcTarget = targetDir.resolve("gensrc");142143ClassLoader propertiesParserLoader = new URLClassLoader(new URL[] {144propertiesParserTarget.toUri().toURL(),145crulesDir.toUri().toURL()146});147Class propertiesParserClass =148Class.forName("propertiesparser.PropertiesParser", false, propertiesParserLoader);149Method propertiesParserRun =150propertiesParserClass.getDeclaredMethod("run", String[].class, PrintStream.class);151String compilerProperties =152"jdk.compiler/share/classes/com/sun/tools/javac/resources/compiler.properties";153Path propertiesPath = mainSrcDir.resolve(compilerProperties.replace("/", FS));154Path genSrcTargetDir = genSrcTarget.resolve(mainSrcDir.relativize(propertiesPath.getParent()));155156Files.createDirectories(genSrcTargetDir);157String[] propertiesParserRunOptions = new String[] {158"-compile", propertiesPath.toString(), genSrcTargetDir.toString()159};160161Object result = propertiesParserRun.invoke(null, propertiesParserRunOptions, System.err);162163if (!(result instanceof Boolean) || !(Boolean) result) {164throw new AssertionError("Cannot parse properties: " + result);165}166167//compile langtools sources with crules enabled:168List<File> sources = sourceDirs.stream()169.flatMap(dir -> silentFilesWalk(dir))170.filter(entry -> entry.getFileName().toString().endsWith(".java"))171.map(p -> p.toFile())172.collect(Collectors.toList());173174Path sourceTarget = targetDir.resolve("classes");175Files.createDirectories(sourceTarget);176String processorPath = crulesTarget + PS + crulesDir;177178List<String> options = Arrays.asList(179"-d", sourceTarget.toString(),180"--module-source-path", mainSrcDir + FS + "*" + FS + "share" + FS + "classes" + PS181+ genSrcTarget + FS + "*" + FS + "share" + FS + "classes",182"-XDaccessInternalAPI",183"-processorpath", processorPath,184"-Xplugin:coding_rules");185javaCompiler.getTask(null, fm, noErrors, options, null,186fm.getJavaFileObjectsFromFiles(sources)).call();187}188}189190Stream<Path> silentFilesWalk(Path dir) throws IllegalStateException {191try {192return Files.walk(dir);193} catch (IOException ex) {194throw new IllegalStateException(ex);195}196}197}198199200