Example usage for com.google.common.collect ImmutableSet.Builder addAll

List of usage examples for com.google.common.collect ImmutableSet.Builder addAll

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableSet.Builder addAll.

Prototype

boolean addAll(Collection<? extends E> c);

Source Link

Document

Adds all of the elements in the specified collection to this set if they're not already present (optional operation).

Usage

From source file:com.facebook.buck.jvm.java.JavaLibraryClasspathProvider.java

public static ImmutableSet<Path> getOutputClasspathJars(JavaLibrary javaLibraryRule,
        SourcePathResolver resolver, Optional<SourcePath> outputJar) {
    ImmutableSet.Builder<Path> outputClasspathBuilder = ImmutableSet.builder();
    Iterable<JavaLibrary> javaExportedLibraryDeps;
    if (javaLibraryRule instanceof ExportDependencies) {
        javaExportedLibraryDeps = getJavaLibraryDeps(((ExportDependencies) javaLibraryRule).getExportedDeps());
    } else {//w  w  w .  j  a v  a 2  s.c  o m
        javaExportedLibraryDeps = Sets.newHashSet();
    }

    for (JavaLibrary rule : javaExportedLibraryDeps) {
        outputClasspathBuilder.addAll(rule.getOutputClasspaths());
    }

    if (outputJar.isPresent()) {
        outputClasspathBuilder.add(resolver.getAbsolutePath(outputJar.get()));
    }

    return outputClasspathBuilder.build();
}

From source file:com.facebook.buck.features.haskell.HaskellDescriptionUtils.java

