Search in sources :

Example 1 with NestedSetBuilder

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

the class ShLibrary method create.

@Override
public ConfiguredTarget create(RuleContext ruleContext) throws RuleErrorException {
    NestedSet<Artifact> filesToBuild = NestedSetBuilder.<Artifact>stableOrder().addAll(ruleContext.getPrerequisiteArtifacts("srcs", Mode.TARGET).list()).addAll(ruleContext.getPrerequisiteArtifacts("deps", Mode.TARGET).list()).addAll(ruleContext.getPrerequisiteArtifacts("data", Mode.DATA).list()).build();
    Runfiles runfiles = new Runfiles.Builder(ruleContext.getWorkspaceName(), ruleContext.getConfiguration().legacyExternalRunfiles()).addTransitiveArtifacts(filesToBuild).build();
    return new RuleConfiguredTargetBuilder(ruleContext).setFilesToBuild(filesToBuild).addProvider(RunfilesProvider.class, RunfilesProvider.simple(runfiles)).build();
}
Also used : Runfiles(com.google.devtools.build.lib.analysis.Runfiles) NestedSetBuilder(com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder) RuleConfiguredTargetBuilder(com.google.devtools.build.lib.analysis.RuleConfiguredTargetBuilder) RuleConfiguredTargetBuilder(com.google.devtools.build.lib.analysis.RuleConfiguredTargetBuilder) RunfilesProvider(com.google.devtools.build.lib.analysis.RunfilesProvider) Artifact(com.google.devtools.build.lib.actions.Artifact)

Example 2 with NestedSetBuilder

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

the class CppLinkActionBuilder method build.

