You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by su...@apache.org on 2019/11/17 08:53:58 UTC

[groovy] 03/18: add notes on joint compiler arguments and refactor minor stuff

This is an automated email from the ASF dual-hosted git repository.

sunlan pushed a commit to branch GROOVY_3_0_X
in repository https://gitbox.apache.org/repos/asf/groovy.git

commit 7b86d85c14e50021f8f0dd67bf278b3498625afe
Author: Eric Milles <er...@thomsonreuters.com>
AuthorDate: Tue Nov 12 17:20:59 2019 -0600

    add notes on joint compiler arguments and refactor minor stuff
    
    (cherry picked from commit 6aff769ed697218229fa12f6bbf3e4903f725218)
---
 .../groovy/tools/javac/JavacJavaCompiler.java      | 79 ++++++++------------
 .../main/java/org/codehaus/groovy/ant/Groovyc.java | 83 ++++++++++++++--------
 2 files changed, 83 insertions(+), 79 deletions(-)

diff --git a/src/main/java/org/codehaus/groovy/tools/javac/JavacJavaCompiler.java b/src/main/java/org/codehaus/groovy/tools/javac/JavacJavaCompiler.java
index 4024f42..cb35ad2 100644
--- a/src/main/java/org/codehaus/groovy/tools/javac/JavacJavaCompiler.java
+++ b/src/main/java/org/codehaus/groovy/tools/javac/JavacJavaCompiler.java
@@ -27,10 +27,6 @@ import org.codehaus.groovy.control.messages.ExceptionMessage;
 import org.codehaus.groovy.control.messages.SimpleMessage;
 import org.codehaus.groovy.runtime.DefaultGroovyMethods;
 
-import javax.tools.JavaCompiler.CompilationTask;
-import javax.tools.JavaFileObject;
-import javax.tools.StandardJavaFileManager;
-import javax.tools.ToolProvider;
 import java.io.File;
 import java.io.IOException;
 import java.net.URISyntaxException;
@@ -41,9 +37,7 @@ import java.security.AccessController;
 import java.security.CodeSource;
 import java.security.PrivilegedAction;
 import java.util.ArrayList;
-import java.util.Arrays;
 import java.util.Collections;
-import java.util.LinkedList;
 import java.util.List;
 import java.util.Locale;
 import java.util.Map;