/** Give a rule that will result in a ghci session for the target */
public static HaskellGhciRule requireGhciRule(BuildTarget buildTarget, ProjectFilesystem projectFilesystem,
        BuildRuleParams params, CellPathResolver cellPathResolver, ActionGraphBuilder graphBuilder,
        HaskellPlatform platform, CxxBuckConfig cxxBuckConfig, ImmutableSortedSet<BuildTarget> argDeps,
        PatternMatchedCollection<ImmutableSortedSet<BuildTarget>> argPlatformDeps, SourceSortedSet argSrcs,
        ImmutableSortedSet<BuildTarget> argPreloadDeps,
        PatternMatchedCollection<ImmutableSortedSet<BuildTarget>> argPlatformPreloadDeps,
        ImmutableList<String> argCompilerFlags, Optional<BuildTarget> argGhciBinDep,
        Optional<SourcePath> argGhciInit, ImmutableList<SourcePath> argExtraScriptTemplates,
        boolean hsProfile) {
    SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(graphBuilder);
    SourcePathResolver pathResolver = DefaultSourcePathResolver.from(ruleFinder);

    ImmutableSet.Builder<BuildRule> depsBuilder = ImmutableSet.builder();
    depsBuilder.addAll(CxxDeps.builder().addDeps(argDeps).addPlatformDeps(argPlatformDeps).build()
            .get(graphBuilder, platform.getCxxPlatform()));
    ImmutableSet<BuildRule> deps = depsBuilder.build();

    ImmutableSet.Builder<BuildRule> preloadDepsBuilder = ImmutableSet.builder();
    preloadDepsBuilder.addAll(CxxDeps.builder().addDeps(argPreloadDeps).addPlatformDeps(argPlatformPreloadDeps)
            .build().get(graphBuilder, platform.getCxxPlatform()));
    ImmutableSet<BuildRule> preloadDeps = preloadDepsBuilder.build();

    // Haskell visitor
    ImmutableSet.Builder<HaskellPackage> haskellPackages = ImmutableSet.builder();
    ImmutableSet.Builder<HaskellPackage> prebuiltHaskellPackages = ImmutableSet.builder();
    ImmutableSet.Builder<HaskellPackage> firstOrderHaskellPackages = ImmutableSet.builder();
    AbstractBreadthFirstTraversal<BuildRule> haskellVisitor = new AbstractBreadthFirstTraversal<BuildRule>(
            deps) {/*from  w  ww.j  a v a 2s .  c  om*/
        @Override
        public ImmutableSet<BuildRule> visit(BuildRule rule) {
            ImmutableSet.Builder<BuildRule> traverse = ImmutableSet.builder();
            if (rule instanceof HaskellLibrary || rule instanceof PrebuiltHaskellLibrary) {
                HaskellCompileDep haskellRule = (HaskellCompileDep) rule;
                HaskellCompileInput ci = haskellRule.getCompileInput(platform, Linker.LinkableDepType.STATIC,
                        hsProfile);

                if (params.getBuildDeps().contains(rule)) {
                    firstOrderHaskellPackages.addAll(ci.getPackages());
                }

                if (rule instanceof HaskellLibrary) {
                    haskellPackages.addAll(ci.getPackages());
                } else if (rule instanceof PrebuiltHaskellLibrary) {
                    prebuiltHaskellPackages.addAll(ci.getPackages());
                }

                traverse.addAll(haskellRule.getCompileDeps(platform));
            }

            return traverse.build();
        }
    };
    haskellVisitor.start();

    // Build the omnibus composition spec.
    HaskellGhciOmnibusSpec omnibusSpec = HaskellGhciDescription.getOmnibusSpec(buildTarget,
            platform.getCxxPlatform(), graphBuilder,
            NativeLinkables.getNativeLinkableRoots(
                    RichStream.from(deps).filter(NativeLinkable.class).toImmutableList(),
                    n -> n instanceof HaskellLibrary || n instanceof PrebuiltHaskellLibrary ? Optional.of(
                            n.getNativeLinkableExportedDepsForPlatform(platform.getCxxPlatform(), graphBuilder))
                            : Optional.empty()),
            // The preloaded deps form our excluded roots, which we need to keep them separate from
            // the omnibus library so that they can be `LD_PRELOAD`ed early.
            RichStream.from(preloadDeps).filter(NativeLinkable.class)
                    .collect(ImmutableMap.toImmutableMap(NativeLinkable::getBuildTarget, l -> l)));

    // Add an -rpath to the omnibus for shared library dependencies
    Path symlinkRelDir = HaskellGhciDescription.getSoLibsRelDir(buildTarget);
    ImmutableList.Builder<Arg> extraLinkFlags = ImmutableList.builder();
    extraLinkFlags.addAll(StringArg.from(Linkers.iXlinker("-rpath", String.format("%s/%s",
            platform.getCxxPlatform().getLd().resolve(graphBuilder).origin(), symlinkRelDir.toString()))));

    // Construct the omnibus shared library.
    BuildRule omnibusSharedObject = HaskellGhciDescription.requireOmnibusSharedObject(cellPathResolver,
            buildTarget, projectFilesystem, graphBuilder, platform.getCxxPlatform(), cxxBuckConfig,
            omnibusSpec.getBody().values(), omnibusSpec.getDeps().values(), extraLinkFlags.build());

    // Build up a map of all transitive shared libraries the the monolithic omnibus library depends
    // on (basically, stuff we couldn't statically link in).  At this point, this should *not* be
    // pulling in any excluded deps.
    SharedLibrariesBuilder sharedLibsBuilder = new SharedLibrariesBuilder();
    ImmutableMap<BuildTarget, NativeLinkable> transitiveDeps = NativeLinkables.getTransitiveNativeLinkables(
            platform.getCxxPlatform(), graphBuilder, omnibusSpec.getDeps().values());
    transitiveDeps.values().stream()
            // Skip statically linked libraries.
            .filter(l -> l.getPreferredLinkage(platform.getCxxPlatform(), graphBuilder) != Linkage.STATIC)
            .forEach(l -> sharedLibsBuilder.add(platform.getCxxPlatform(), l, graphBuilder));
    ImmutableSortedMap<String, SourcePath> sharedLibs = sharedLibsBuilder.build();

    // Build up a set of all transitive preload libs, which are the ones that have been "excluded"
    // from the omnibus link.  These are the ones we need to LD_PRELOAD.
    SharedLibrariesBuilder preloadLibsBuilder = new SharedLibrariesBuilder();
    omnibusSpec.getExcludedTransitiveDeps().values().stream()
            // Don't include shared libs for static libraries -- except for preload roots, which we
            // always link dynamically.
            .filter(l -> l.getPreferredLinkage(platform.getCxxPlatform(), graphBuilder) != Linkage.STATIC
                    || omnibusSpec.getExcludedRoots().containsKey(l.getBuildTarget()))
            .forEach(l -> preloadLibsBuilder.add(platform.getCxxPlatform(), l, graphBuilder));
    ImmutableSortedMap<String, SourcePath> preloadLibs = preloadLibsBuilder.build();

    HaskellSources srcs = HaskellSources.from(buildTarget, graphBuilder, pathResolver, ruleFinder, platform,
            "srcs", argSrcs);

    return HaskellGhciRule.from(buildTarget, projectFilesystem, params, ruleFinder, srcs, argCompilerFlags,
            argGhciBinDep.map(
                    target -> Objects.requireNonNull(graphBuilder.getRule(target).getSourcePathToOutput())),
            argGhciInit, omnibusSharedObject, sharedLibs, preloadLibs, firstOrderHaskellPackages.build(),
            haskellPackages.build(), prebuiltHaskellPackages.build(), hsProfile,
            platform.getGhciScriptTemplate().get(), argExtraScriptTemplates,
            platform.getGhciIservScriptTemplate().get(), platform.getGhciBinutils().get(),
            platform.getGhciGhc().get(), platform.getGhciIServ().get(), platform.getGhciIServProf().get(),
            platform.getGhciLib().get(), platform.getGhciCxx().get(), platform.getGhciCc().get(),
            platform.getGhciCpp().get(), platform.getGhciPackager().get());
}