/** Builds the Action as configured and returns it. */
public CppLinkAction build() throws InterruptedException {
    // Executable links do not have library identifiers.
    boolean hasIdentifier = (libraryIdentifier != null);
    boolean isExecutable = linkType.isExecutable();
    Preconditions.checkState(hasIdentifier != isExecutable);
    if (interfaceOutput != null && (fake || linkType != LinkTargetType.DYNAMIC_LIBRARY)) {
        throw new RuntimeException("Interface output can only be used " + "with non-fake DYNAMIC_LIBRARY targets");
    }
    final ImmutableList<Artifact> buildInfoHeaderArtifacts = !linkstamps.isEmpty() ? analysisEnvironment.getBuildInfo(ruleContext, CppBuildInfo.KEY, configuration) : ImmutableList.<Artifact>of();
    boolean needWholeArchive = wholeArchive || needWholeArchive(linkStaticness, linkType, linkopts, isNativeDeps, cppConfiguration);
    NestedSet<LibraryToLink> uniqueLibraries = libraries.build();
    final Iterable<Artifact> objectArtifacts = LinkerInputs.toLibraryArtifacts(objectFiles);
    final Iterable<LinkerInput> linkerInputs = IterablesChain.<LinkerInput>builder().add(ImmutableList.copyOf(objectFiles)).add(ImmutableIterable.from(Link.mergeInputsCmdLine(uniqueLibraries, needWholeArchive, cppConfiguration.archiveType()))).build();
    // ruleContext can only be null during testing. This is kind of ugly.
    final ImmutableSet<String> features = (ruleContext == null) ? ImmutableSet.<String>of() : ruleContext.getFeatures();
    // instantiated without a feature configuration.
    if (featureConfiguration == null) {
        if (toolchain != null) {
            featureConfiguration = CcCommon.configureFeatures(ruleContext, toolchain, CcLibraryHelper.SourceCategory.CC);
        } else {
            featureConfiguration = CcCommon.configureFeatures(ruleContext, toolchain);
        }
    }
    final LibraryToLink outputLibrary = linkType.isExecutable() ? null : LinkerInputs.newInputLibrary(output, linkType.getLinkerOutput(), libraryIdentifier, objectArtifacts, this.ltoBitcodeFiles);
    final LibraryToLink interfaceOutputLibrary = (interfaceOutput == null) ? null : LinkerInputs.newInputLibrary(interfaceOutput, ArtifactCategory.DYNAMIC_LIBRARY, libraryIdentifier, objectArtifacts, this.ltoBitcodeFiles);
    final ImmutableMap<Artifact, Artifact> linkstampMap = mapLinkstampsToOutputs(linkstamps, ruleContext, configuration, output, linkArtifactFactory);
    PathFragment ltoOutputRootPrefix = null;
    if (isLTOIndexing && allLTOArtifacts == null) {
        ltoOutputRootPrefix = FileSystemUtils.appendExtension(output.getRootRelativePath(), ".lto");
        allLTOArtifacts = createLTOArtifacts(ltoOutputRootPrefix, uniqueLibraries);
    }
    PathFragment linkerParamFileRootPath = null;
    @Nullable Artifact thinltoParamFile = null;
    if (allLTOArtifacts != null) {
        // Create artifact for the file that the LTO indexing step will emit
        // object file names into for any that were included in the link as
        // determined by the linker's symbol resolution. It will be used to
        // provide the inputs for the subsequent final native object link.
        // Note that the paths emitted into this file will have their prefixes
        // replaced with the final output directory, so they will be the paths
        // of the native object files not the input bitcode files.
        linkerParamFileRootPath = ParameterFile.derivePath(output.getRootRelativePath(), "lto-final");
        thinltoParamFile = linkArtifactFactory.create(ruleContext, configuration, linkerParamFileRootPath);
    }
    final ImmutableList<Artifact> actionOutputs;
    if (isLTOIndexing) {
        ImmutableList.Builder<Artifact> builder = ImmutableList.builder();
        for (LTOBackendArtifacts ltoA : allLTOArtifacts) {
            ltoA.addIndexingOutputs(builder);
        }
        if (thinltoParamFile != null) {
            builder.add(thinltoParamFile);
        }
        actionOutputs = builder.build();
    } else {
        actionOutputs = constructOutputs(output, linkstampMap.values(), interfaceOutputLibrary == null ? null : interfaceOutputLibrary.getArtifact(), symbolCounts);
    }
    ImmutableList<LinkerInput> runtimeLinkerInputs = ImmutableList.copyOf(LinkerInputs.simpleLinkerInputs(runtimeInputs, runtimeType));
    PathFragment paramRootPath = ParameterFile.derivePath(output.getRootRelativePath(), (isLTOIndexing) ? "lto-index" : "2");
    @Nullable final Artifact paramFile = canSplitCommandLine() ? linkArtifactFactory.create(ruleContext, configuration, paramRootPath) : null;
    // Add build variables necessary to template link args into the crosstool.
    Variables.Builder buildVariablesBuilder = new Variables.Builder();
    CppLinkVariablesExtension variablesExtension = isLTOIndexing ? new CppLinkVariablesExtension(configuration, ImmutableMap.<Artifact, Artifact>of(), needWholeArchive, linkerInputs, runtimeLinkerInputs, null, paramFile, thinltoParamFile, ltoOutputRootPrefix, null, null) : new CppLinkVariablesExtension(configuration, linkstampMap, needWholeArchive, linkerInputs, runtimeLinkerInputs, output, paramFile, thinltoParamFile, PathFragment.EMPTY_FRAGMENT, toolchain.getInterfaceSoBuilder(), interfaceOutput);
    variablesExtension.addVariables(buildVariablesBuilder);
    for (VariablesExtension extraVariablesExtension : variablesExtensions) {
        extraVariablesExtension.addVariables(buildVariablesBuilder);
    }
    Variables buildVariables = buildVariablesBuilder.build();
    Preconditions.checkArgument(linkType != LinkTargetType.INTERFACE_DYNAMIC_LIBRARY, "you can't link an interface dynamic library directly");
    if (linkType != LinkTargetType.DYNAMIC_LIBRARY) {
        Preconditions.checkArgument(interfaceOutput == null, "interface output may only be non-null for dynamic library links");
    }
    if (linkType.staticness() == Staticness.STATIC) {
        // solib dir must be null for static links
        runtimeSolibDir = null;
        Preconditions.checkArgument(linkStaticness == LinkStaticness.FULLY_STATIC, "static library link must be static");
        Preconditions.checkArgument(symbolCounts == null, "the symbol counts output must be null for static links");
        Preconditions.checkArgument(!isNativeDeps, "the native deps flag must be false for static links");
        Preconditions.checkArgument(!needWholeArchive, "the need whole archive flag must be false for static links");
    }
    LinkCommandLine.Builder linkCommandLineBuilder = new LinkCommandLine.Builder(configuration, getOwner(), ruleContext).setLinkerInputs(linkerInputs).setRuntimeInputs(runtimeLinkerInputs).setLinkTargetType(linkType).setLinkStaticness(linkStaticness).setFeatures(features).setRuntimeSolibDir(linkType.staticness() == Staticness.STATIC ? null : runtimeSolibDir).setNativeDeps(isNativeDeps).setUseTestOnlyFlags(useTestOnlyFlags).setParamFile(paramFile).setToolchain(toolchain).setFdoSupport(fdoSupport.getFdoSupport()).setBuildVariables(buildVariables).setToolPath(getToolPath()).setFeatureConfiguration(featureConfiguration);
    if (!isLTOIndexing) {
        linkCommandLineBuilder.setOutput(output).setBuildInfoHeaderArtifacts(buildInfoHeaderArtifacts).setLinkstamps(linkstampMap).setLinkopts(ImmutableList.copyOf(linkopts)).addLinkstampCompileOptions(linkstampOptions);
    } else {
        List<String> opts = new ArrayList<>(linkopts);
        opts.addAll(featureConfiguration.getCommandLine("lto-indexing", buildVariables));
        opts.addAll(cppConfiguration.getLTOIndexOptions());
        linkCommandLineBuilder.setLinkopts(ImmutableList.copyOf(opts));
    }
    LinkCommandLine linkCommandLine = linkCommandLineBuilder.build();
    // Compute the set of inputs - we only need stable order here.
    NestedSetBuilder<Artifact> dependencyInputsBuilder = NestedSetBuilder.stableOrder();
    dependencyInputsBuilder.addTransitive(crosstoolInputs);
    dependencyInputsBuilder.add(toolchain.getLinkDynamicLibraryTool());
    dependencyInputsBuilder.addTransitive(linkActionInputs.build());
    if (runtimeMiddleman != null) {
        dependencyInputsBuilder.add(runtimeMiddleman);
    }
    if (!isLTOIndexing) {
        dependencyInputsBuilder.addAll(buildInfoHeaderArtifacts);
        dependencyInputsBuilder.addAll(linkstamps);
        dependencyInputsBuilder.addTransitive(compilationInputs.build());
    }
    Iterable<Artifact> expandedInputs = LinkerInputs.toLibraryArtifacts(Link.mergeInputsDependencies(uniqueLibraries, needWholeArchive, cppConfiguration.archiveType()));
    Iterable<Artifact> expandedNonLibraryInputs = LinkerInputs.toLibraryArtifacts(objectFiles);
    if (!isLTOIndexing && allLTOArtifacts != null) {
        // We are doing LTO, and this is the real link, so substitute
        // the LTO bitcode files with the real object files they were translated into.
        Map<Artifact, Artifact> ltoMapping = new HashMap<>();
        for (LTOBackendArtifacts a : allLTOArtifacts) {
            ltoMapping.put(a.getBitcodeFile(), a.getObjectFile());
        }
        // Handle libraries.
        List<Artifact> renamedInputs = new ArrayList<>();
        for (Artifact a : expandedInputs) {
            Artifact renamed = ltoMapping.get(a);
            renamedInputs.add(renamed == null ? a : renamed);
        }
        expandedInputs = renamedInputs;
        // Handle non-libraries.
        List<Artifact> renamedNonLibraryInputs = new ArrayList<>();
        for (Artifact a : expandedNonLibraryInputs) {
            Artifact renamed = ltoMapping.get(a);
            renamedNonLibraryInputs.add(renamed == null ? a : renamed);
        }
        expandedNonLibraryInputs = renamedNonLibraryInputs;
    } else if (isLTOIndexing && allLTOArtifacts != null) {
        for (LTOBackendArtifacts a : allLTOArtifacts) {
            List<String> argv = new ArrayList<>();
            argv.addAll(cppConfiguration.getLinkOptions());
            argv.addAll(cppConfiguration.getCompilerOptions(features));
            a.setCommandLine(argv);
            a.scheduleLTOBackendAction(ruleContext, featureConfiguration, toolchain, fdoSupport, usePicForLTOBackendActions, useFissionForLTOBackendActions);
        }
    }
    // getPrimaryInput returns the first element, and that is a public interface - therefore the
    // order here is important.
    IterablesChain.Builder<Artifact> inputsBuilder = IterablesChain.<Artifact>builder().add(ImmutableList.copyOf(expandedNonLibraryInputs)).add(ImmutableList.copyOf(nonCodeInputs)).add(dependencyInputsBuilder.build()).add(ImmutableIterable.from(expandedInputs));
    if (thinltoParamFile != null && !isLTOIndexing) {
        inputsBuilder.add(ImmutableList.of(thinltoParamFile));
    }
    if (linkCommandLine.getParamFile() != null) {
        inputsBuilder.add(ImmutableList.of(linkCommandLine.getParamFile()));
        Action parameterFileWriteAction = new ParameterFileWriteAction(getOwner(), paramFile, linkCommandLine.paramCmdLine(), ParameterFile.ParameterFileType.UNQUOTED, ISO_8859_1);
        analysisEnvironment.registerAction(parameterFileWriteAction);
    }
    ImmutableMap<String, String> toolchainEnv = featureConfiguration.getEnvironmentVariables(getActionName(), buildVariables);
    // If the crosstool uses action_configs to configure cc compilation, collect execution info
    // from there, otherwise, use no execution info.
    // TODO(b/27903698): Assert that the crosstool has an action_config for this action.
    ImmutableSet.Builder<String> executionRequirements = ImmutableSet.<String>builder();
    if (featureConfiguration.actionIsConfigured(getActionName())) {
        executionRequirements.addAll(featureConfiguration.getToolForAction(getActionName()).getExecutionRequirements());
    }
    return new CppLinkAction(getOwner(), mnemonic, inputsBuilder.deduplicate().build(), actionOutputs, cppConfiguration, outputLibrary, output, interfaceOutputLibrary, fake, isLTOIndexing, allLTOArtifacts, linkCommandLine, configuration.getVariableShellEnvironment(), configuration.getLocalShellEnvironment(), toolchainEnv, executionRequirements.build());
}
Also used : Action(com.google.devtools.build.lib.actions.Action) ParameterFileWriteAction(com.google.devtools.build.lib.analysis.actions.ParameterFileWriteAction) HashMap(java.util.HashMap) ImmutableList(com.google.common.collect.ImmutableList) SequenceBuilder(com.google.devtools.build.lib.rules.cpp.CcToolchainFeatures.Variables.SequenceBuilder) Builder(com.google.common.collect.ImmutableSet.Builder) NestedSetBuilder(com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder) PathFragment(com.google.devtools.build.lib.vfs.PathFragment) ArrayList(java.util.ArrayList) Variables(com.google.devtools.build.lib.rules.cpp.CcToolchainFeatures.Variables) ParameterFileWriteAction(com.google.devtools.build.lib.analysis.actions.ParameterFileWriteAction) ImmutableSet(com.google.common.collect.ImmutableSet) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) List(java.util.List) IterablesChain(com.google.devtools.build.lib.collect.IterablesChain) Artifact(com.google.devtools.build.lib.actions.Artifact) LibraryToLink(com.google.devtools.build.lib.rules.cpp.LinkerInputs.LibraryToLink) VariablesExtension(com.google.devtools.build.lib.rules.cpp.CcToolchainFeatures.Variables.VariablesExtension) Nullable(javax.annotation.Nullable)

