aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/java_tools/buildjar/java/com/google/devtools/build/buildjar/javac/BlazeJavaCompiler.java
blob: 665a8fcaf66a3b14f50a1f6f78643e5fc4445825 (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
// 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 com.google.common.base.Function;
import com.google.devtools.build.buildjar.javac.plugins.BlazeJavaCompilerPlugin;

import com.sun.tools.javac.comp.AttrContext;
import com.sun.tools.javac.comp.CompileStates.CompileState;
import com.sun.tools.javac.comp.Env;
import com.sun.tools.javac.main.JavaCompiler;
import com.sun.tools.javac.util.Context;

import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

import javax.annotation.Nullable;

/**
 * An extended version of the javac compiler, providing support for
 * composable static analyses via a plugin mechanism. BlazeJavaCompiler
 * keeps a list of plugins and calls callback methods in those plugins
 * after certain compiler phases. The plugins perform the actual static
 * analyses.
 */
public class BlazeJavaCompiler extends JavaCompiler {

  private int skippedFlowEvents = 0;
  private int flowEvents = 0;

  /**
   * A list of plugins to run at particular points in the compile
   */
  private final List<BlazeJavaCompilerPlugin> plugins = new ArrayList<>();

  private BlazeJavaCompiler(Context context, Iterable<BlazeJavaCompilerPlugin> plugins) {
    super(context);

    // initialize all plugins
    for (BlazeJavaCompilerPlugin plugin : plugins) {
      plugin.init(context, log, this);
      this.plugins.add(plugin);
    }
  }

  /**
   * Adds an initialization hook to the Context, such that requests for a
   * JavaCompiler (i.e., a lookup for 'compilerKey' of our superclass,
   * JavaCompiler) will actually construct and return BlazeJavaCompiler.
   *
   * This is the preferred way for extending behavior within javac,
   * per the documentation in {@link Context}.
   *
   * Prior to JDK-8038455 additional JavaCompilers were created for
   * annotation processing rounds, but we now expect a single
   * compiler instance per compilation. The factory is still seems
   * to be necessary to avoid context-ordering issues, but we
   * assert that the factory is only called once, and save the
   * output after its call for introspection.
   */
  public static void preRegister(
      final Context context,
      final Iterable<BlazeJavaCompilerPlugin> plugins,
      @Nullable final Function<BlazeJavaCompiler, Void> listener) {
    context.put(
        compilerKey,
        new Context.Factory<JavaCompiler>() {
          boolean first = true;

          @Override
          public JavaCompiler make(Context c) {
            if (!first) {
              throw new AssertionError("Expected a single creation of BlazeJavaCompiler.");
            }
            first = false;
            BlazeJavaCompiler compiler = new BlazeJavaCompiler(c, plugins);
            if (listener != null) {
              listener.apply(compiler);
            }
            return compiler;
          }
        });
  }

  public static void preRegister(
      final Context context, final Iterable<BlazeJavaCompilerPlugin> plugins) {
    preRegister(context, plugins, null);
  }

  @Override
  public Env<AttrContext> attribute(Env<AttrContext> env) {
    Env<AttrContext> result = super.attribute(env);
    // don't run plugins if there were compilation errors
    if (errorCount() > 0) {
      return result;
    }
    // Iterate over all plugins, calling their postAttribute methods
    for (BlazeJavaCompilerPlugin plugin : plugins) {
      plugin.postAttribute(result);
    }

    return result;
  }

  @Override
  protected void flow(Env<AttrContext> env, Queue<Env<AttrContext>> results) {
    boolean isDone = compileStates.isDone(env, CompileState.FLOW);
    super.flow(env, results);
    if (isDone) {
      return;
    }
    // don't run plugins if there were compilation errors
    if (errorCount() > 0) {
      skippedFlowEvents++;
      return;
    }
    flowEvents++;

    // Iterate over all plugins, calling their postFlow methods
    for (BlazeJavaCompilerPlugin plugin : plugins) {
      plugin.postFlow(env);
    }
  }

  @Override
  public void close() {
    for (BlazeJavaCompilerPlugin plugin : plugins) {
      plugin.finish();
    }
    plugins.clear();
    super.close();
  }

  /** The number of flow events that were skipped. */
  public int skippedFlowEvents() {
    return skippedFlowEvents;
  }

  /** The number of error-free flow events that were passed to plugins. */
  public int flowEvents() {
    return flowEvents;
  }

  /**
   * Testing purposes only.  Returns true if the collection of plugins in
   * this instance contains one of the provided type.
   */
  boolean pluginsContain(Class<? extends BlazeJavaCompilerPlugin> klass) {
    for (BlazeJavaCompilerPlugin plugin : plugins) {
      if (klass.isInstance(plugin)) {
        return true;
      }
    }
    return false;
  }
}