From source file:edu.mit.streamjit.util.bytecode.DeadCodeElimination.java

/**
 * Returns all instructions that could follow the given instruction in an
 * execution.  The set may include start itself (if start is in a loop, for
 * example)./*  w w  w  .  j  a v  a  2s .co m*/
 * @param start the starting point
 * @return a set containing all instructions that follow start
 */
private static ImmutableSet<Instruction> followingInstructions(Instruction start) {
    ImmutableSet.Builder<Instruction> followers = ImmutableSet.builder();
    BasicBlock startBlock = start.getParent();
    int startIndex = startBlock.instructions().indexOf(start);
    followers.addAll(startBlock.instructions().subList(startIndex + 1, startBlock.instructions().size()));

    List<BasicBlock> worklist = Lists.newArrayList(startBlock.successors());
    for (int i = 0; i < worklist.size(); ++i) {
        followers.addAll(worklist.get(i).instructions());
        for (BasicBlock s : worklist.get(i).successors())
            if (!worklist.contains(s))
                worklist.add(s);
    }
    return followers.build();
}

From source file:com.facebook.buck.features.rust.RustCompileUtils.java

static Iterable<BuildTarget> getPlatformParseTimeDeps(RustPlatform rustPlatform) {
    ImmutableSet.Builder<BuildTarget> deps = ImmutableSet.builder();
    deps.addAll(rustPlatform.getRustCompiler().getParseTimeDeps());
    rustPlatform.getLinker().ifPresent(l -> deps.addAll(l.getParseTimeDeps()));
    deps.addAll(CxxPlatforms.getParseTimeDeps(rustPlatform.getCxxPlatform()));
    return deps.build();
}

From source file:com.facebook.buck.distributed.DistBuildUtil.java

/** Checks whether the given target command line arguments match the Stampede project whitelist */
public static boolean doTargetsMatchProjectWhitelist(List<String> commandArgs,
        ImmutableSet<String> projectWhitelist, BuckConfig buckConfig) {
    ImmutableSet.Builder<String> buildTargets = new ImmutableSet.Builder<>();
    for (String commandArg : commandArgs) {
        ImmutableSet<String> buildTargetForAliasAsString = AliasConfig.from(buckConfig)
                .getBuildTargetForAliasAsString(commandArg);
        if (buildTargetForAliasAsString.size() > 0) {
            buildTargets.addAll(buildTargetForAliasAsString);
        } else {/* w  ww.  ja va 2  s .  com*/
            // Target was not an alias
            if (!commandArg.startsWith("//")) {
                commandArg = "//" + commandArg;
            }

            buildTargets.add(commandArg);
        }
    }

    return doTargetsMatchProjectWhitelist(buildTargets.build(), projectWhitelist);
}

From source file:com.facebook.buck.android.AndroidPlatformTarget.java

/**
 * Given the path to the Android SDK as well as the platform path within the Android SDK,
 * find all the files needed to create the {@link AndroidPlatformTarget}, assuming that the
 * organization of the Android SDK conforms to the ordinary directory structure.
 *///from   ww w  . j  av  a  2  s  .co m