@@ -51,7 +45,7 @@ import java.util.Set;
 import java.util.stream.Collectors;
 
 public class JavacJavaCompiler implements JavaCompiler {
-    private static final String[] EMPTY_STRING_ARRAY = new String[0];
+
     private static final Locale DEFAULT_LOCALE = Locale.ENGLISH;
     private final CompilerConfiguration config;
     private final Charset charset;
@@ -62,7 +56,7 @@ public class JavacJavaCompiler implements JavaCompiler {
     }
 
     public void compile(List<String> files, CompilationUnit cu) {
-        String[] javacParameters = makeParameters(cu.getClassLoader());
+        List<String> javacParameters = makeParameters(cu.getClassLoader());
         StringBuilderWriter javacOutput = new StringBuilderWriter();
         int javacReturnValue = 0;
         try {
@@ -78,7 +72,6 @@ public class JavacJavaCompiler implements JavaCompiler {
                 javacReturnValue = 1;
                 cu.getErrorCollector().addFatalError(new ExceptionMessage(e, true, cu));
             }
-
         } catch (Exception e) {
             cu.getErrorCollector().addFatalError(new ExceptionMessage(e, true, cu));
         }
@@ -95,23 +88,21 @@ public class JavacJavaCompiler implements JavaCompiler {
         }
     }
 
-    private boolean doCompileWithSystemJavaCompiler(CompilationUnit cu, List<String> files, String[] javacParameters, StringBuilderWriter javacOutput) throws IOException {
-        javax.tools.JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
-        try (StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, DEFAULT_LOCALE, charset)) {
-            final Set<JavaFileObject> compilationUnitSet = cu.getJavaCompilationUnitSet(); // java stubs already added
+    private boolean doCompileWithSystemJavaCompiler(CompilationUnit cu, List<String> files, List<String> javacParameters, StringBuilderWriter javacOutput) throws IOException {
+        javax.tools.JavaCompiler compiler = javax.tools.ToolProvider.getSystemJavaCompiler();
+        try (javax.tools.StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, DEFAULT_LOCALE, charset)) {
+            Set<javax.tools.JavaFileObject> compilationUnitSet = cu.getJavaCompilationUnitSet(); // java stubs already added
 
             // add java source files to compile
             fileManager.getJavaFileObjectsFromFiles(
-                    files.stream()
-                            .map(File::new)
-                            .collect(Collectors.toList())
+                    files.stream().map(File::new).collect(Collectors.toList())
             ).forEach(compilationUnitSet::add);
 
-            CompilationTask compilationTask = compiler.getTask(
+            javax.tools.JavaCompiler.CompilationTask compilationTask = compiler.getTask(
                     javacOutput,
                     fileManager,
                     null,
-                    Arrays.asList(javacParameters),
+                    javacParameters,
                     Collections.emptyList(),
                     compilationUnitSet
             );
@@ -133,72 +124,64 @@ public class JavacJavaCompiler implements JavaCompiler {
         cu.getErrorCollector().addFatalError(new SimpleMessage(header, cu));
     }
 
-    private String[] makeParameters(GroovyClassLoader parentClassLoader) {
-        Map options = config.getJointCompilationOptions();
-        LinkedList<String> paras = new LinkedList<String>();
+    private List<String> makeParameters(GroovyClassLoader parentClassLoader) {
+        Map<String, Object> options = config.getJointCompilationOptions();
+        List<String> params = new ArrayList<>();
 
         File target = config.getTargetDirectory();
         if (target == null) target = new File(".");
 
-        // defaults
-        paras.add("-d");
-        paras.add(target.getAbsolutePath());
+        params.add("-d");
+        params.add(target.getAbsolutePath());
 
-        // add flags
         String[] flags = (String[]) options.get("flags");
         if (flags != null) {
             for (String flag : flags) {
-                paras.add('-' + flag);
+                params.add("-" + flag);
             }
         }
 
         boolean hadClasspath = false;
-        // add namedValues
         String[] namedValues = (String[]) options.get("namedValues");
         if (namedValues != null) {
-            for (int i = 0; i < namedValues.length; i += 2) {
+            for (int i = 0, n = namedValues.length; i < n; i += 2) {
                 String name = namedValues[i];
                 if (name.equals("classpath")) hadClasspath = true;
-                paras.add('-' + name);
-                paras.add(namedValues[i + 1]);
+                params.add("-" + name);
+                params.add(namedValues[i + 1]);
             }
         }
 
         // append classpath if not already defined
         if (!hadClasspath) {
             // add all classpaths that compilation unit sees
-            List<String> paths = new ArrayList<String>(config.getClasspath());
-            ClassLoader cl = parentClassLoader;
-            while (cl != null) {
-                if (cl instanceof URLClassLoader) {
-                    for (URL u : ((URLClassLoader) cl).getURLs()) {
+            List<String> paths = new ArrayList<>(config.getClasspath());
+            ClassLoader loader = parentClassLoader;
+            while (loader != null) {
+                if (loader instanceof URLClassLoader) {
+                    for (URL u : ((URLClassLoader) loader).getURLs()) {
                         try {
                             paths.add(new File(u.toURI()).getPath());
-                        } catch (URISyntaxException e) {
-                            // ignore it
+                        } catch (URISyntaxException ignore) {
                         }
                     }
                 }
-                cl = cl.getParent();
+                loader = loader.getParent();
             }
 
             try {
-                CodeSource codeSource =
-                        AccessController.doPrivileged(
-                                (PrivilegedAction<CodeSource>) () -> GroovyObject.class.getProtectionDomain().getCodeSource()
-                        );
+                CodeSource codeSource = AccessController.doPrivileged(
+                        (PrivilegedAction<CodeSource>) () -> GroovyObject.class.getProtectionDomain().getCodeSource());
                 if (codeSource != null) {
                     paths.add(new File(codeSource.getLocation().toURI()).getPath());
                 }
-            } catch (URISyntaxException e) {
-                // ignore it
+            } catch (URISyntaxException ignore) {
             }
 
-            paras.add("-classpath");
-            paras.add(DefaultGroovyMethods.join((Iterable) paths, File.pathSeparator));
+            params.add("-classpath");
+            params.add(DefaultGroovyMethods.join((Iterable<String>) paths, File.pathSeparator));
         }
 
-        return paras.toArray(EMPTY_STRING_ARRAY);
+        return params;
     }
-
 }
diff --git a/subprojects/groovy-ant/src/main/java/org/codehaus/groovy/ant/Groovyc.java b/subprojects/groovy-ant/src/main/java/org/codehaus/groovy/ant/Groovyc.java
index a7d41af..a255703 100644
--- a/subprojects/groovy-ant/src/main/java/org/codehaus/groovy/ant/Groovyc.java
+++ b/subprojects/groovy-ant/src/main/java/org/codehaus/groovy/ant/Groovyc.java
@@ -52,7 +52,7 @@ import java.nio.charset.Charset;
 import java.security.AccessController;
 import java.security.PrivilegedAction;
 import java.util.ArrayList;
-import java.util.Enumeration;
+import java.util.Collections;
 import java.util.LinkedHashSet;
 import java.util.List;
 import java.util.Map;
@@ -959,47 +959,68 @@ public class Groovyc extends MatchingTask {
         }
     }
 
+    /**
+     * If {@code groovyc} task includes a nested {@code javac} task, check for
+     * shareable configuration.  {@code FileSystemCompiler} supports several
+     * command-line arguments for configuring joint compilation:
+     * <ul>
+     * <li><tt>-j</tt> enables joint compile
+     * <li><tt>-F</tt> is used to pass flags
+     * <li><tt>-J</tt> is used to pass name=value pairs
+     * </ul>
+     * Joint compilation options are transferred from {@link FileSystemCompiler}
+     * to {@link CompilerConfiguration}'s jointCompileOptions property.  Flags
+     * are saved to key "flags" (with the inclusion of "parameters" if enabled
+     * on groovyc), pairs are saved to key "namedValues" and the key "memStub"
+     * may also be set to {@link Boolean#TRUE} to influence joint compilation.
+     *
+     * @see org.codehaus.groovy.tools.javac.JavacJavaCompiler
+     * @see javax.tools.JavaCompiler
+     */
     private List<String> extractJointOptions(Path classpath) {
         List<String> jointOptions = new ArrayList<>();
         if (!jointCompilation) return jointOptions;
 
-        // extract joint options, some get pushed up...
+        // map "debug" and "debuglevel" to "-Fg"
+        if (javac.getDebug()) {
+            jointOptions.add("-Fg" + Optional.ofNullable(javac.getDebugLevel()).map(level -> ":" + level).orElse(""));
+        } else {
+            jointOptions.add("-Fg:none");
+        }
+
+        // map "verbose" to "-Fverbose"
+        if (javac.getVerbose()) {
+            jointOptions.add("-Fverbose");
+        }
+
         RuntimeConfigurable rc = javac.getRuntimeConfigurableWrapper();
+
         for (Map.Entry<String, Object> e : rc.getAttributeMap().entrySet()) {
             String key = e.getKey();
-            String value = getProject().replaceProperties(e.getValue().toString());
-            if (key.contains("debug")) {
-                String level = "";
-                if (javac.getDebugLevel() != null) {
-                    level = ":" + javac.getDebugLevel();
-                }
-                jointOptions.add("-Fg" + level);
-            } else if (key.contains("debugLevel")) {
-                // ignore, taken care of in debug
-            } else if (key.contains("verbose")) {
-                // false is default, so something to do only in true case
-                if ("on".equalsIgnoreCase(value) || "true".equalsIgnoreCase(value) || "yes".equalsIgnoreCase(value))
-                    jointOptions.add("-F" + key);
+            if (key.contains("encoding")
+                    || key.contains("extdirs")
+                    || key.contains("depend")
+                    || key.contains("source")
+                    || key.contains("target")) {
+                // map "encoding", etc. to "-Jkey=val"
+                jointOptions.add("-J" + key + "=" + getProject().replaceProperties(e.getValue().toString()));
+
             } else if (key.contains("classpath")) {
-                classpath.add(javac.getClasspath());
-            } else if ((key.contains("depend"))
-                    || (key.contains("extdirs"))
-                    || (key.contains("encoding"))
-                    || (key.contains("source"))
-                    || (key.contains("target"))
-                    || (key.contains("verbose"))) { // already handling verbose but pass on too
-                jointOptions.add("-J" + key + "=" + value);
-            } else {
-                log.warn("The option " + key + " cannot be set on the contained <javac> element. The option will be ignored");
+                if (key.startsWith("boot")) {
+                    // TODO: javac.getBootclasspath()
+                } else {
+                    classpath.add(javac.getClasspath());
+                }
+            } else if (!key.contains("debug") && !key.contains("verbose")) {
+                log.warn("The option " + key + " cannot be set on the contained <javac> element. The option will be ignored.");
             }
-            // TODO includes? excludes?
+            // TODO: modulepath, modulepathref, modulesourcepath, modulesourcepathref, upgrademodulepath, upgrademodulepathref
+            // TODO: release, deprecation, failonerror, nowarn, tempdir, nativeheaderdir, includes(file)? excludes(file)?
         }
 
-        // ant's <javac> supports nested <compilerarg value=""> elements (there can be multiple of them)
-        // for additional options to be passed to javac.
-        Enumeration<RuntimeConfigurable> children = rc.getChildren();
-        while (children.hasMoreElements()) {
-            RuntimeConfigurable childrc = children.nextElement();
+        // Ant's <javac> supports nested <compilerarg value=""> elements (there
+        // can be multiple of them) for additional options to be passed to javac.
+        for (RuntimeConfigurable childrc : Collections.list(rc.getChildren())) {
             if (childrc.getElementTag().equals("compilerarg")) {
                 for (Map.Entry<String, Object> e : childrc.getAttributeMap().entrySet()) {
                     String key = e.getKey();