aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/main/java/com/google/devtools/build/lib/rules/java/JavaCompilationHelper.java
blob: 181dd12a61d1074f5670afea30f3e4731e322496 (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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
// Copyright 2014 Google Inc. 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.lib.rules.java;

import static com.google.devtools.build.lib.analysis.config.BuildConfiguration.StrictDepsMode.OFF;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.analysis.AnalysisUtils;
import com.google.devtools.build.lib.analysis.RuleContext;
import com.google.devtools.build.lib.analysis.TransitiveInfoCollection;
import com.google.devtools.build.lib.analysis.config.BuildConfiguration.StrictDepsMode;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder;
import com.google.devtools.build.lib.rules.java.JavaCompilationArgs.ClasspathType;
import com.google.devtools.build.lib.rules.java.JavaConfiguration.JavaClasspathMode;
import com.google.devtools.build.lib.vfs.FileSystemUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.annotation.Nullable;

/**
 * A helper class for compiling Java targets. It contains method to create the
 * various intermediate Artifacts for using ijars and source ijars.
 * <p>
 * Also supports the creation of resource and source only Jars.
 */
public class JavaCompilationHelper extends BaseJavaCompilationHelper {
  private Artifact outputDepsProtoArtifact;
  private JavaTargetAttributes.Builder attributes;
  private JavaTargetAttributes builtAttributes;
  private final ImmutableList<String> customJavacOpts;
  private final List<Artifact> translations = new ArrayList<>();
  private boolean translationsFrozen = false;
  private final JavaSemantics semantics;

  public JavaCompilationHelper(RuleContext ruleContext, JavaSemantics semantics,
      ImmutableList<String> javacOpts, JavaTargetAttributes.Builder attributes) {
    super(ruleContext);
    this.attributes = attributes;
    this.customJavacOpts = javacOpts;
    this.semantics = semantics;
  }

  public JavaCompilationHelper(RuleContext ruleContext, JavaSemantics semantics,
      JavaTargetAttributes.Builder attributes) {
    this(ruleContext, semantics, getDefaultJavacOptsFromRule(ruleContext), attributes);
  }

  public JavaTargetAttributes getAttributes() {
    if (builtAttributes == null) {
      builtAttributes = attributes.build();
    }
    return builtAttributes;
  }

  /**
   * Creates the Action that compiles Java source files.
   *
   * @param outputJar the class jar Artifact to create with the Action
   * @param gensrcOutputJar the generated sources jar Artifact to create with the Action
   *        (null if no sources will be generated).
   * @param outputDepsProto the compiler-generated jdeps file to create with the Action
   *        (null if not requested)
   * @param outputMetadata metadata file (null if no instrumentation is needed).
   */
  public void createCompileAction(Artifact outputJar, @Nullable Artifact gensrcOutputJar,
      @Nullable Artifact outputDepsProto, @Nullable Artifact outputMetadata) {
    JavaTargetAttributes attributes = getAttributes();
    List<String> javacOpts = getJavacOpts();
    JavaCompileAction.Builder builder = createJavaCompileActionBuilder(semantics);
    builder.setClasspathEntries(attributes.getCompileTimeClassPath());
    builder.addResources(attributes.getResources());
    builder.addClasspathResources(attributes.getClassPathResources());
    // Only add default bootclasspath entries if not explicitly set in attributes.
    if (!attributes.getBootClassPath().isEmpty()) {
      builder.setBootclasspathEntries(attributes.getBootClassPath());
    } else {
      builder.setBootclasspathEntries(getBootClasspath());
    }
    builder.setLangtoolsJar(getLangtoolsJar());
    builder.setJavaBuilderJar(getJavaBuilderJar());
    builder.addTranslations(getTranslations());
    builder.setOutputJar(outputJar);
    builder.setGensrcOutputJar(gensrcOutputJar);
    builder.setOutputDepsProto(outputDepsProto);
    builder.setMetadata(outputMetadata);
    builder.addSourceFiles(attributes.getSourceFiles());
    builder.addSourceJars(attributes.getSourceJars());
    builder.setJavacOpts(javacOpts);
    builder.setCompressJar(true);
    builder.setClassDirectory(outputDir(outputJar));
    builder.setSourceGenDirectory(sourceGenDir(outputJar));
    builder.setTempDirectory(tempDir(outputJar));
    builder.addProcessorPaths(attributes.getProcessorPath());
    builder.addProcessorNames(attributes.getProcessorNames());
    builder.setStrictJavaDeps(attributes.getStrictJavaDeps());
    builder.addDirectJars(attributes.getDirectJars());
    builder.addCompileTimeDependencyArtifacts(attributes.getCompileTimeDependencyArtifacts());
    builder.setRuleKind(attributes.getRuleKind());
    builder.setTargetLabel(attributes.getTargetLabel());
    getAnalysisEnvironment().registerAction(builder.build());
  }

  /**
   * Creates the Action that compiles Java source files and optionally instruments them for
   * coverage.
   *
   * @param outputJar the class jar Artifact to create with the Action
   * @param gensrcJar the generated sources jar Artifact to create with the Action
   * @param outputDepsProto the compiler-generated jdeps file to create with the Action
   * @param javaArtifactsBuilder the build to store the instrumentation metadata in
   */
  public void createCompileActionWithInstrumentation(Artifact outputJar, Artifact gensrcJar,
      Artifact outputDepsProto, JavaCompilationArtifacts.Builder javaArtifactsBuilder) {
    createCompileAction(outputJar, gensrcJar, outputDepsProto,
        createInstrumentationMetadata(outputJar, javaArtifactsBuilder));
  }

  /**
   * Creates the instrumentation metadata artifact if needed.
   *
   * @return the instrumentation metadata artifact or null if instrumentation is
   *         disabled
   */
  public Artifact createInstrumentationMetadata(Artifact outputJar,
      JavaCompilationArtifacts.Builder javaArtifactsBuilder) {
    // If we need to instrument the jar, add additional output (the coverage metadata file) to the
    // JavaCompileAction.
    Artifact instrumentationMetadata = null;
    if (shouldInstrumentJar()) {
      instrumentationMetadata = semantics.createInstrumentationMetadataArtifact(
          getAnalysisEnvironment(), outputJar);

      if (instrumentationMetadata != null) {
        javaArtifactsBuilder.addInstrumentationMetadata(instrumentationMetadata);
      }
    }
    return instrumentationMetadata;
  }

  private boolean shouldInstrumentJar() {
    // TODO(bazel-team): What about source jars?
    return getConfiguration().isCodeCoverageEnabled() && attributes.hasSourceFiles() &&
        getConfiguration().getInstrumentationFilter().isIncluded(
            getRuleContext().getLabel().toString());
  }

  /**
   * Returns the artifact for a jar file containing source files that were generated by an
   * annotation processor or null if no annotation processors are used.
   */
  public Artifact createGensrcJar(@Nullable Artifact outputJar) {
    if (!usesAnnotationProcessing()) {
      return null;
    }
    return getAnalysisEnvironment().getDerivedArtifact(
        FileSystemUtils.appendWithoutExtension(outputJar.getRootRelativePath(), "-gensrc"),
        outputJar.getRoot());
  }

  /**
   * Returns whether this target uses annotation processing.
   */
  private boolean usesAnnotationProcessing() {
    JavaTargetAttributes attributes = getAttributes();
    return getJavacOpts().contains("-processor") || !attributes.getProcessorNames().isEmpty();
  }

  public Artifact getOutputDepsProtoArtifact() {
    return outputDepsProtoArtifact;
  }
  /**
   * Creates the jdeps file artifact if needed. Returns null if the target can't emit dependency
   * information (i.e there is no compilation step, the target acts as an alias).
   *
   * @param outputJar output jar artifact used to derive the name
   * @return the jdeps file artifact or null if the target can't generate such a file
   */
  public Artifact createOutputDepsProtoArtifact(Artifact outputJar,
      JavaCompilationArtifacts.Builder builder) {
    if (!generatesOutputDeps()) {
      return null;
    }

    outputDepsProtoArtifact = getAnalysisEnvironment().getDerivedArtifact(
          FileSystemUtils.replaceExtension(outputJar.getRootRelativePath(), ".jdeps"),
          outputJar.getRoot());

    builder.setRunTimeDependencies(outputDepsProtoArtifact);
    return outputDepsProtoArtifact;
  }

  /**
   * Returns whether this target emits dependency information. Compilation must occur, so certain
   * targets acting as aliases have to be filtered out.
   */
  private boolean generatesOutputDeps() {
    return getJavaConfiguration().getGenerateJavaDeps() &&
        (attributes.hasSourceFiles() || attributes.hasSourceJars());
  }

  /**
   * Creates an Action that packages all of the resources into a Jar. This
   * includes the declared resources, the classpath resources and the translated
   * messages.
   *
   * <p>The resource jar artifact is derived from the given original jar, by
   * prepending the given prefix and appending the given suffix. The new jar
   * uses the same root as the original jar.
   */
  // TODO(bazel-team): Extract this method to make it easier to create simple
  // zip/jar archives without having to first create a JavaCompilationhelper and
  // JavaTargetAttributes.
  public Artifact createResourceJarAction(Artifact resourceJar) {
    JavaTargetAttributes attributes = getAttributes();
    JavaCompileAction.Builder builder = createJavaCompileActionBuilder(semantics);
    builder.setOutputJar(resourceJar);
    builder.addResources(attributes.getResources());
    builder.addClasspathResources(attributes.getClassPathResources());
    builder.setLangtoolsJar(getLangtoolsJar());
    builder.addTranslations(getTranslations());
    builder.setCompressJar(true);
    builder.setClassDirectory(outputDir(resourceJar));
    builder.setTempDirectory(tempDir(resourceJar));
    builder.setJavaBuilderJar(getJavaBuilderJar());
    getAnalysisEnvironment().registerAction(builder.build());
    return resourceJar;
  }

  /**
   * Creates an Action that packages the Java source files into a Jar.  If {@code gensrcJar} is
   * non-null, includes the contents of the {@code gensrcJar} with the output source jar.
   *
   * @param outputJar the Artifact to create with the Action
   * @param gensrcJar the generated sources jar Artifact that should be included with the
   *        sources in the output Artifact.  May be null.
   */
  public void createSourceJarAction(Artifact outputJar, @Nullable Artifact gensrcJar) {
    JavaTargetAttributes attributes = getAttributes();
    Collection<Artifact> resourceJars = new ArrayList<>(attributes.getSourceJars());
    if (gensrcJar != null) {
      resourceJars.add(gensrcJar);
    }
    createSourceJarAction(semantics, attributes.getSourceFiles(), resourceJars, outputJar);
  }

  /**
   * Creates the actions that produce the interface jar. Adds the jar artifacts to the given
   * JavaCompilationArtifacts builder.
   */
  public void createCompileTimeJarAction(Artifact runtimeJar,
      @Nullable Artifact runtimeDeps, JavaCompilationArtifacts.Builder builder) {
    Artifact jar = getJavaConfiguration().getUseIjars()
        ? createIjarAction(runtimeJar, false)
        : runtimeJar;
    Artifact deps = runtimeDeps;

    builder.addCompileTimeJar(jar);
    builder.setCompileTimeDependencies(deps);
  }

  /**
   * Creates actions that create ijars from generated jars that are an input to
   * the Java target.
   *
   * @return the generated ijars or original jars that are not generated by a
   *         genrule
   */
  public Iterable<Artifact> filterGeneratedJarsThroughIjar(Iterable<Artifact> jars) {
    if (!getJavaConfiguration().getUseIjars()) {
      return jars;
    }
    // We need to copy this list in order to avoid generating a new action each time the iterator
    // is enumerated
    return ImmutableList.copyOf(Iterables.transform(jars, new Function<Artifact, Artifact>() {
      @Override
      public Artifact apply(Artifact jar) {
        return !jar.isSourceArtifact() ? createIjarAction(jar, true) : jar;
      }
    }));
  }

  private void addArgsAndJarsToAttributes(JavaCompilationArgs args, Iterable<Artifact> directJars) {
    // Can only be non-null when isStrict() returns true.
    if (directJars != null) {
      attributes.addDirectCompileTimeClassPathEntries(directJars);
      attributes.addDirectJars(directJars);
    }

    attributes.merge(args);
  }

  private void addLibrariesToAttributesInternal(Iterable<? extends TransitiveInfoCollection> deps) {
    JavaCompilationArgs args = JavaCompilationArgs.builder()
        .addTransitiveTargets(deps).build();

    NestedSet<Artifact> directJars = isStrict()
        ? getNonRecursiveCompileTimeJarsFromCollection(deps)
        : null;
    addArgsAndJarsToAttributes(args, directJars);
  }

  private void addProvidersToAttributesInternal(
      Iterable<? extends SourcesJavaCompilationArgsProvider> deps, boolean isNeverLink) {
    JavaCompilationArgs args = JavaCompilationArgs.builder()
        .addSourcesTransitiveCompilationArgs(deps, true,
            isNeverLink ? ClasspathType.COMPILE_ONLY : ClasspathType.BOTH)
        .build();

    NestedSet<Artifact> directJars = isStrict()
        ? getNonRecursiveCompileTimeJarsFromProvider(deps, isNeverLink)
        : null;
    addArgsAndJarsToAttributes(args, directJars);
  }

  private boolean isStrict() {
    return getStrictJavaDeps() != OFF;
  }

  private NestedSet<Artifact> getNonRecursiveCompileTimeJarsFromCollection(
      Iterable<? extends TransitiveInfoCollection> deps) {
    JavaCompilationArgs.Builder builder = JavaCompilationArgs.builder();
    builder.addTransitiveTargets(deps, /*recursive=*/false);
    return builder.build().getCompileTimeJars();
  }

  private NestedSet<Artifact> getNonRecursiveCompileTimeJarsFromProvider(
      Iterable<? extends SourcesJavaCompilationArgsProvider> deps, boolean isNeverLink) {
    return JavaCompilationArgs.builder()
        .addSourcesTransitiveCompilationArgs(deps, false,
            isNeverLink ? ClasspathType.COMPILE_ONLY : ClasspathType.BOTH)
        .build().getCompileTimeJars();
  }

  private void addDependencyArtifactsToAttributes(
      Iterable<? extends TransitiveInfoCollection> deps) {
    NestedSetBuilder<Artifact> compileTimeBuilder = NestedSetBuilder.stableOrder();
    NestedSetBuilder<Artifact> runTimeBuilder = NestedSetBuilder.stableOrder();
    for (JavaCompilationArgsProvider provider : AnalysisUtils.getProviders(
        deps, JavaCompilationArgsProvider.class)) {
      compileTimeBuilder.addTransitive(provider.getCompileTimeJavaDependencyArtifacts());
      runTimeBuilder.addTransitive(provider.getRunTimeJavaDependencyArtifacts());
    }
    attributes.addCompileTimeDependencyArtifacts(compileTimeBuilder.build());
    attributes.addRuntimeDependencyArtifacts(runTimeBuilder.build());
  }

  /**
   * Adds the compile time and runtime Java libraries in the transitive closure
   * of the deps to the attributes.
   *
   * @param deps the dependencies to be included as roots of the transitive
   *        closure
   */
  public void addLibrariesToAttributes(Iterable<? extends TransitiveInfoCollection> deps) {
    // Enforcing strict Java dependencies: when the --strict_java_deps flag is
    // WARN or ERROR, or is DEFAULT and strict_java_deps attribute is unset,
    // we use a stricter javac compiler to perform direct deps checks.
    attributes.setStrictJavaDeps(getStrictJavaDeps());
    addLibrariesToAttributesInternal(deps);

    JavaClasspathMode classpathMode = getJavaConfiguration().getReduceJavaClasspath();
    if (isStrict() && classpathMode != JavaClasspathMode.OFF) {
      addDependencyArtifactsToAttributes(deps);
    }
  }

  public void addProvidersToAttributes(Iterable<? extends SourcesJavaCompilationArgsProvider> deps,
      boolean isNeverLink) {
    // see addLibrariesToAttributes() for explanation
    attributes.setStrictJavaDeps(getStrictJavaDeps());
    addProvidersToAttributesInternal(deps, isNeverLink);
  }

  /**
   * Determines whether to enable strict_java_deps.
   *
   * @return filtered command line flag value, defaulting to ERROR
   */
  public StrictDepsMode getStrictJavaDeps() {
    return getJavaConfiguration().getFilteredStrictJavaDeps();
  }

  /**
   * Gets the value of the "javacopts" attribute combining them with the
   * default options. If the current rule has no javacopts attribute, this
   * method only returns the default options.
   */
  @VisibleForTesting
  ImmutableList<String> getJavacOpts() {
    return customJavacOpts;
  }

  /**
   * Obtains the standard list of javac opts needed to build {@code rule}.
   *
   * This method must only be called during initialization.
   *
   * @param ruleContext a rule context
   * @return a list of options to provide to javac
   */
  private static ImmutableList<String> getDefaultJavacOptsFromRule(RuleContext ruleContext) {
    return ImmutableList.copyOf(Iterables.concat(
        JavaToolchainProvider.getDefaultJavacOptions(ruleContext),
        ruleContext.getTokenizedStringListAttr("javacopts")));
  }

  public void addTranslations(Collection<Artifact> translations) {
    Preconditions.checkArgument(!translationsFrozen);
    this.translations.addAll(translations);
  }

  private ImmutableList<Artifact> getTranslations() {
    translationsFrozen = true;
    return ImmutableList.copyOf(translations);
  }
}