summaryrefslogtreecommitdiff
path: root/kythe/java/com/google/devtools/kythe/extractors/java/standalone/Javac9Wrapper.java
blob: 31bc66a7b6778f60b25ac95450a80a239231a725 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
/*
 * Copyright 2014 The Kythe Authors. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.devtools.kythe.extractors.java.standalone;

import static com.google.common.collect.ImmutableList.toImmutableList;

import com.google.common.collect.Lists;
import com.google.devtools.kythe.extractors.java.JavaCompilationUnitExtractor;
import com.google.devtools.kythe.extractors.shared.CompilationDescription;
import com.google.devtools.kythe.extractors.shared.EnvironmentUtils;
import com.sun.tools.javac.file.JavacFileManager;
import com.sun.tools.javac.main.Arguments;
import com.sun.tools.javac.main.Option;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.Options;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumSet;
import java.util.List;
import javax.tools.JavaFileObject;
import javax.tools.StandardLocation;

/** A class that wraps javac to extract compilation information and write it to an index file. */
public class Javac9Wrapper extends AbstractJavacWrapper {
  @Override
  protected Collection<CompilationDescription> processCompilation(
      String[] arguments, JavaCompilationUnitExtractor javaCompilationUnitExtractor)
      throws Exception {
    // Use javac's argument parser to get the list of source files
    Context context = new Context();

    JavacFileManager fileManager = new JavacFileManager(context, true, null);
    Arguments args = Arguments.instance(context);
    // JDK changed the signature of Arguments.init method, support both
    try {
      try {
        // JDK15+: the signature is
        //     init(String, Iterable<String> args);
        Arguments.class.getMethod("init", String.class, Iterable.class)
          .invoke(args, "kythe_javac", (Object) Arrays.asList(arguments));
      } catch (NoSuchMethodException nsme) {
        // pre-JDK15:
        //     init(String, String...);
        Arguments.class.getMethod("init", String.class,String[].class)
          .invoke(args, "kythe_javac", (Object)arguments);
      }
    } catch (NoSuchMethodException ns2) {
      System.err.printf("Cannot locate com.sun.tools.javac.main.Arguments.init method, JDK version %s\n", System.getProperty("java.version"));
      System.exit(2);
    } catch (InvocationTargetException|IllegalAccessException ex) {
      System.err.printf("Cannot call com.sun.tools.javac.main.Arguments.init (JDK version %s):\n%s\n", System.getProperty("java.version"), ex);
      System.exit(2);
    }

    fileManager.handleOptions(args.getDeferredFileManagerOptions());
    Options options = Options.instance(context);

    List<String> sources =
        args.getFileObjects().stream().map(JavaFileObject::getName).collect(toImmutableList());

    // Retrieve the list of class paths provided by the -classpath argument.
    List<String> classPaths = splitPaths(options.get(Option.CLASS_PATH));

    // Retrieve the list of source paths provided by the -sourcepath argument.
    List<String> sourcePaths = splitPaths(options.get(Option.SOURCE_PATH));

    // Retrieve the list of processor paths provided by the -processorpath argument.
    List<String> processorPaths = splitPaths(options.get(Option.PROCESSOR_PATH));

    // Retrieve the list of processors provided by the -processor argument.
    List<String> processors = splitCSV(options.get(Option.PROCESSOR));

    // Retrieve system path (the value of --system=, unless it equals 'none'
    String sysd = options.get(Option.SYSTEM);
    if (sysd != null && !"none".equals(sysd)) {
      javaCompilationUnitExtractor.useSystemDirectory(sysd);
    }

    EnumSet<Option> claimed =
        EnumSet.of(Option.CLASS_PATH, Option.SOURCE_PATH, Option.PROCESSOR_PATH, Option.PROCESSOR);

    List<String> completeOptions = new ArrayList<>();
    if (options.isSet(Option.RELEASE)) {
      // If --release is set, claim it and the associated -source/-target flags.
      completeOptions.add(Option.RELEASE.getPrimaryName());
      completeOptions.add(options.get(Option.RELEASE));
      claimed.add(Option.RELEASE);
      claimed.add(Option.SOURCE);
      claimed.add(Option.TARGET);
    }

    // Retrieve all other javac options.
    for (Option opt : Option.values()) {
      if (!claimed.contains(opt)) {
        String value = options.get(opt);
        if (value != null) {
          if (opt.getPrimaryName().endsWith(":")) {
            completeOptions.add(opt.getPrimaryName() + value);
          } else {
            completeOptions.add(opt.getPrimaryName());
            if (!value.equals(opt.getPrimaryName())) {
              completeOptions.add(value);
            }
          }
        }
      }
    }

    /* Special processing for -Ax=y options. Arguments.init immediately processes them
     * into x=>y pairs that cannot be easily retrieved. This may be an indication that
     * we are processing the command line arguments in a wrong way (that is, after parsing
     * them we reconstruct the strings and pass them as completeOptions).
     */
    for (String arg : arguments) {
      if (arg.startsWith("-A")) {
        completeOptions.add(arg);
      }
    }

    List<String> bootclasspath = new ArrayList<>();
    for (File bcp : fileManager.getLocation(StandardLocation.PLATFORM_CLASS_PATH)) {
      bootclasspath.add(bcp.toString());
    }

    // Get the output directory for this target.
    String outputDirectory = options.get(Option.D);
    if (outputDirectory == null) {
      outputDirectory = ".";
    }

    int batchSize = readSourcesBatchSize().orElse(sources.size());
    List<CompilationDescription> results = new ArrayList<>();
    for (List<String> sourceBatch : Lists.partition(sources, batchSize)) {
      String analysisTarget =
          EnvironmentUtils.readEnvironmentVariable(
              "KYTHE_ANALYSIS_TARGET", createTargetFromSourceFiles(sourceBatch));

      results.add(
          javaCompilationUnitExtractor.extract(
              analysisTarget,
              sourceBatch,
              classPaths,
              bootclasspath,
              sourcePaths,
              processorPaths,
              processors,
              completeOptions,
              outputDirectory));
    }
    return results;
  }

  @Override
  protected void passThrough(String[] args) throws Exception {
    com.sun.tools.javac.Main.main(args);
  }

  public static void main(String[] args) {
    new Javac9Wrapper().process(args);
  }
}