Example 3 with NestedSetBuilder

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

the class CcToolchain method create.

@Override
public ConfiguredTarget create(RuleContext ruleContext) throws RuleErrorException, InterruptedException {
    TransitiveInfoCollection lipoContextCollector = ruleContext.getPrerequisite(":lipo_context_collector", Mode.DONT_CHECK);
    if (lipoContextCollector != null && lipoContextCollector.getProvider(LipoContextProvider.class) == null) {
        ruleContext.ruleError("--lipo_context must point to a cc_binary or a cc_test rule");
        return null;
    }
    CppConfiguration cppConfiguration = Preconditions.checkNotNull(ruleContext.getFragment(CppConfiguration.class));
    Path fdoZip = ruleContext.getConfiguration().getCompilationMode() == CompilationMode.OPT ? cppConfiguration.getFdoZip() : null;
    SkyKey fdoKey = FdoSupportValue.key(cppConfiguration.getLipoMode(), fdoZip, cppConfiguration.getFdoInstrument());
    SkyFunction.Environment skyframeEnv = ruleContext.getAnalysisEnvironment().getSkyframeEnv();
    FdoSupportValue fdoSupport;
    try {
        fdoSupport = (FdoSupportValue) skyframeEnv.getValueOrThrow(fdoKey, FdoException.class, IOException.class);
    } catch (FdoException | IOException e) {
        ruleContext.ruleError("cannot initialize FDO: " + e.getMessage());
        return null;
    }
    if (skyframeEnv.valuesMissing()) {
        return null;
    }
    final Label label = ruleContext.getLabel();
    final NestedSet<Artifact> crosstool = ruleContext.getPrerequisite("all_files", Mode.HOST).getProvider(FileProvider.class).getFilesToBuild();
    final NestedSet<Artifact> crosstoolMiddleman = getFiles(ruleContext, "all_files");
    final NestedSet<Artifact> compile = getFiles(ruleContext, "compiler_files");
    final NestedSet<Artifact> strip = getFiles(ruleContext, "strip_files");
    final NestedSet<Artifact> objcopy = getFiles(ruleContext, "objcopy_files");
    final NestedSet<Artifact> link = getFiles(ruleContext, "linker_files");
    final NestedSet<Artifact> dwp = getFiles(ruleContext, "dwp_files");
    final NestedSet<Artifact> libcLink = inputsForLibc(ruleContext);
    String purposePrefix = Actions.escapeLabel(label) + "_";
    String runtimeSolibDirBase = "_solib_" + "_" + Actions.escapeLabel(label);
    final PathFragment runtimeSolibDir = ruleContext.getConfiguration().getBinFragment().getRelative(runtimeSolibDirBase);
    // Static runtime inputs.
    TransitiveInfoCollection staticRuntimeLibDep = selectDep(ruleContext, "static_runtime_libs", cppConfiguration.getStaticRuntimeLibsLabel());
    final NestedSet<Artifact> staticRuntimeLinkInputs;
    final Artifact staticRuntimeLinkMiddleman;
    if (cppConfiguration.supportsEmbeddedRuntimes()) {
        staticRuntimeLinkInputs = staticRuntimeLibDep.getProvider(FileProvider.class).getFilesToBuild();
    } else {
        staticRuntimeLinkInputs = NestedSetBuilder.emptySet(Order.STABLE_ORDER);
    }
    if (!staticRuntimeLinkInputs.isEmpty()) {
        NestedSet<Artifact> staticRuntimeLinkMiddlemanSet = CompilationHelper.getAggregatingMiddleman(ruleContext, purposePrefix + "static_runtime_link", staticRuntimeLibDep);
        staticRuntimeLinkMiddleman = staticRuntimeLinkMiddlemanSet.isEmpty() ? null : Iterables.getOnlyElement(staticRuntimeLinkMiddlemanSet);
    } else {
        staticRuntimeLinkMiddleman = null;
    }
    Preconditions.checkState((staticRuntimeLinkMiddleman == null) == staticRuntimeLinkInputs.isEmpty());
    // Dynamic runtime inputs.
    TransitiveInfoCollection dynamicRuntimeLibDep = selectDep(ruleContext, "dynamic_runtime_libs", cppConfiguration.getDynamicRuntimeLibsLabel());
    NestedSet<Artifact> dynamicRuntimeLinkSymlinks;
    List<Artifact> dynamicRuntimeLinkInputs = new ArrayList<>();
    Artifact dynamicRuntimeLinkMiddleman;
    if (cppConfiguration.supportsEmbeddedRuntimes()) {
        NestedSetBuilder<Artifact> dynamicRuntimeLinkSymlinksBuilder = NestedSetBuilder.stableOrder();
        for (Artifact artifact : dynamicRuntimeLibDep.getProvider(FileProvider.class).getFilesToBuild()) {
            if (CppHelper.SHARED_LIBRARY_FILETYPES.matches(artifact.getFilename())) {
                dynamicRuntimeLinkInputs.add(artifact);
                dynamicRuntimeLinkSymlinksBuilder.add(SolibSymlinkAction.getCppRuntimeSymlink(ruleContext, artifact, runtimeSolibDirBase, ruleContext.getConfiguration()));
            }
        }
        dynamicRuntimeLinkSymlinks = dynamicRuntimeLinkSymlinksBuilder.build();
    } else {
        dynamicRuntimeLinkSymlinks = NestedSetBuilder.emptySet(Order.STABLE_ORDER);
    }
    if (!dynamicRuntimeLinkInputs.isEmpty()) {
        List<Artifact> dynamicRuntimeLinkMiddlemanSet = CppHelper.getAggregatingMiddlemanForCppRuntimes(ruleContext, purposePrefix + "dynamic_runtime_link", dynamicRuntimeLinkInputs, runtimeSolibDirBase, ruleContext.getConfiguration());
        dynamicRuntimeLinkMiddleman = dynamicRuntimeLinkMiddlemanSet.isEmpty() ? null : Iterables.getOnlyElement(dynamicRuntimeLinkMiddlemanSet);
    } else {
        dynamicRuntimeLinkMiddleman = null;
    }
    Preconditions.checkState((dynamicRuntimeLinkMiddleman == null) == dynamicRuntimeLinkSymlinks.isEmpty());
    CppCompilationContext.Builder contextBuilder = new CppCompilationContext.Builder(ruleContext);
    CppModuleMap moduleMap = createCrosstoolModuleMap(ruleContext);
    if (moduleMap != null) {
        contextBuilder.setCppModuleMap(moduleMap);
    }
    final CppCompilationContext context = contextBuilder.build();
    boolean supportsParamFiles = ruleContext.attributes().get("supports_param_files", BOOLEAN);
    boolean supportsHeaderParsing = ruleContext.attributes().get("supports_header_parsing", BOOLEAN);
    NestedSetBuilder<Pair<String, String>> coverageEnvironment = NestedSetBuilder.compileOrder();
    coverageEnvironment.add(Pair.of("COVERAGE_GCOV_PATH", cppConfiguration.getGcovExecutable().getPathString()));
    if (cppConfiguration.getFdoInstrument() != null) {
        coverageEnvironment.add(Pair.of("FDO_DIR", cppConfiguration.getFdoInstrument().getPathString()));
    }
    CcToolchainProvider provider = new CcToolchainProvider(cppConfiguration, crosstool, fullInputsForCrosstool(ruleContext, crosstoolMiddleman), compile, strip, objcopy, fullInputsForLink(ruleContext, link), ruleContext.getPrerequisiteArtifact("$interface_library_builder", Mode.HOST), dwp, libcLink, staticRuntimeLinkInputs, staticRuntimeLinkMiddleman, dynamicRuntimeLinkSymlinks, dynamicRuntimeLinkMiddleman, runtimeSolibDir, context, supportsParamFiles, supportsHeaderParsing, getBuildVariables(ruleContext), getBuiltinIncludes(ruleContext), coverageEnvironment.build(), ruleContext.getPrerequisiteArtifact("$link_dynamic_library_tool", Mode.HOST), getEnvironment(ruleContext));
    RuleConfiguredTargetBuilder builder = new RuleConfiguredTargetBuilder(ruleContext).add(CcToolchainProvider.class, provider).add(FdoSupportProvider.class, fdoSupport.getFdoSupport().createFdoSupportProvider(ruleContext)).setFilesToBuild(new NestedSetBuilder<Artifact>(Order.STABLE_ORDER).build()).add(RunfilesProvider.class, RunfilesProvider.simple(Runfiles.EMPTY));
    // If output_license is specified on the cc_toolchain rule, override the transitive licenses
    // with that one. This is necessary because cc_toolchain is used in the target configuration,
    // but it is sort-of-kind-of a tool, but various parts of it are linked into the output...
    // ...so we trust the judgment of the author of the cc_toolchain rule to figure out what
    // licenses should be propagated to C++ targets.
    // TODO(elenairina): Remove this and use Attribute.Builder.useOutputLicenses() on the
    // :cc_toolchain attribute instead.
    final License outputLicense = ruleContext.getRule().getToolOutputLicense(ruleContext.attributes());
    if (outputLicense != null && outputLicense != License.NO_LICENSE) {
        final NestedSet<TargetLicense> license = NestedSetBuilder.create(Order.STABLE_ORDER, new TargetLicense(ruleContext.getLabel(), outputLicense));
        LicensesProvider licensesProvider = new LicensesProvider() {

            @Override
            public NestedSet<TargetLicense> getTransitiveLicenses() {
                return license;
            }

            @Override
            public TargetLicense getOutputLicenses() {
                return new TargetLicense(label, outputLicense);
            }

            @Override
            public boolean hasOutputLicenses() {
                return true;
            }
        };
        builder.add(LicensesProvider.class, licensesProvider);
    }
    return builder.build();
}
Also used : NestedSetBuilder(com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder) RuleConfiguredTargetBuilder(com.google.devtools.build.lib.analysis.RuleConfiguredTargetBuilder) Label(com.google.devtools.build.lib.cmdline.Label) PathFragment(com.google.devtools.build.lib.vfs.PathFragment) ArrayList(java.util.ArrayList) License(com.google.devtools.build.lib.packages.License) TargetLicense(com.google.devtools.build.lib.analysis.LicensesProvider.TargetLicense) LicensesProvider(com.google.devtools.build.lib.analysis.LicensesProvider) Pair(com.google.devtools.build.lib.util.Pair) Path(com.google.devtools.build.lib.vfs.Path) SkyKey(com.google.devtools.build.skyframe.SkyKey) SkyFunction(com.google.devtools.build.skyframe.SkyFunction) IOException(java.io.IOException) Artifact(com.google.devtools.build.lib.actions.Artifact) TargetLicense(com.google.devtools.build.lib.analysis.LicensesProvider.TargetLicense) FileProvider(com.google.devtools.build.lib.analysis.FileProvider) RuleConfiguredTargetBuilder(com.google.devtools.build.lib.analysis.RuleConfiguredTargetBuilder) TransitiveInfoCollection(com.google.devtools.build.lib.analysis.TransitiveInfoCollection) FdoException(com.google.devtools.build.lib.rules.cpp.FdoSupport.FdoException)

