Search in sources :

Example 6 with NestedSetBuilder

use of com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder in project bazel by bazelbuild.

the class JavaBinary method create.

@Override
public ConfiguredTarget create(RuleContext ruleContext) throws InterruptedException, RuleErrorException {
    final JavaCommon common = new JavaCommon(ruleContext, semantics);
    DeployArchiveBuilder deployArchiveBuilder = new DeployArchiveBuilder(semantics, ruleContext);
    Runfiles.Builder runfilesBuilder = new Runfiles.Builder(ruleContext.getWorkspaceName(), ruleContext.getConfiguration().legacyExternalRunfiles());
    List<String> jvmFlags = new ArrayList<>();
    JavaTargetAttributes.Builder attributesBuilder = common.initCommon();
    attributesBuilder.addClassPathResources(ruleContext.getPrerequisiteArtifacts("classpath_resources", Mode.TARGET).list());
    // Add Java8 timezone resource data
    addTimezoneResourceForJavaBinaries(ruleContext, attributesBuilder);
    List<String> userJvmFlags = JavaCommon.getJvmFlags(ruleContext);
    ruleContext.checkSrcsSamePackage(true);
    boolean createExecutable = ruleContext.attributes().get("create_executable", Type.BOOLEAN);
    if (!createExecutable) {
        // TODO(cushon): disallow combining launcher=JDK_LAUNCHER_LABEL with create_executable=0
        // and use isAttributeExplicitlySpecified here
        Label launcherAttribute = ruleContext.attributes().get("launcher", BuildType.LABEL);
        if (launcherAttribute != null && !JavaHelper.isJdkLauncher(ruleContext, launcherAttribute)) {
            ruleContext.ruleError("launcher specified but create_executable is false");
        }
    }
    semantics.checkRule(ruleContext, common);
    semantics.checkForProtoLibraryAndJavaProtoLibraryOnSameProto(ruleContext, common);
    String mainClass = semantics.getMainClass(ruleContext, common.getSrcsArtifacts());
    String originalMainClass = mainClass;
    if (ruleContext.hasErrors()) {
        return null;
    }
    // Collect the transitive dependencies.
    JavaCompilationHelper helper = new JavaCompilationHelper(ruleContext, semantics, common.getJavacOpts(), attributesBuilder);
    List<TransitiveInfoCollection> deps = // Do not remove <TransitiveInfoCollection>: workaround for Java 7 type inference.
    Lists.<TransitiveInfoCollection>newArrayList(common.targetsTreatedAsDeps(ClasspathType.COMPILE_ONLY));
    helper.addLibrariesToAttributes(deps);
    attributesBuilder.addNativeLibraries(collectNativeLibraries(common.targetsTreatedAsDeps(ClasspathType.BOTH)));
    // deploy_env is valid for java_binary, but not for java_test.
    if (ruleContext.getRule().isAttrDefined("deploy_env", BuildType.LABEL_LIST)) {
        for (JavaRuntimeClasspathProvider envTarget : ruleContext.getPrerequisites("deploy_env", Mode.TARGET, JavaRuntimeClasspathProvider.class)) {
            attributesBuilder.addExcludedArtifacts(envTarget.getRuntimeClasspath());
        }
    }
    Artifact srcJar = ruleContext.getImplicitOutputArtifact(JavaSemantics.JAVA_BINARY_SOURCE_JAR);
    JavaSourceJarsProvider.Builder javaSourceJarsProviderBuilder = JavaSourceJarsProvider.builder().addSourceJar(srcJar).addAllTransitiveSourceJars(common.collectTransitiveSourceJars(srcJar));
    Artifact classJar = ruleContext.getImplicitOutputArtifact(JavaSemantics.JAVA_BINARY_CLASS_JAR);
    JavaRuleOutputJarsProvider.Builder ruleOutputJarsProviderBuilder = JavaRuleOutputJarsProvider.builder().addOutputJar(classJar, null, /* iJar */
    ImmutableList.of(srcJar));
    CppConfiguration cppConfiguration = ruleContext.getConfiguration().getFragment(CppConfiguration.class);
    boolean stripAsDefault = cppConfiguration.useFission() && cppConfiguration.getCompilationMode() == CompilationMode.OPT;
    Artifact launcher = semantics.getLauncher(ruleContext, common, deployArchiveBuilder, runfilesBuilder, jvmFlags, attributesBuilder, stripAsDefault);
    DeployArchiveBuilder unstrippedDeployArchiveBuilder = null;
    Artifact unstrippedLauncher = null;
    if (stripAsDefault) {
        unstrippedDeployArchiveBuilder = new DeployArchiveBuilder(semantics, ruleContext);
        unstrippedLauncher = semantics.getLauncher(ruleContext, common, unstrippedDeployArchiveBuilder, runfilesBuilder, jvmFlags, attributesBuilder, false);
    }
    JavaCompilationArtifacts.Builder javaArtifactsBuilder = new JavaCompilationArtifacts.Builder();
    Artifact instrumentationMetadata = helper.createInstrumentationMetadata(classJar, javaArtifactsBuilder);
    NestedSetBuilder<Artifact> filesBuilder = NestedSetBuilder.stableOrder();
    Artifact executableForRunfiles = null;
    if (createExecutable) {
        // This artifact is named as the rule itself, e.g. //foo:bar_bin -> bazel-bin/foo/bar_bin
        executableForRunfiles = ruleContext.createOutputArtifact();
        filesBuilder.add(classJar).add(executableForRunfiles);
        if (ruleContext.getConfiguration().isCodeCoverageEnabled()) {
            mainClass = semantics.addCoverageSupport(helper, attributesBuilder, executableForRunfiles, instrumentationMetadata, javaArtifactsBuilder, mainClass);
        }
    } else {
        filesBuilder.add(classJar);
    }
    JavaTargetAttributes attributes = helper.getAttributes();
    List<Artifact> nativeLibraries = attributes.getNativeLibraries();
    if (!nativeLibraries.isEmpty()) {
        jvmFlags.add("-Djava.library.path=" + JavaCommon.javaLibraryPath(nativeLibraries, ruleContext.getRule().getPackage().getWorkspaceName()));
    }
    JavaConfiguration javaConfig = ruleContext.getFragment(JavaConfiguration.class);
    if (attributes.hasMessages()) {
        helper.setTranslations(semantics.translate(ruleContext, javaConfig, attributes.getMessages()));
    }
    if (attributes.hasSourceFiles() || attributes.hasSourceJars() || attributes.hasResources() || attributes.hasClassPathResources()) {
        // We only want to add a jar to the classpath of a dependent rule if it has content.
        javaArtifactsBuilder.addRuntimeJar(classJar);
    }
    GeneratedExtensionRegistryProvider generatedExtensionRegistryProvider = semantics.createGeneratedExtensionRegistry(ruleContext, common, filesBuilder, javaArtifactsBuilder, ruleOutputJarsProviderBuilder, javaSourceJarsProviderBuilder);
    Artifact outputDepsProto = helper.createOutputDepsProtoArtifact(classJar, javaArtifactsBuilder);
    ruleOutputJarsProviderBuilder.setJdeps(outputDepsProto);
    JavaCompilationArtifacts javaArtifacts = javaArtifactsBuilder.build();
    common.setJavaCompilationArtifacts(javaArtifacts);
    Artifact manifestProtoOutput = helper.createManifestProtoOutput(classJar);
    // The gensrc jar is created only if the target uses annotation processing. Otherwise,
    // it is null, and the source jar action will not depend on the compile action.
    Artifact genSourceJar = null;
    Artifact genClassJar = null;
    if (helper.usesAnnotationProcessing()) {
        genClassJar = helper.createGenJar(classJar);
        genSourceJar = helper.createGensrcJar(classJar);
        helper.createGenJarAction(classJar, manifestProtoOutput, genClassJar);
    }
    helper.createCompileAction(classJar, manifestProtoOutput, genSourceJar, outputDepsProto, instrumentationMetadata);
    helper.createSourceJarAction(srcJar, genSourceJar);
    common.setClassPathFragment(new ClasspathConfiguredFragment(javaArtifacts, attributes, false, helper.getBootclasspathOrDefault()));
    // Collect the action inputs for the runfiles collector here because we need to access the
    // analysis environment, and that may no longer be safe when the runfiles collector runs.
    Iterable<Artifact> dynamicRuntimeActionInputs = CppHelper.getToolchain(ruleContext, ":cc_toolchain").getDynamicRuntimeLinkInputs();
    Iterables.addAll(jvmFlags, semantics.getJvmFlags(ruleContext, common.getSrcsArtifacts(), userJvmFlags));
    if (ruleContext.hasErrors()) {
        return null;
    }
    Artifact executableToRun = executableForRunfiles;
    if (createExecutable) {
        // Create a shell stub for a Java application
        executableToRun = semantics.createStubAction(ruleContext, common, jvmFlags, executableForRunfiles, mainClass, JavaCommon.getJavaBinSubstitution(ruleContext, launcher));
        if (!executableToRun.equals(executableForRunfiles)) {
            filesBuilder.add(executableToRun);
            runfilesBuilder.addArtifact(executableToRun);
        }
    }
    JavaSourceJarsProvider sourceJarsProvider = javaSourceJarsProviderBuilder.build();
    NestedSet<Artifact> transitiveSourceJars = sourceJarsProvider.getTransitiveSourceJars();
    // TODO(bazel-team): if (getOptions().sourceJars) then make this a dummy prerequisite for the
    // DeployArchiveAction ? Needs a few changes there as we can't pass inputs
    SingleJarActionBuilder.createSourceJarAction(ruleContext, ImmutableMap.<PathFragment, Artifact>of(), transitiveSourceJars.toCollection(), ruleContext.getImplicitOutputArtifact(JavaSemantics.JAVA_BINARY_DEPLOY_SOURCE_JAR));
    RuleConfiguredTargetBuilder builder = new RuleConfiguredTargetBuilder(ruleContext);
    builder.add(JavaPrimaryClassProvider.class, new JavaPrimaryClassProvider(semantics.getPrimaryClass(ruleContext, common.getSrcsArtifacts())));
    semantics.addProviders(ruleContext, common, jvmFlags, classJar, srcJar, genClassJar, genSourceJar, ImmutableMap.<Artifact, Artifact>of(), filesBuilder, builder);
    if (generatedExtensionRegistryProvider != null) {
        builder.add(GeneratedExtensionRegistryProvider.class, generatedExtensionRegistryProvider);
    }
    Artifact deployJar = ruleContext.getImplicitOutputArtifact(JavaSemantics.JAVA_BINARY_DEPLOY_JAR);
    boolean runProguard = applyProguardIfRequested(ruleContext, deployJar, common.getBootClasspath(), mainClass, semantics, filesBuilder);
    if (javaConfig.isEnforceOneVersion()) {
        Artifact oneVersionOutput = ruleContext.getAnalysisEnvironment().getDerivedArtifact(replaceExtension(classJar.getRootRelativePath(), "-one-version.txt"), classJar.getRoot());
        filesBuilder.add(oneVersionOutput);
        NestedSet<Artifact> transitiveDependencies = NestedSetBuilder.fromNestedSet(attributes.getRuntimeClassPath()).add(classJar).build();
        OneVersionCheckActionBuilder.build(ruleContext, transitiveDependencies, oneVersionOutput);
    }
    NestedSet<Artifact> filesToBuild = filesBuilder.build();
    // Need not include normal runtime classpath in runfiles if Proguard is used because _deploy.jar
    // is used as classpath instead.  Keeping runfiles unchanged has however the advantage that
    // manually running executable without --singlejar works (although it won't depend on Proguard).
    collectDefaultRunfiles(runfilesBuilder, ruleContext, common, javaArtifacts, filesToBuild, launcher, dynamicRuntimeActionInputs);
    Runfiles defaultRunfiles = runfilesBuilder.build();
    RunfilesSupport runfilesSupport = null;
    if (createExecutable) {
        List<String> extraArgs = new ArrayList<>(semantics.getExtraArguments(ruleContext, common.getSrcsArtifacts()));
        if (runProguard) {
            // Instead of changing the classpath written into the wrapper script, pass --singlejar when
            // running the script (which causes the deploy.jar written by Proguard to be used instead of
            // the normal classpath). It's a bit odd to do this b/c manually running the script wouldn't
            // use Proguard's output unless --singlejar is explicitly supplied.  On the other hand the
            // behavior of the script is more consistent: the (proguarded) deploy.jar is only used with
            // --singlejar.  Moreover, people will almost always run tests using blaze test, which does
            // use Proguard's output thanks to this extra arg when enabled.  Also, it's actually hard to
            // get the classpath changed in the wrapper script (would require calling
            // JavaCommon.setClasspathFragment with a new fragment at the *end* of this method because
            // the classpath is evaluated lazily when generating the wrapper script) and the wrapper
            // script would essentially have an if (--singlejar was set), set classpath to deploy jar,
            // otherwise, set classpath to deploy jar.
            extraArgs.add("--wrapper_script_flag=--singlejar");
        }
        // The executable we pass here will be used when creating the runfiles directory. E.g. for the
        // stub script called bazel-bin/foo/bar_bin, the runfiles directory will be created under
        // bazel-bin/foo/bar_bin.runfiles . On platforms where there's an extra stub script (Windows)
        // which dispatches to this one, we still create the runfiles directory for the shell script,
        // but use the dispatcher script (a batch file) as the RunfilesProvider's executable.
        runfilesSupport = RunfilesSupport.withExecutable(ruleContext, defaultRunfiles, executableForRunfiles, extraArgs);
    }
    RunfilesProvider runfilesProvider = RunfilesProvider.withData(defaultRunfiles, new Runfiles.Builder(ruleContext.getWorkspaceName(), ruleContext.getConfiguration().legacyExternalRunfiles()).merge(runfilesSupport).build());
    ImmutableList<String> deployManifestLines = getDeployManifestLines(ruleContext, originalMainClass);
    // When running Proguard:
    // (1) write single jar to intermediate destination; Proguard will write _deploy.jar file
    // (2) Don't depend on runfiles to avoid circular dependency, since _deploy.jar is itself part
    //     of runfiles when Proguard runs (because executable then needs it) and _deploy.jar depends
    //     on this single jar.
    // (3) Don't bother with compression since Proguard will write the final jar anyways
    deployArchiveBuilder.setOutputJar(runProguard ? ruleContext.getImplicitOutputArtifact(JavaSemantics.JAVA_BINARY_MERGED_JAR) : deployJar).setJavaStartClass(mainClass).setDeployManifestLines(deployManifestLines).setAttributes(attributes).addRuntimeJars(javaArtifacts.getRuntimeJars()).setIncludeBuildData(true).setRunfilesMiddleman(runProguard || runfilesSupport == null ? null : runfilesSupport.getRunfilesMiddleman()).setCompression(runProguard ? UNCOMPRESSED : COMPRESSED).setLauncher(launcher).build();
    Artifact unstrippedDeployJar = ruleContext.getImplicitOutputArtifact(JavaSemantics.JAVA_UNSTRIPPED_BINARY_DEPLOY_JAR);
    if (stripAsDefault) {
        unstrippedDeployArchiveBuilder.setOutputJar(unstrippedDeployJar).setJavaStartClass(mainClass).setDeployManifestLines(deployManifestLines).setAttributes(attributes).addRuntimeJars(javaArtifacts.getRuntimeJars()).setIncludeBuildData(true).setRunfilesMiddleman(runfilesSupport == null ? null : runfilesSupport.getRunfilesMiddleman()).setCompression(COMPRESSED).setLauncher(unstrippedLauncher);
        unstrippedDeployArchiveBuilder.build();
    } else {
        // Write an empty file as the name_deploy.jar.unstripped when the default output jar is not
        // stripped.
        ruleContext.registerAction(FileWriteAction.create(ruleContext, unstrippedDeployJar, "", false));
    }
    JavaRuleOutputJarsProvider ruleOutputJarsProvider = ruleOutputJarsProviderBuilder.build();
    JavaSkylarkApiProvider.Builder skylarkApiProvider = JavaSkylarkApiProvider.builder().setRuleOutputJarsProvider(ruleOutputJarsProvider).setSourceJarsProvider(sourceJarsProvider);
    common.addTransitiveInfoProviders(builder, skylarkApiProvider, filesToBuild, classJar);
    common.addGenJarsProvider(builder, skylarkApiProvider, genClassJar, genSourceJar);
    return builder.setFilesToBuild(filesToBuild).addSkylarkTransitiveInfo(JavaSkylarkApiProvider.NAME, skylarkApiProvider.build()).add(JavaRuleOutputJarsProvider.class, ruleOutputJarsProvider).add(RunfilesProvider.class, runfilesProvider).setRunfilesSupport(runfilesSupport, executableToRun).add(JavaRuntimeClasspathProvider.class, new JavaRuntimeClasspathProvider(common.getRuntimeClasspath())).add(JavaSourceInfoProvider.class, JavaSourceInfoProvider.fromJavaTargetAttributes(attributes, semantics)).add(JavaSourceJarsProvider.class, sourceJarsProvider).addOutputGroup(JavaSemantics.SOURCE_JARS_OUTPUT_GROUP, transitiveSourceJars).build();
}
Also used : NestedSetBuilder(com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder) RuleConfiguredTargetBuilder(com.google.devtools.build.lib.analysis.RuleConfiguredTargetBuilder) ArrayList(java.util.ArrayList) Label(com.google.devtools.build.lib.cmdline.Label) RunfilesSupport(com.google.devtools.build.lib.analysis.RunfilesSupport) RunfilesProvider(com.google.devtools.build.lib.analysis.RunfilesProvider) Artifact(com.google.devtools.build.lib.actions.Artifact) Runfiles(com.google.devtools.build.lib.analysis.Runfiles) CppConfiguration(com.google.devtools.build.lib.rules.cpp.CppConfiguration) GeneratedExtensionRegistryProvider(com.google.devtools.build.lib.rules.java.proto.GeneratedExtensionRegistryProvider) RuleConfiguredTargetBuilder(com.google.devtools.build.lib.analysis.RuleConfiguredTargetBuilder) TransitiveInfoCollection(com.google.devtools.build.lib.analysis.TransitiveInfoCollection)

