aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/java_tools/buildjar/java/com/google/devtools/build/buildjar/javac/BlazeJavacMain.java
blob: e086efd0fddd88db1af731fc96b8c409691de4d2 (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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
// Copyright 2014 The Bazel 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.build.buildjar.javac;

import static com.google.common.base.Verify.verifyNotNull;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.base.Verify;
import com.google.devtools.build.buildjar.InvalidCommandLineException;
import com.google.devtools.build.buildjar.javac.plugins.BlazeJavaCompilerPlugin;
import com.google.devtools.build.buildjar.javac.plugins.BlazeJavaCompilerPlugin.PluginException;

import com.sun.source.util.TaskEvent;
import com.sun.source.util.TaskListener;
import com.sun.tools.javac.api.JavacTaskImpl;
import com.sun.tools.javac.api.JavacTool;
import com.sun.tools.javac.api.MultiTaskListener;
import com.sun.tools.javac.comp.CompileStates.CompileState;
import com.sun.tools.javac.main.Main;
import com.sun.tools.javac.main.Main.Result;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.Options;
import com.sun.tools.javac.util.PropagatedException;

import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;

import javax.annotation.processing.Processor;
import javax.tools.DiagnosticListener;
import javax.tools.JavaFileManager;
import javax.tools.JavaFileObject;

/**
 * Main class for our custom patched javac.
 *
 * <p> This main class tweaks the standard javac log class by changing the
 * compiler's context to use our custom log class. This custom log class
 * modifies javac's output to list all errors after all warnings.
 */
public class BlazeJavacMain {

  /**
   * Compose {@link com.sun.tools.javac.main.Main} and perform custom setup before deferring to
   * its compile() method.
   *
   * <p>Historically BlazeJavacMain extended javac's Main and overrode methods to get the desired
   * custom behaviour. That approach created incompatibilities when upgrading to newer versions of
   * javac, so composition is preferred.
   */
  private List<BlazeJavaCompilerPlugin> plugins;
  private final PrintWriter errOutput;
  private final String compilerName;
  private BlazeJavaCompiler compiler = null;

  public BlazeJavacMain(PrintWriter errOutput, List<BlazeJavaCompilerPlugin> plugins) {
    this.compilerName = "blaze javac";
    this.errOutput = errOutput;
    this.plugins = plugins;
  }

  /**
   * Installs the BlazeJavaCompiler within the provided context. Enables
   * plugins based on field values.
   *
   * @param context JavaCompiler's associated Context
   */
  void setupBlazeJavaCompiler(Context context) {
    preRegister(context, plugins);
  }

  private final Function<BlazeJavaCompiler, Void> compilerListener =
      new Function<BlazeJavaCompiler, Void>() {
        @Override
        public Void apply(BlazeJavaCompiler compiler) {
          Verify.verify(BlazeJavacMain.this.compiler == null);
          BlazeJavacMain.this.compiler = Preconditions.checkNotNull(compiler);
          return null;
        }
      };

  public void preRegister(Context context, List<BlazeJavaCompilerPlugin> plugins) {
    this.plugins = plugins;
    for (BlazeJavaCompilerPlugin plugin : plugins) {
      plugin.initializeContext(context);
    }
    BlazeJavaCompiler.preRegister(context, plugins, compilerListener);
  }

  public Result compile(String[] argv) {
    // set up a fresh Context with our custom bindings for JavaCompiler
    Context context = new Context();
    // disable faulty Zip optimizations
    Options options = Options.instance(context);
    options.put("useOptimizedZip", "false");

    // enable Java 8-style type inference features
    //
    // This is currently duplicated in JAVABUILDER. That's deliberate for now, because
    // (1) JavaBuilder's integration test coverage for default options isn't very good, and
    // (2) the migration from JAVABUILDER to java_toolchain configs is in progress so blaze
    // integration tests for defaults options are also not trustworthy.
    //
    // TODO(bazel-team): removed duplication with JAVABUILDER
    options.put("usePolyAttribution", "true");
    options.put("useStrictMethodClashCheck", "true");
    options.put("useStructuralMostSpecificResolution", "true");
    options.put("useGraphInference", "true");

    String[] processedArgs;

    try {
      processedArgs = processPluginArgs(argv);
    } catch (InvalidCommandLineException e) {
      errOutput.println(e.getMessage());
      return Result.CMDERR;
    }

    setupBlazeJavaCompiler(context);
    return compile(processedArgs, context);
  }

  @VisibleForTesting
  public Result compile(String[] argv, Context context) {
    enableEndPositions(context);
    Result result = Result.ABNORMAL;
    try {
      result = new Main(compilerName, errOutput).compile(argv, context);
    } catch (PropagatedException e) {
      if (e.getCause() instanceof PluginException) {
        PluginException pluginException = (PluginException) e.getCause();
        errOutput.println(pluginException.getMessage());
        return pluginException.getResult();
      }
      e.printStackTrace(errOutput);
      result = Result.ABNORMAL;
    } finally {
      if (result.isOK()) {
        verifyNotNull(compiler);
        if (compiler.shouldStopPolicyIfNoError.isAfter(CompileState.FLOW)
            && compiler.flowEvents() == 0) {
          errOutput.println("Expected at least one FLOW event");
          result = Result.ABNORMAL;
        }
      }
    }
    return result;
  }

  // javac9 removes the ability to pass lists of {@link JavaFileObject}s or {@link Processors}s to
  // it's 'Main' class (i.e. the entry point for command-line javac). Having BlazeJavacMain
  // continue to call into javac's Main has the nice property that it keeps JavaBuilder's
  // behaviour closer to stock javac, but it makes it harder to write integration tests. This class
  // provides a compile method that accepts file objects and processors, but it isn't
  // guaranteed to behave exactly the same way as JavaBuilder does when used from the command-line.
  // TODO(cushon): either stop using Main and commit to using the the API for everything, or
  // re-write integration tests for JavaBuilder to use the real compile() method.
  @VisibleForTesting
  @Deprecated
  public Result compile(
      String[] argv,
      Context context,
      JavaFileManager fileManager,
      DiagnosticListener<? super JavaFileObject> diagnosticListener,
      List<JavaFileObject> javaFileObjects,
      Iterable<? extends Processor> processors) {

    JavacTool tool = JavacTool.create();
    JavacTaskImpl task = (JavacTaskImpl) tool.getTask(
        errOutput,
        fileManager,
        diagnosticListener,
        Arrays.asList(argv),
        null,
        javaFileObjects,
        context);
    if (processors != null) {
      task.setProcessors(processors);
    }

    try {
      return task.doCall();
    } catch (PluginException e) {
      errOutput.println(e.getMessage());
      return e.getResult();
    }
  }

  private static final TaskListener EMPTY_LISTENER = new TaskListener() {
    @Override public void started(TaskEvent e) {}
    @Override public void finished(TaskEvent e) {}
  };

  /**
   * Convinces javac to run in 'API mode', and collect end position information needed by
   * error-prone.
   */
  private static void enableEndPositions(Context context) {
    MultiTaskListener.instance(context).add(EMPTY_LISTENER);
  }

  /**
   * Processes Plugin-specific arguments and removes them from the args array.
   */
  @VisibleForTesting
  String[] processPluginArgs(String[] args) throws InvalidCommandLineException {
    List<String> processedArgs = Arrays.asList(args);
    for (BlazeJavaCompilerPlugin plugin : plugins) {
      processedArgs = plugin.processArgs(processedArgs);
    }
    return processedArgs.toArray(new String[processedArgs.size()]);
  }

  @VisibleForTesting
  BlazeJavaCompiler getCompiler() {
    return verifyNotNull(compiler);
  }
}