Example 4 with NestedSetBuilder

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

the class J2ObjcAspect method createJ2ObjcTranspilationAction.

private static J2ObjcMappingFileProvider createJ2ObjcTranspilationAction(RuleContext ruleContext, Iterable<Artifact> sources, Iterable<Artifact> sourceJars, J2ObjcMappingFileProvider depJ2ObjcMappingFileProvider, JavaCompilationArgsProvider compArgsProvider, J2ObjcSource j2ObjcSource) {
    CustomCommandLine.Builder argBuilder = CustomCommandLine.builder();
    PathFragment javaExecutable = ruleContext.getFragment(Jvm.class, HOST).getJavaExecutable();
    argBuilder.add("--java").add(javaExecutable.getPathString());
    Artifact j2ObjcDeployJar = ruleContext.getPrerequisiteArtifact("$j2objc", Mode.HOST);
    argBuilder.addExecPath("--j2objc", j2ObjcDeployJar);
    argBuilder.add("--main_class").add("com.google.devtools.j2objc.J2ObjC");
    argBuilder.add("--objc_file_path").addPath(j2ObjcSource.getObjcFilePath());
    Artifact outputDependencyMappingFile = j2ObjcOutputDependencyMappingFile(ruleContext);
    argBuilder.addExecPath("--output_dependency_mapping_file", outputDependencyMappingFile);
    ImmutableList.Builder<Artifact> sourceJarOutputFiles = ImmutableList.builder();
    if (!Iterables.isEmpty(sourceJars)) {
        sourceJarOutputFiles.addAll(sourceJarOutputs(ruleContext));
        argBuilder.addJoinExecPaths("--src_jars", ",", sourceJars);
        argBuilder.add(sourceJarFlags(ruleContext));
    }
    Iterable<String> translationFlags = ruleContext.getFragment(J2ObjcConfiguration.class).getTranslationFlags();
    argBuilder.add(translationFlags);
    NestedSet<Artifact> depsHeaderMappingFiles = depJ2ObjcMappingFileProvider.getHeaderMappingFiles();
    if (!depsHeaderMappingFiles.isEmpty()) {
        argBuilder.addJoinExecPaths("--header-mapping", ",", depsHeaderMappingFiles);
    }
    Artifact outputHeaderMappingFile = j2ObjcOutputHeaderMappingFile(ruleContext);
    argBuilder.addExecPath("--output-header-mapping", outputHeaderMappingFile);
    NestedSet<Artifact> depsClassMappingFiles = depJ2ObjcMappingFileProvider.getClassMappingFiles();
    if (!depsClassMappingFiles.isEmpty()) {
        argBuilder.addJoinExecPaths("--mapping", ",", depsClassMappingFiles);
    }
    Artifact archiveSourceMappingFile = j2ObjcOutputArchiveSourceMappingFile(ruleContext);
    argBuilder.addExecPath("--output_archive_source_mapping_file", archiveSourceMappingFile);
    Artifact compiledLibrary = ObjcRuleClasses.j2objcIntermediateArtifacts(ruleContext).archive();
    argBuilder.addExecPath("--compiled_archive_file_path", compiledLibrary);
    Artifact bootclasspathJar = ruleContext.getPrerequisiteArtifact("$jre_emul_jar", Mode.HOST);
    argBuilder.add("-Xbootclasspath:" + bootclasspathJar.getExecPathString());
    argBuilder.add("-d").addPath(j2ObjcSource.getObjcFilePath());
    NestedSet<Artifact> compileTimeJars = compArgsProvider.getRecursiveJavaCompilationArgs().getCompileTimeJars();
    if (!compileTimeJars.isEmpty()) {
        argBuilder.addJoinExecPaths("-classpath", ":", compileTimeJars);
    }
    argBuilder.addExecPaths(sources);
    Artifact paramFile = j2ObjcOutputParamFile(ruleContext);
    ruleContext.registerAction(new ParameterFileWriteAction(ruleContext.getActionOwner(), paramFile, argBuilder.build(), ParameterFile.ParameterFileType.UNQUOTED, ISO_8859_1));
    SpawnAction.Builder builder = new SpawnAction.Builder().setMnemonic("TranspilingJ2objc").setExecutable(ruleContext.getPrerequisiteArtifact("$j2objc_wrapper", Mode.HOST)).addInput(ruleContext.getPrerequisiteArtifact("$j2objc_wrapper", Mode.HOST)).addInput(j2ObjcDeployJar).addInput(bootclasspathJar).addInputs(sources).addInputs(sourceJars).addTransitiveInputs(compileTimeJars).addTransitiveInputs(JavaHelper.getHostJavabaseInputs(ruleContext)).addTransitiveInputs(depsHeaderMappingFiles).addTransitiveInputs(depsClassMappingFiles).addInput(paramFile).setCommandLine(CustomCommandLine.builder().addPaths("@%s", paramFile.getExecPath()).build()).addOutputs(j2ObjcSource.getObjcSrcs()).addOutputs(j2ObjcSource.getObjcHdrs()).addOutput(outputHeaderMappingFile).addOutput(outputDependencyMappingFile).addOutput(archiveSourceMappingFile);
    ruleContext.registerAction(builder.build(ruleContext));
    return new J2ObjcMappingFileProvider(NestedSetBuilder.<Artifact>stableOrder().add(outputHeaderMappingFile).build(), NestedSetBuilder.<Artifact>stableOrder().build(), NestedSetBuilder.<Artifact>stableOrder().add(outputDependencyMappingFile).build(), NestedSetBuilder.<Artifact>stableOrder().add(archiveSourceMappingFile).build());
}
Also used : Jvm(com.google.devtools.build.lib.rules.java.Jvm) CustomCommandLine(com.google.devtools.build.lib.analysis.actions.CustomCommandLine) ImmutableList(com.google.common.collect.ImmutableList) NestedSetBuilder(com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder) ProtoCompileActionBuilder(com.google.devtools.build.lib.rules.proto.ProtoCompileActionBuilder) PathFragment(com.google.devtools.build.lib.vfs.PathFragment) Artifact(com.google.devtools.build.lib.actions.Artifact) SpawnAction(com.google.devtools.build.lib.analysis.actions.SpawnAction) ParameterFileWriteAction(com.google.devtools.build.lib.analysis.actions.ParameterFileWriteAction)