Example 7 with NestedSetBuilder

use of com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder in project bazel by bazelbuild.

the class JavaImport method create.

@Override
public ConfiguredTarget create(RuleContext ruleContext) throws InterruptedException, RuleErrorException {
    ImmutableList<Artifact> srcJars = ImmutableList.of();
    ImmutableList<Artifact> jars = collectJars(ruleContext);
    Artifact srcJar = ruleContext.getPrerequisiteArtifact("srcjar", Mode.TARGET);
    if (ruleContext.hasErrors()) {
        return null;
    }
    ImmutableList<TransitiveInfoCollection> targets = ImmutableList.<TransitiveInfoCollection>builder().addAll(ruleContext.getPrerequisites("deps", Mode.TARGET)).addAll(ruleContext.getPrerequisites("exports", Mode.TARGET)).build();
    final JavaCommon common = new JavaCommon(ruleContext, semantics, /*srcs=*/
    ImmutableList.<Artifact>of(), targets, targets, targets);
    semantics.checkRule(ruleContext, common);
    // No need for javac options - no compilation happening here.
    ImmutableBiMap.Builder<Artifact, Artifact> compilationToRuntimeJarMapBuilder = ImmutableBiMap.builder();
    ImmutableList<Artifact> interfaceJars = processWithIjar(jars, ruleContext, compilationToRuntimeJarMapBuilder);
    JavaCompilationArtifacts javaArtifacts = collectJavaArtifacts(jars, interfaceJars);
    common.setJavaCompilationArtifacts(javaArtifacts);
    CppCompilationContext transitiveCppDeps = common.collectTransitiveCppDeps();
    NestedSet<LinkerInput> transitiveJavaNativeLibraries = common.collectTransitiveJavaNativeLibraries();
    boolean neverLink = JavaCommon.isNeverLink(ruleContext);
    JavaCompilationArgs javaCompilationArgs = common.collectJavaCompilationArgs(false, neverLink, false);
    JavaCompilationArgs recursiveJavaCompilationArgs = common.collectJavaCompilationArgs(true, neverLink, false);
    NestedSet<Artifact> transitiveJavaSourceJars = collectTransitiveJavaSourceJars(ruleContext, srcJar);
    if (srcJar != null) {
        srcJars = ImmutableList.of(srcJar);
    }
    // The "neverlink" attribute is transitive, so if it is enabled, we don't add any
    // runfiles from this target or its dependencies.
    Runfiles runfiles = neverLink ? Runfiles.EMPTY : new Runfiles.Builder(ruleContext.getWorkspaceName(), ruleContext.getConfiguration().legacyExternalRunfiles()).addArtifacts(javaArtifacts.getRuntimeJars()).addTargets(targets, RunfilesProvider.DEFAULT_RUNFILES).addRunfiles(ruleContext, RunfilesProvider.DEFAULT_RUNFILES).addTargets(targets, JavaRunfilesProvider.TO_RUNFILES).add(ruleContext, JavaRunfilesProvider.TO_RUNFILES).build();
    CcLinkParamsStore ccLinkParamsStore = new CcLinkParamsStore() {

        @Override
        protected void collect(CcLinkParams.Builder builder, boolean linkingStatically, boolean linkShared) {
            builder.addTransitiveTargets(common.targetsTreatedAsDeps(ClasspathType.BOTH), JavaCcLinkParamsProvider.TO_LINK_PARAMS, CcLinkParamsProvider.TO_LINK_PARAMS);
        }
    };
    RuleConfiguredTargetBuilder ruleBuilder = new RuleConfiguredTargetBuilder(ruleContext);
    NestedSetBuilder<Artifact> filesBuilder = NestedSetBuilder.stableOrder();
    filesBuilder.addAll(jars);
    ImmutableBiMap<Artifact, Artifact> compilationToRuntimeJarMap = compilationToRuntimeJarMapBuilder.build();
    semantics.addProviders(ruleContext, common, ImmutableList.<String>of(), null, /* classJar */
    srcJar, /* srcJar */
    null, /* genJar */
    null, /* gensrcJar */
    compilationToRuntimeJarMap, filesBuilder, ruleBuilder);
    NestedSet<Artifact> filesToBuild = filesBuilder.build();
    JavaSourceInfoProvider javaSourceInfoProvider = new JavaSourceInfoProvider.Builder().setJarFiles(jars).setSourceJarsForJarFiles(srcJars).build();
    JavaRuleOutputJarsProvider.Builder ruleOutputJarsProviderBuilder = JavaRuleOutputJarsProvider.builder();
    for (Artifact jar : jars) {
        ruleOutputJarsProviderBuilder.addOutputJar(jar, compilationToRuntimeJarMap.inverse().get(jar), srcJars);
    }
    NestedSet<Artifact> proguardSpecs = new ProguardLibrary(ruleContext).collectProguardSpecs();
    JavaRuleOutputJarsProvider ruleOutputJarsProvider = ruleOutputJarsProviderBuilder.build();
    JavaSourceJarsProvider sourceJarsProvider = JavaSourceJarsProvider.create(transitiveJavaSourceJars, srcJars);
    JavaCompilationArgsProvider compilationArgsProvider = JavaCompilationArgsProvider.create(javaCompilationArgs, recursiveJavaCompilationArgs);
    JavaSkylarkApiProvider.Builder skylarkApiProvider = JavaSkylarkApiProvider.builder().setRuleOutputJarsProvider(ruleOutputJarsProvider).setSourceJarsProvider(sourceJarsProvider).setCompilationArgsProvider(compilationArgsProvider);
    common.addTransitiveInfoProviders(ruleBuilder, skylarkApiProvider, filesToBuild, null);
    return ruleBuilder.setFilesToBuild(filesToBuild).addSkylarkTransitiveInfo(JavaSkylarkApiProvider.NAME, skylarkApiProvider.build()).add(JavaRuleOutputJarsProvider.class, ruleOutputJarsProvider).add(JavaRuntimeJarProvider.class, new JavaRuntimeJarProvider(javaArtifacts.getRuntimeJars())).add(JavaNeverlinkInfoProvider.class, new JavaNeverlinkInfoProvider(neverLink)).add(RunfilesProvider.class, RunfilesProvider.simple(runfiles)).add(CcLinkParamsProvider.class, new CcLinkParamsProvider(ccLinkParamsStore)).add(JavaCompilationArgsProvider.class, compilationArgsProvider).add(JavaNativeLibraryProvider.class, new JavaNativeLibraryProvider(transitiveJavaNativeLibraries)).add(CppCompilationContext.class, transitiveCppDeps).add(JavaSourceInfoProvider.class, javaSourceInfoProvider).add(JavaSourceJarsProvider.class, sourceJarsProvider).add(ProguardSpecProvider.class, new ProguardSpecProvider(proguardSpecs)).addOutputGroup(JavaSemantics.SOURCE_JARS_OUTPUT_GROUP, transitiveJavaSourceJars).addOutputGroup(OutputGroupProvider.HIDDEN_TOP_LEVEL, proguardSpecs).build();
}
Also used : NestedSetBuilder(com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder) RuleConfiguredTargetBuilder(com.google.devtools.build.lib.analysis.RuleConfiguredTargetBuilder) CcLinkParamsProvider(com.google.devtools.build.lib.rules.cpp.CcLinkParamsProvider) LinkerInput(com.google.devtools.build.lib.rules.cpp.LinkerInput) CcLinkParamsStore(com.google.devtools.build.lib.rules.cpp.CcLinkParamsStore) Artifact(com.google.devtools.build.lib.actions.Artifact) Runfiles(com.google.devtools.build.lib.analysis.Runfiles) ImmutableBiMap(com.google.common.collect.ImmutableBiMap) CppCompilationContext(com.google.devtools.build.lib.rules.cpp.CppCompilationContext) RuleConfiguredTargetBuilder(com.google.devtools.build.lib.analysis.RuleConfiguredTargetBuilder) TransitiveInfoCollection(com.google.devtools.build.lib.analysis.TransitiveInfoCollection)