@VisibleForTesting
static AndroidPlatformTarget createFromDefaultDirectoryStructure(String name,
        AndroidDirectoryResolver androidDirectoryResolver, String platformDirectoryPath,
        Set<Path> additionalJarPaths, Optional<Path> aaptOverride) {
    Path androidSdkDir = androidDirectoryResolver.getSdkOrThrow();
    if (!androidSdkDir.isAbsolute()) {
        throw new HumanReadableException("Path to Android SDK must be absolute but was: %s.", androidSdkDir);
    }

    Path platformDirectory = androidSdkDir.resolve(platformDirectoryPath);
    Path androidJar = platformDirectory.resolve("android.jar");

    // Add any libraries found in the optional directory under the Android SDK directory. These
    // go at the head of the bootclasspath before any additional jars.
    File optionalDirectory = platformDirectory.resolve("optional").toFile();
    if (optionalDirectory.exists() && optionalDirectory.isDirectory()) {
        String[] optionalDirList = optionalDirectory.list(new AddonFilter());
        if (optionalDirList != null) {
            Arrays.sort(optionalDirList);
            ImmutableSet.Builder<Path> additionalJars = ImmutableSet.builder();
            for (String file : optionalDirList) {
                additionalJars.add(optionalDirectory.toPath().resolve(file));
            }
            additionalJars.addAll(additionalJarPaths);
            additionalJarPaths = additionalJars.build();
        }
    }

    LinkedList<Path> bootclasspathEntries = Lists.newLinkedList(additionalJarPaths);

    // Make sure android.jar is at the front of the bootclasspath.
    bootclasspathEntries.addFirst(androidJar);

    // This is the directory under the Android SDK directory that contains the dx script, jack,
    // jill, and binaries.
    Path buildToolsDir = androidDirectoryResolver.getBuildToolsOrThrow();

    // This is the directory under the Android SDK directory that contains the aapt, aidl, and
    // zipalign binaries. Before Android SDK Build-tools 23.0.0_rc1, this was the same as
    // buildToolsDir above.
    Path buildToolsBinDir;
    if (buildToolsDir.resolve("bin").toFile().exists()) {
        // Android SDK Build-tools >= 23.0.0_rc1 have executables under a new bin directory.
        buildToolsBinDir = buildToolsDir.resolve("bin");
    } else {
        // Android SDK Build-tools < 23.0.0_rc1 have executables under the build-tools directory.
        buildToolsBinDir = buildToolsDir;
    }

    Path zipAlignExecutable = androidSdkDir.resolve("tools/zipalign").toAbsolutePath();
    if (!zipAlignExecutable.toFile().exists()) {
        // Android SDK Build-tools >= 19.1.0 have zipalign under the build-tools directory.
        zipAlignExecutable = androidSdkDir.resolve(buildToolsBinDir).resolve("zipalign").toAbsolutePath();
    }

    Path androidFrameworkIdlFile = platformDirectory.resolve("framework.aidl");
    Path proguardJar = androidSdkDir.resolve("tools/proguard/lib/proguard.jar");
    Path proguardConfig = androidSdkDir.resolve("tools/proguard/proguard-android.txt");
    Path optimizedProguardConfig = androidSdkDir.resolve("tools/proguard/proguard-android-optimize.txt");

    return new AndroidPlatformTarget(name, androidJar.toAbsolutePath(), bootclasspathEntries,
            aaptOverride.orElse(androidSdkDir.resolve(buildToolsBinDir).resolve("aapt").toAbsolutePath()),
            androidSdkDir.resolve("platform-tools/adb").toAbsolutePath(),
            androidSdkDir.resolve(buildToolsBinDir).resolve("aidl").toAbsolutePath(), zipAlignExecutable,
            buildToolsDir.resolve(Platform.detect() == Platform.WINDOWS ? "dx.bat" : "dx").toAbsolutePath(),
            androidFrameworkIdlFile, proguardJar, proguardConfig, optimizedProguardConfig,
            androidDirectoryResolver);
}

From source file:com.wrmsr.wava.analyze.Analyses.java

public static Set<Name> getReferencedNames(Node root) {
    ImmutableSet.Builder<Name> builder = ImmutableSet.builder();
    Visitors.preWalk(root, new Visitor<Void, Void>() {
        @Override//  w w  w  .  ja  v a 2  s  .  com
        public Void visitBreak(Break node, Void context) {
            builder.add(node.getTarget());
            return null;
        }

        @Override
        public Void visitBreakTable(BreakTable node, Void context) {
            builder.addAll(node.getTargets());
            builder.add(node.getDefaultTarget());
            return null;
        }
    }, null);
    return builder.build();
}