Example 5 with NestedSetBuilder

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

the class J2ObjcLibrary method create.

@Override
public ConfiguredTarget create(RuleContext ruleContext) throws InterruptedException, RuleErrorException {
    checkAttributes(ruleContext);
    if (ruleContext.hasErrors()) {
        return null;
    }
    J2ObjcEntryClassProvider j2ObjcEntryClassProvider = new J2ObjcEntryClassProvider.Builder().addTransitive(ruleContext).addEntryClasses(ruleContext.attributes().get("entry_classes", Type.STRING_LIST)).build();
    Iterable<ObjcProvider> jreDeps = ruleContext.getPrerequisites("jre_deps", Mode.TARGET, ObjcProvider.class);
    ObjcProvider.Builder objcProviderBuilder = new ObjcProvider.Builder().addTransitiveAndPropagate(jreDeps).addTransitiveAndPropagate(ruleContext.getPrerequisites("deps", Mode.TARGET, ObjcProvider.class));
    for (ObjcProvider prereq : jreDeps) {
        objcProviderBuilder.addTransitiveAndPropagate(JRE_LIBRARY, prereq.get(LIBRARY));
    }
    XcodeProvider.Builder xcodeProviderBuilder = new XcodeProvider.Builder();
    XcodeSupport xcodeSupport = new XcodeSupport(ruleContext).addJreDependencies(xcodeProviderBuilder).addDependencies(xcodeProviderBuilder, new Attribute("deps", Mode.TARGET));
    ObjcProvider objcProvider = objcProviderBuilder.build();
    xcodeSupport.addXcodeSettings(xcodeProviderBuilder, objcProvider, LIBRARY_STATIC);
    J2ObjcMappingFileProvider j2ObjcMappingFileProvider = J2ObjcMappingFileProvider.union(ruleContext.getPrerequisites("deps", Mode.TARGET, J2ObjcMappingFileProvider.class));
    return new RuleConfiguredTargetBuilder(ruleContext).setFilesToBuild(NestedSetBuilder.<Artifact>emptySet(STABLE_ORDER)).add(RunfilesProvider.class, RunfilesProvider.EMPTY).addProvider(J2ObjcEntryClassProvider.class, j2ObjcEntryClassProvider).addProvider(J2ObjcMappingFileProvider.class, j2ObjcMappingFileProvider).addProvider(ObjcProvider.class, objcProvider).addProvider(XcodeProvider.class, xcodeProviderBuilder.build()).build();
}
Also used : NestedSetBuilder(com.google.devtools.build.lib.collect.nestedset.NestedSetBuilder) RuleConfiguredTargetBuilder(com.google.devtools.build.lib.analysis.RuleConfiguredTargetBuilder) RunfilesProvider(com.google.devtools.build.lib.analysis.RunfilesProvider) RuleConfiguredTargetBuilder(com.google.devtools.build.lib.analysis.RuleConfiguredTargetBuilder)

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