Example 8 with NestedSetBuilder

use of com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder in project bazel by bazelbuild.

the class JavaLibrary method init.

public RuleConfiguredTargetBuilder init(RuleContext ruleContext, final JavaCommon common) throws InterruptedException {
    JavaTargetAttributes.Builder attributesBuilder = common.initCommon();
    // Collect the transitive dependencies.
    JavaCompilationHelper helper = new JavaCompilationHelper(ruleContext, semantics, common.getJavacOpts(), attributesBuilder);
    helper.addLibrariesToAttributes(common.targetsTreatedAsDeps(ClasspathType.COMPILE_ONLY));
    if (ruleContext.hasErrors()) {
        return null;
    }
    semantics.checkRule(ruleContext, common);
    JavaCompilationArtifacts.Builder javaArtifactsBuilder = new JavaCompilationArtifacts.Builder();
    if (ruleContext.hasErrors()) {
        common.setJavaCompilationArtifacts(JavaCompilationArtifacts.EMPTY);
        return null;
    }
    JavaConfiguration javaConfig = ruleContext.getFragment(JavaConfiguration.class);
    NestedSetBuilder<Artifact> filesBuilder = NestedSetBuilder.stableOrder();
    JavaTargetAttributes attributes = helper.getAttributes();
    if (attributes.hasMessages()) {
        helper.setTranslations(semantics.translate(ruleContext, javaConfig, attributes.getMessages()));
    }
    ruleContext.checkSrcsSamePackage(true);
    Artifact jar = null;
    Artifact srcJar = ruleContext.getImplicitOutputArtifact(JavaSemantics.JAVA_LIBRARY_SOURCE_JAR);
    Artifact classJar = ruleContext.getImplicitOutputArtifact(JavaSemantics.JAVA_LIBRARY_CLASS_JAR);
    if (attributes.hasSourceFiles() || attributes.hasSourceJars() || attributes.hasResources() || attributes.hasMessages()) {
        // We only want to add a jar to the classpath of a dependent rule if it has content.
        javaArtifactsBuilder.addRuntimeJar(classJar);
        jar = classJar;
    }
    filesBuilder.add(classJar);
    Artifact manifestProtoOutput = helper.createManifestProtoOutput(classJar);
    // The gensrc jar is created only if the target uses annotation processing.
    // Otherwise, it is null, and the source jar action will not depend on the compile action.
    Artifact genSourceJar = null;
    Artifact genClassJar = null;
    if (helper.usesAnnotationProcessing()) {
        genClassJar = helper.createGenJar(classJar);
        genSourceJar = helper.createGensrcJar(classJar);
        helper.createGenJarAction(classJar, manifestProtoOutput, genClassJar);
    }
    Artifact outputDepsProto = helper.createOutputDepsProtoArtifact(classJar, javaArtifactsBuilder);
    helper.createCompileActionWithInstrumentation(classJar, manifestProtoOutput, genSourceJar, outputDepsProto, javaArtifactsBuilder);
    helper.createSourceJarAction(srcJar, genSourceJar);
    Artifact iJar = null;
    if ((attributes.hasSourceFiles() || attributes.hasSourceJars()) && jar != null) {
        iJar = helper.createCompileTimeJarAction(jar, javaArtifactsBuilder);
    }
    boolean neverLink = JavaCommon.isNeverLink(ruleContext);
    JavaCompilationArtifacts javaArtifacts = javaArtifactsBuilder.build();
    common.setJavaCompilationArtifacts(javaArtifacts);
    common.setClassPathFragment(new ClasspathConfiguredFragment(javaArtifacts, attributes, neverLink, helper.getBootclasspathOrDefault()));
    CppCompilationContext transitiveCppDeps = common.collectTransitiveCppDeps();
    NestedSet<Artifact> transitiveSourceJars = common.collectTransitiveSourceJars(srcJar);
    // If sources are empty, treat this library as a forwarding node for dependencies.
    JavaCompilationArgs javaCompilationArgs = common.collectJavaCompilationArgs(false, neverLink, false);
    JavaCompilationArgs recursiveJavaCompilationArgs = common.collectJavaCompilationArgs(true, neverLink, false);
    NestedSet<Artifact> compileTimeJavaDepArtifacts = common.collectCompileTimeDependencyArtifacts(javaArtifacts.getCompileTimeDependencyArtifact());
    NestedSet<Artifact> runTimeJavaDepArtifacts = NestedSetBuilder.emptySet(Order.STABLE_ORDER);
    NestedSet<LinkerInput> transitiveJavaNativeLibraries = common.collectTransitiveJavaNativeLibraries();
    CcLinkParamsStore ccLinkParamsStore = new CcLinkParamsStore() {

        @Override
        protected void collect(CcLinkParams.Builder builder, boolean linkingStatically, boolean linkShared) {
            builder.addTransitiveTargets(common.targetsTreatedAsDeps(ClasspathType.BOTH), JavaCcLinkParamsProvider.TO_LINK_PARAMS, CcLinkParamsProvider.TO_LINK_PARAMS);
        }
    };
    ProtoJavaApiInfoAspectProvider.Builder protoAspectBuilder = ProtoJavaApiInfoAspectProvider.builder();
    for (TransitiveInfoCollection dep : common.getDependencies()) {
        ProtoJavaApiInfoAspectProvider protoProvider = JavaProvider.getProvider(ProtoJavaApiInfoAspectProvider.class, dep);
        if (protoProvider != null) {
            protoAspectBuilder.addTransitive(protoProvider);
        }
    }
    RuleConfiguredTargetBuilder builder = new RuleConfiguredTargetBuilder(ruleContext);
    semantics.addProviders(ruleContext, common, ImmutableList.<String>of(), classJar, srcJar, genClassJar, genSourceJar, ImmutableMap.<Artifact, Artifact>of(), filesBuilder, builder);
    JavaRuleOutputJarsProvider ruleOutputJarsProvider = JavaRuleOutputJarsProvider.builder().addOutputJar(classJar, iJar, ImmutableList.of(srcJar)).setJdeps(outputDepsProto).build();
    JavaCompilationArgsProvider compilationArgsProvider = JavaCompilationArgsProvider.create(javaCompilationArgs, recursiveJavaCompilationArgs, compileTimeJavaDepArtifacts, runTimeJavaDepArtifacts);
    JavaSourceJarsProvider sourceJarsProvider = JavaSourceJarsProvider.create(transitiveSourceJars, ImmutableList.of(srcJar));
    JavaSkylarkApiProvider.Builder skylarkApiProvider = JavaSkylarkApiProvider.builder().setRuleOutputJarsProvider(ruleOutputJarsProvider).setSourceJarsProvider(sourceJarsProvider).setCompilationArgsProvider(compilationArgsProvider);
    NestedSet<Artifact> filesToBuild = filesBuilder.build();
    common.addTransitiveInfoProviders(builder, skylarkApiProvider, filesToBuild, classJar);
    common.addGenJarsProvider(builder, skylarkApiProvider, genClassJar, genSourceJar);
    NestedSet<Artifact> proguardSpecs = new ProguardLibrary(ruleContext).collectProguardSpecs();
    CcLinkParamsProvider ccLinkParamsProvider = new CcLinkParamsProvider(ccLinkParamsStore);
    JavaProvider javaProvider = JavaProvider.Builder.create().addProvider(JavaCompilationArgsProvider.class, compilationArgsProvider).addProvider(JavaSourceJarsProvider.class, sourceJarsProvider).addProvider(ProtoJavaApiInfoAspectProvider.class, protoAspectBuilder.build()).build();
    builder.addSkylarkTransitiveInfo(JavaSkylarkApiProvider.NAME, skylarkApiProvider.build()).add(JavaRuleOutputJarsProvider.class, ruleOutputJarsProvider).add(JavaRuntimeJarProvider.class, new JavaRuntimeJarProvider(javaArtifacts.getRuntimeJars())).add(RunfilesProvider.class, RunfilesProvider.simple(JavaCommon.getRunfiles(ruleContext, semantics, javaArtifacts, neverLink))).setFilesToBuild(filesToBuild).add(JavaNeverlinkInfoProvider.class, new JavaNeverlinkInfoProvider(neverLink)).add(CppCompilationContext.class, transitiveCppDeps).add(JavaCompilationArgsProvider.class, compilationArgsProvider).add(JavaProvider.class, javaProvider).add(CcLinkParamsProvider.class, ccLinkParamsProvider).addNativeDeclaredProvider(ccLinkParamsProvider).addNativeDeclaredProvider(javaProvider).add(JavaNativeLibraryProvider.class, new JavaNativeLibraryProvider(transitiveJavaNativeLibraries)).add(JavaSourceInfoProvider.class, JavaSourceInfoProvider.fromJavaTargetAttributes(attributes, semantics)).add(JavaSourceJarsProvider.class, sourceJarsProvider).add(JavaPluginInfoProvider.class, JavaCommon.getTransitivePlugins(ruleContext)).add(ProguardSpecProvider.class, new ProguardSpecProvider(proguardSpecs)).addOutputGroup(JavaSemantics.SOURCE_JARS_OUTPUT_GROUP, transitiveSourceJars).addOutputGroup(OutputGroupProvider.HIDDEN_TOP_LEVEL, proguardSpecs);
    if (ruleContext.hasErrors()) {
        return null;
    }
    return builder;
}
Also used : NestedSetBuilder(com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder) RuleConfiguredTargetBuilder(com.google.devtools.build.lib.analysis.RuleConfiguredTargetBuilder) CcLinkParamsProvider(com.google.devtools.build.lib.rules.cpp.CcLinkParamsProvider) LinkerInput(com.google.devtools.build.lib.rules.cpp.LinkerInput) CcLinkParamsStore(com.google.devtools.build.lib.rules.cpp.CcLinkParamsStore) RunfilesProvider(com.google.devtools.build.lib.analysis.RunfilesProvider) Artifact(com.google.devtools.build.lib.actions.Artifact) CppCompilationContext(com.google.devtools.build.lib.rules.cpp.CppCompilationContext) RuleConfiguredTargetBuilder(com.google.devtools.build.lib.analysis.RuleConfiguredTargetBuilder) TransitiveInfoCollection(com.google.devtools.build.lib.analysis.TransitiveInfoCollection)