From source file:com.netflix.genie.web.controllers.DtoConverters.java

/**
 * Convert a given V4 {@code criterion} to the equivalent representation in V3 set of tags.
 *
 * @param criterion The {@link Criterion} to convert
 * @return A set of String's representing the criterion tags as they would have looked in V3
 *//*from  www  .ja v  a 2s  . c o  m*/
public static ImmutableSet<String> toV3CriterionTags(final Criterion criterion) {
    final ImmutableSet.Builder<String> tags = ImmutableSet.builder();
    criterion.getId().ifPresent(id -> tags.add(GENIE_ID_PREFIX + id));
    criterion.getName().ifPresent(name -> tags.add(GENIE_NAME_PREFIX + name));
    tags.addAll(criterion.getTags());
    return tags.build();
}

From source file:com.google.devtools.build.lib.rules.cpp.CcCommon.java

/**
 * Creates the feature configuration for a given rule.
 *
 * @param ruleContext the context of the rule we want the feature configuration for.
 * @param ruleSpecificRequestedFeatures features that will be requested, and thus be always
 * enabled if the toolchain supports them.
 * @param ruleSpecificUnsupportedFeatures features that are not supported in the current context.
 * @param sourceCategory the source category for this build.
 * @return the feature configuration for the given {@code ruleContext}.
 *//* ww  w . j av  a  2 s .  co m*/
public static FeatureConfiguration configureFeatures(RuleContext ruleContext,
        Set<String> ruleSpecificRequestedFeatures, Set<String> ruleSpecificUnsupportedFeatures,
        SourceCategory sourceCategory, CcToolchainProvider toolchain) {
    ImmutableSet.Builder<String> unsupportedFeaturesBuilder = ImmutableSet.builder();
    unsupportedFeaturesBuilder.addAll(ruleSpecificUnsupportedFeatures);
    if (!toolchain.supportsHeaderParsing()) {
        // TODO(bazel-team): Remove once supports_header_parsing has been removed from the
        // cc_toolchain rule.
        unsupportedFeaturesBuilder.add(CppRuleClasses.PARSE_HEADERS);
        unsupportedFeaturesBuilder.add(CppRuleClasses.PREPROCESS_HEADERS);
    }
    if (toolchain.getCppCompilationContext().getCppModuleMap() == null) {
        unsupportedFeaturesBuilder.add(CppRuleClasses.MODULE_MAPS);
    }
    Set<String> unsupportedFeatures = unsupportedFeaturesBuilder.build();
    ImmutableSet.Builder<String> requestedFeatures = ImmutableSet.builder();
    for (String feature : Iterables.concat(ImmutableSet.of(toolchain.getCompilationMode().toString()),
            ImmutableSet.of(getHostOrNonHostFeature(ruleContext)), DEFAULT_FEATURES,
            ruleContext.getFeatures())) {
        if (!unsupportedFeatures.contains(feature)) {
            requestedFeatures.add(feature);
        }
    }
    requestedFeatures.addAll(ruleSpecificRequestedFeatures);

    requestedFeatures.addAll(sourceCategory.getActionConfigSet());

    FeatureConfiguration configuration = toolchain.getFeatures()
            .getFeatureConfiguration(requestedFeatures.build());
    for (String feature : unsupportedFeatures) {
        if (configuration.isEnabled(feature)) {
            ruleContext.ruleError("The C++ toolchain '"
                    + ruleContext.getPrerequisite(":cc_toolchain", Mode.TARGET).getLabel()
                    + "' unconditionally implies feature '" + feature + "', which is unsupported by this rule. "
                    + "This is most likely a misconfiguration in the C++ toolchain.");
        }
    }
    return configuration;
}

From source file:org.daisy.maven.xspec.XSpecRunner.java

public static Set<File> listXSpecFilesRecursively(File directory) {
    ImmutableSet.Builder<File> builder = new ImmutableSet.Builder<File>();
    if (directory.isDirectory())
        for (File file : directory.listFiles()) {
            if (file.isDirectory())
                builder.addAll(listXSpecFilesRecursively(file));
            else if (file.getName().endsWith(".xspec"))
                builder.add(file);//from   ww w.ja  va  2s  . com
        }
    return builder.build();
}