Example 9 with NestedSetBuilder

use of com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder in project bazel by bazelbuild.

the class JavaProtoLibrary method create.

@Override
public ConfiguredTarget create(final RuleContext ruleContext) throws InterruptedException, RuleErrorException {
    JavaCompilationArgsProvider dependencyArgsProviders = JavaCompilationArgsProvider.merge(Iterables.<JavaCompilationArgsAspectProvider, JavaCompilationArgsProvider>transform(this.<JavaCompilationArgsAspectProvider>getDeps(ruleContext, JavaCompilationArgsAspectProvider.class), JavaCompilationArgsAspectProvider.GET_PROVIDER));
    if (!StrictDepsUtils.isStrictDepsJavaProtoLibrary(ruleContext)) {
        dependencyArgsProviders = StrictDepsUtils.makeNonStrict(dependencyArgsProviders);
    }
    Runfiles runfiles = new Runfiles.Builder(ruleContext.getWorkspaceName()).addArtifacts(dependencyArgsProviders.getRecursiveJavaCompilationArgs().getRuntimeJars()).build();
    JavaSourceJarsProvider sourceJarsProvider = JavaSourceJarsProvider.merge(Iterables.<JavaSourceJarsAspectProvider, JavaSourceJarsProvider>transform(this.<JavaSourceJarsAspectProvider>getDeps(ruleContext, JavaSourceJarsAspectProvider.class), JavaSourceJarsAspectProvider.GET_PROVIDER));
    NestedSetBuilder<Artifact> filesToBuild = NestedSetBuilder.stableOrder();
    filesToBuild.addAll(sourceJarsProvider.getSourceJars());
    for (JavaProtoLibraryTransitiveFilesToBuildProvider provider : ruleContext.getPrerequisites("deps", Mode.TARGET, JavaProtoLibraryTransitiveFilesToBuildProvider.class)) {
        filesToBuild.addTransitive(provider.getJars());
    }
    JavaRuleOutputJarsProvider ruleOutputJarsProvider = JavaRuleOutputJarsProvider.builder().build();
    JavaSkylarkApiProvider.Builder skylarkApiProvider = JavaSkylarkApiProvider.builder().setRuleOutputJarsProvider(ruleOutputJarsProvider).setSourceJarsProvider(sourceJarsProvider).setCompilationArgsProvider(dependencyArgsProviders);
    return new RuleConfiguredTargetBuilder(ruleContext).setFilesToBuild(filesToBuild.build()).addSkylarkTransitiveInfo(JavaSkylarkApiProvider.NAME, skylarkApiProvider.build()).addProvider(RunfilesProvider.class, RunfilesProvider.withData(Runfiles.EMPTY, runfiles)).addOutputGroup(OutputGroupProvider.DEFAULT, NestedSetBuilder.<Artifact>emptySet(STABLE_ORDER)).add(JavaCompilationArgsProvider.class, dependencyArgsProviders).add(JavaSourceJarsProvider.class, sourceJarsProvider).add(JavaRunfilesProvider.class, new JavaRunfilesProvider(runfiles)).add(JavaRuleOutputJarsProvider.class, ruleOutputJarsProvider).build();
}
Also used : JavaRuleOutputJarsProvider(com.google.devtools.build.lib.rules.java.JavaRuleOutputJarsProvider) JavaSourceJarsProvider(com.google.devtools.build.lib.rules.java.JavaSourceJarsProvider) JavaSkylarkApiProvider(com.google.devtools.build.lib.rules.java.JavaSkylarkApiProvider) NestedSetBuilder(com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder) RuleConfiguredTargetBuilder(com.google.devtools.build.lib.analysis.RuleConfiguredTargetBuilder) Artifact(com.google.devtools.build.lib.actions.Artifact) Runfiles(com.google.devtools.build.lib.analysis.Runfiles) JavaCompilationArgsProvider(com.google.devtools.build.lib.rules.java.JavaCompilationArgsProvider) RuleConfiguredTargetBuilder(com.google.devtools.build.lib.analysis.RuleConfiguredTargetBuilder) JavaRunfilesProvider(com.google.devtools.build.lib.rules.java.JavaRunfilesProvider)

Example 10 with NestedSetBuilder

use of com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder in project bazel by bazelbuild.

the class AppleBinary method create.

@Override
public final ConfiguredTarget create(RuleContext ruleContext) throws InterruptedException, RuleErrorException {
    PlatformType platformType = MultiArchSplitTransitionProvider.getPlatformType(ruleContext);
    AppleConfiguration appleConfiguration = ruleContext.getFragment(AppleConfiguration.class);
    Platform platform = appleConfiguration.getMultiArchPlatform(platformType);
    ImmutableListMultimap<BuildConfiguration, ObjcProvider> configurationToNonPropagatedObjcMap = ruleContext.getPrerequisitesByConfiguration("non_propagated_deps", Mode.SPLIT, ObjcProvider.class);
    ImmutableListMultimap<BuildConfiguration, TransitiveInfoCollection> configToDepsCollectionMap = ruleContext.getPrerequisitesByConfiguration("deps", Mode.SPLIT);
    Set<BuildConfiguration> childConfigurations = getChildConfigurations(ruleContext);
    Artifact outputArtifact = ObjcRuleClasses.intermediateArtifacts(ruleContext).combinedArchitectureBinary();
    MultiArchBinarySupport multiArchBinarySupport = new MultiArchBinarySupport(ruleContext);
    Map<BuildConfiguration, ObjcProvider> objcProviderByDepConfiguration = multiArchBinarySupport.objcProviderByDepConfiguration(childConfigurations, configToDepsCollectionMap, configurationToNonPropagatedObjcMap, getDylibProviders(ruleContext), getDylibProtoProviders(ruleContext));
    multiArchBinarySupport.registerActions(platform, getExtraLinkArgs(ruleContext), objcProviderByDepConfiguration, getExtraLinkInputs(ruleContext), configToDepsCollectionMap, outputArtifact);
    NestedSetBuilder<Artifact> filesToBuild = NestedSetBuilder.<Artifact>stableOrder().add(outputArtifact);
    RuleConfiguredTargetBuilder targetBuilder = ObjcRuleClasses.ruleConfiguredTarget(ruleContext, filesToBuild.build());
    ObjcProvider.Builder objcProviderBuilder = new ObjcProvider.Builder();
    for (ObjcProvider objcProvider : objcProviderByDepConfiguration.values()) {
        objcProviderBuilder.addTransitiveAndPropagate(objcProvider);
    }
    objcProviderBuilder.add(MULTI_ARCH_LINKED_BINARIES, outputArtifact);
    ObjcProvider objcProvider = objcProviderBuilder.build();
    // TODO(cparsons): Stop propagating ObjcProvider directly from this rule.
    targetBuilder.addProvider(ObjcProvider.class, objcProvider);
    switch(getBinaryType(ruleContext)) {
        case EXECUTABLE:
            targetBuilder.addNativeDeclaredProvider(new AppleExecutableBinaryProvider(outputArtifact, objcProvider));
            break;
        case DYLIB:
            targetBuilder.addNativeDeclaredProvider(new AppleDylibBinaryProvider(outputArtifact, objcProvider));
            break;
        case LOADABLE_BUNDLE:
            targetBuilder.addNativeDeclaredProvider(new AppleLoadableBundleBinaryProvider(outputArtifact));
            break;
    }
    AppleDebugOutputsProvider.Builder builder = AppleDebugOutputsProvider.Builder.create();
    for (BuildConfiguration childConfig : childConfigurations) {
        AppleConfiguration childAppleConfig = childConfig.getFragment(AppleConfiguration.class);
        ObjcConfiguration childObjcConfig = childConfig.getFragment(ObjcConfiguration.class);
        IntermediateArtifacts intermediateArtifacts = new IntermediateArtifacts(ruleContext, /*archiveFileNameSuffix*/
        "", /*outputPrefix*/
        "", childConfig);
        String arch = childAppleConfig.getSingleArchitecture();
        if (childAppleConfig.getBitcodeMode() == AppleBitcodeMode.EMBEDDED) {
            Artifact bitcodeSymbol = intermediateArtifacts.bitcodeSymbolMap();
            builder.addOutput(arch, OutputType.BITCODE_SYMBOLS, bitcodeSymbol);
        }
        if (childObjcConfig.generateDsym()) {
            Artifact dsymBinary = intermediateArtifacts.dsymSymbol(DsymOutputType.APP);
            builder.addOutput(arch, OutputType.DSYM_BINARY, dsymBinary);
        }
        if (childObjcConfig.generateLinkmap()) {
            Artifact linkmap = intermediateArtifacts.linkmap();
            builder.addOutput(arch, OutputType.LINKMAP, linkmap);
        }
    }
    targetBuilder.addNativeDeclaredProvider(builder.build());
    return targetBuilder.build();
}
Also used : Platform(com.google.devtools.build.lib.rules.apple.Platform) NestedSetBuilder(com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder) RuleConfiguredTargetBuilder(com.google.devtools.build.lib.analysis.RuleConfiguredTargetBuilder) AppleConfiguration(com.google.devtools.build.lib.rules.apple.AppleConfiguration) Artifact(com.google.devtools.build.lib.actions.Artifact) BuildConfiguration(com.google.devtools.build.lib.analysis.config.BuildConfiguration) RuleConfiguredTargetBuilder(com.google.devtools.build.lib.analysis.RuleConfiguredTargetBuilder) TransitiveInfoCollection(com.google.devtools.build.lib.analysis.TransitiveInfoCollection) PlatformType(com.google.devtools.build.lib.rules.apple.Platform.PlatformType)

Aggregations

NestedSetBuilder (com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder)28 Artifact (com.google.devtools.build.lib.actions.Artifact)24 RuleConfiguredTargetBuilder (com.google.devtools.build.lib.analysis.RuleConfiguredTargetBuilder)18 TransitiveInfoCollection (com.google.devtools.build.lib.analysis.TransitiveInfoCollection)8 AppleConfiguration (com.google.devtools.build.lib.rules.apple.AppleConfiguration)8 Runfiles (com.google.devtools.build.lib.analysis.Runfiles)6 RunfilesProvider (com.google.devtools.build.lib.analysis.RunfilesProvider)6 ImmutableList (com.google.common.collect.ImmutableList)4 BuildConfiguration (com.google.devtools.build.lib.analysis.config.BuildConfiguration)4 FileProvider (com.google.devtools.build.lib.analysis.FileProvider)3 RunfilesSupport (com.google.devtools.build.lib.analysis.RunfilesSupport)3 ParameterFileWriteAction (com.google.devtools.build.lib.analysis.actions.ParameterFileWriteAction)3 SpawnAction (com.google.devtools.build.lib.analysis.actions.SpawnAction)3 Label (com.google.devtools.build.lib.cmdline.Label)3 PlatformType (com.google.devtools.build.lib.rules.apple.Platform.PlatformType)3 CcLinkParamsProvider (com.google.devtools.build.lib.rules.cpp.CcLinkParamsProvider)3 JavaRuleOutputJarsProvider (com.google.devtools.build.lib.rules.java.JavaRuleOutputJarsProvider)3 PathFragment (com.google.devtools.build.lib.vfs.PathFragment)3 ArrayList (java.util.ArrayList)3 ImmutableSet (com.google.common.collect.ImmutableSet)2