Example usage for com.google.common.collect ImmutableMultimap builder

List of usage examples for com.google.common.collect ImmutableMultimap builder

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableMultimap builder.

Prototype

public static <K, V> Builder<K, V> builder() 

Source Link

Document

Returns a new builder.

Usage

From source file:com.facebook.presto.sql.analyzer.TupleAnalyzer.java

private List<FieldOrExpression> analyzeOrderBy(QuerySpecification node, TupleDescriptor tupleDescriptor,
        AnalysisContext context, List<FieldOrExpression> outputExpressions) {
    List<SortItem> items = node.getOrderBy();

    ImmutableList.Builder<FieldOrExpression> orderByExpressionsBuilder = ImmutableList.builder();

    if (!items.isEmpty()) {
        // Compute aliased output terms so we can resolve order by expressions against them first
        ImmutableMultimap.Builder<QualifiedName, Expression> byAliasBuilder = ImmutableMultimap.builder();
        for (SelectItem item : node.getSelect().getSelectItems()) {
            if (item instanceof SingleColumn) {
                Optional<String> alias = ((SingleColumn) item).getAlias();
                if (alias.isPresent()) {
                    byAliasBuilder.put(QualifiedName.of(alias.get()), ((SingleColumn) item).getExpression()); // TODO: need to know if alias was quoted
                }/*from  w  w  w  . jav  a  2 s .  co  m*/
            }
        }
        Multimap<QualifiedName, Expression> byAlias = byAliasBuilder.build();

        for (SortItem item : items) {
            Expression expression = item.getSortKey();

            FieldOrExpression orderByExpression = null;
            if (expression instanceof QualifiedNameReference
                    && !((QualifiedNameReference) expression).getName().getPrefix().isPresent()) {
                // if this is a simple name reference, try to resolve against output columns

                QualifiedName name = ((QualifiedNameReference) expression).getName();
                Collection<Expression> expressions = byAlias.get(name);
                if (expressions.size() > 1) {
                    throw new SemanticException(AMBIGUOUS_ATTRIBUTE, expression,
                            "'%s' in ORDER BY is ambiguous", name.getSuffix());
                } else if (expressions.size() == 1) {
                    orderByExpression = new FieldOrExpression(Iterables.getOnlyElement(expressions));
                }

                // otherwise, couldn't resolve name against output aliases, so fall through...
            } else if (expression instanceof LongLiteral) {
                // this is an ordinal in the output tuple

                long ordinal = ((LongLiteral) expression).getValue();
                if (ordinal < 1 || ordinal > outputExpressions.size()) {
                    throw new SemanticException(INVALID_ORDINAL, expression,
                            "ORDER BY position %s is not in select list", ordinal);
                }

                orderByExpression = outputExpressions.get((int) (ordinal - 1));

                if (orderByExpression.isExpression()) {
                    Type type = analysis.getType(orderByExpression.getExpression());
                    if (!type.isOrderable()) {
                        throw new SemanticException(TYPE_MISMATCH, node,
                                "The type of expression in position %s is not orderable (actual: %s), and therefore cannot be used in ORDER BY: %s",
                                ordinal, type, orderByExpression);
                    }
                } else {
                    Type type = tupleDescriptor.getFieldByIndex(orderByExpression.getFieldIndex()).getType();
                    if (!type.isOrderable()) {
                        throw new SemanticException(TYPE_MISMATCH, node,
                                "The type of expression in position %s is not orderable (actual: %s), and therefore cannot be used in ORDER BY",
                                ordinal, type);
                    }
                }
            }

            // otherwise, just use the expression as is
            if (orderByExpression == null) {
                orderByExpression = new FieldOrExpression(expression);
            }

            if (orderByExpression.isExpression()) {
                ExpressionAnalysis expressionAnalysis = analyzeExpression(orderByExpression.getExpression(),
                        tupleDescriptor, context);
                analysis.addInPredicates(node, expressionAnalysis.getSubqueryInPredicates());

                Type type = expressionAnalysis.getType(orderByExpression.getExpression());
                if (!type.isOrderable()) {
                    throw new SemanticException(TYPE_MISMATCH, node,
                            "Type %s is not orderable, and therefore cannot be used in ORDER BY: %s", type,
                            expression);
                }
            }

            orderByExpressionsBuilder.add(orderByExpression);
        }
    }

    List<FieldOrExpression> orderByExpressions = orderByExpressionsBuilder.build();
    analysis.setOrderByExpressions(node, orderByExpressions);

    if (node.getSelect().isDistinct() && !outputExpressions.containsAll(orderByExpressions)) {
        throw new SemanticException(ORDER_BY_MUST_BE_IN_SELECT, node.getSelect(),
                "For SELECT DISTINCT, ORDER BY expressions must appear in select list");
    }
    return orderByExpressions;
}

From source file:com.facebook.buck.features.apple.project.ProjectGenerator.java

private ImmutableMultimap<String, ImmutableList<String>> convertPlatformFlags(TargetNode<?> node,
        Iterable<PatternMatchedCollection<ImmutableList<StringWithMacros>>> matchers) {
    ImmutableMultimap.Builder<String, ImmutableList<String>> flagsBuilder = ImmutableMultimap.builder();

    for (PatternMatchedCollection<ImmutableList<StringWithMacros>> matcher : matchers) {
        for (Flavor flavor : appleCxxFlavors) {
            String platform = flavor.toString();
            for (ImmutableList<StringWithMacros> flags : matcher.getMatchingValues(platform)) {
                flagsBuilder.put(platform, convertStringWithMacros(node, flags));
            }//from ww  w.  j  av  a2  s .c  o  m
        }
    }
    return flagsBuilder.build();
}

From source file:com.google.devtools.build.lib.skyframe.SkyframeExecutor.java

/**
 * Returns a map from {@link Dependency} inputs to the {@link ConfiguredTarget}s corresponding
 * to those dependencies./*from  w w w  .  ja  v  a2  s .  co m*/
 *
 * <p>For use for legacy support and tests calling through {@code BuildView} only.
 *
 * <p>If a requested configured target is in error, the corresponding value is omitted from the
 * returned list.
 */
@ThreadSafety.ThreadSafe
public ImmutableMultimap<Dependency, ConfiguredTarget> getConfiguredTargetMap(EventHandler eventHandler,
        BuildConfiguration originalConfig, Iterable<Dependency> keys, boolean useOriginalConfig) {
    checkActive();

    Multimap<Dependency, BuildConfiguration> configs;
    if (originalConfig != null) {

        if (useOriginalConfig) {
            // This flag is used because of some unfortunate complexity in the configuration machinery:
            // Most callers of this method pass a <Label, Configuration> pair to directly create a
            // ConfiguredTarget from, but happen to use the Dependency data structure to pass that
            // info (even though the data has nothing to do with dependencies). If this configuration
            // includes a split transition, a dynamic configuration created from it will *not*
            // include that transition (because dynamic configurations don't embed transitions to
            // other configurations. In that case, we need to preserve the original configuration.
            // TODO(bazel-team); make this unnecessary once split transition logic is properly ported
            // out of configurations.
            configs = ArrayListMultimap.<Dependency, BuildConfiguration>create();
            configs.put(Iterables.getOnlyElement(keys), originalConfig);
        } else {
            configs = getConfigurations(eventHandler, originalConfig.getOptions(), keys);
        }
    } else {
        configs = ArrayListMultimap.<Dependency, BuildConfiguration>create();
        for (Dependency key : keys) {
            configs.put(key, null);
        }
    }

    final List<SkyKey> skyKeys = new ArrayList<>();
    for (Dependency key : keys) {
        if (!configs.containsKey(key)) {
            // If we couldn't compute a configuration for this target, the target was in error (e.g.
            // it couldn't be loaded). Exclude it from the results.
            continue;
        }
        for (BuildConfiguration depConfig : configs.get(key)) {
            skyKeys.add(ConfiguredTargetValue.key(key.getLabel(), depConfig));
            for (AspectDescriptor aspectDescriptor : key.getAspects()) {
                skyKeys.add(ActionLookupValue.key(
                        AspectValue.createAspectKey(key.getLabel(), depConfig, aspectDescriptor, depConfig)));
            }
        }
    }

    EvaluationResult<SkyValue> result = evaluateSkyKeys(eventHandler, skyKeys);
    for (Map.Entry<SkyKey, ErrorInfo> entry : result.errorMap().entrySet()) {
        reportCycles(eventHandler, entry.getValue().getCycleInfo(), entry.getKey());
    }

    ImmutableMultimap.Builder<Dependency, ConfiguredTarget> cts = ImmutableMultimap
            .<Dependency, ConfiguredTarget>builder();

    DependentNodeLoop: for (Dependency key : keys) {
        if (!configs.containsKey(key)) {
            // If we couldn't compute a configuration for this target, the target was in error (e.g.
            // it couldn't be loaded). Exclude it from the results.
            continue;
        }
        for (BuildConfiguration depConfig : configs.get(key)) {
            SkyKey configuredTargetKey = ConfiguredTargetValue.key(key.getLabel(), depConfig);
            if (result.get(configuredTargetKey) == null) {
                continue;
            }

            ConfiguredTarget configuredTarget = ((ConfiguredTargetValue) result.get(configuredTargetKey))
                    .getConfiguredTarget();
            List<ConfiguredAspect> configuredAspects = new ArrayList<>();

            for (AspectDescriptor aspectDescriptor : key.getAspects()) {
                SkyKey aspectKey = ActionLookupValue.key(
                        AspectValue.createAspectKey(key.getLabel(), depConfig, aspectDescriptor, depConfig));
                if (result.get(aspectKey) == null) {
                    continue DependentNodeLoop;
                }

                configuredAspects.add(((AspectValue) result.get(aspectKey)).getConfiguredAspect());
            }

            try {
                cts.put(key, MergedConfiguredTarget.of(configuredTarget, configuredAspects));
            } catch (DuplicateException e) {
                throw new IllegalStateException(
                        String.format("Error creating %s", configuredTarget.getTarget().getLabel()), e);
            }
        }
    }

    return cts.build();
}

From source file:com.facebook.buck.apple.project_generator.ProjectGenerator.java

private PBXNativeTarget generateBinaryTarget(PBXProject project,
        Optional<? extends TargetNode<? extends HasAppleBundleFields, ?>> bundle,
        TargetNode<? extends CxxLibraryDescription.Arg, ?> targetNode, ProductType productType,
        String productOutputFormat, Optional<Path> infoPlistOptional, boolean includeFrameworks,
        ImmutableSet<AppleResourceDescription.Arg> recursiveResources,
        ImmutableSet<AppleResourceDescription.Arg> directResources,
        ImmutableSet<AppleAssetCatalogDescription.Arg> recursiveAssetCatalogs,
        ImmutableSet<AppleAssetCatalogDescription.Arg> directAssetCatalogs,
        ImmutableSet<AppleWrapperResourceArg> wrapperResources,
        Optional<Iterable<PBXBuildPhase>> copyFilesPhases,
        Optional<TargetNode<AppleBundleDescription.Arg, ?>> bundleLoaderNode) throws IOException {

    LOG.debug("Generating binary target for node %s", targetNode);

    TargetNode<?, ?> buildTargetNode = bundle.isPresent() ? bundle.get() : targetNode;
    final BuildTarget buildTarget = buildTargetNode.getBuildTarget();

    String buildTargetName = getProductNameForBuildTarget(buildTarget);
    CxxLibraryDescription.Arg arg = targetNode.getConstructorArg();
    NewNativeTargetProjectMutator mutator = new NewNativeTargetProjectMutator(pathRelativizer,
            sourcePathResolver);//from   w  ww .  j  a va 2  s .  c om
    ImmutableSet<SourcePath> exportedHeaders = ImmutableSet.copyOf(getHeaderSourcePaths(arg.exportedHeaders));
    ImmutableSet<SourcePath> headers = ImmutableSet.copyOf(getHeaderSourcePaths(arg.headers));
    ImmutableMap<CxxSource.Type, ImmutableList<String>> langPreprocessorFlags = targetNode
            .getConstructorArg().langPreprocessorFlags;

    mutator.setTargetName(getXcodeTargetName(buildTarget)).setProduct(productType, buildTargetName,
            Paths.get(String.format(productOutputFormat, buildTargetName)));

    boolean isFocusedOnTarget = shouldIncludeBuildTargetIntoFocusedProject(focusModules, buildTarget);
    if (isFocusedOnTarget) {
        mutator.setLangPreprocessorFlags(langPreprocessorFlags).setPublicHeaders(exportedHeaders)
                .setPrefixHeader(arg.prefixHeader).setSourcesWithFlags(ImmutableSet.copyOf(arg.srcs))
                .setPrivateHeaders(headers).setRecursiveResources(recursiveResources)
                .setDirectResources(directResources).setWrapperResources(wrapperResources);
    }

    if (bundle.isPresent() && isFocusedOnTarget) {
        HasAppleBundleFields bundleArg = bundle.get().getConstructorArg();
        mutator.setInfoPlist(Optional.of(bundleArg.getInfoPlist()));
    }

    mutator.setBridgingHeader(arg.bridgingHeader);

    Optional<TargetNode<AppleNativeTargetDescriptionArg, ?>> appleTargetNode = targetNode
            .castArg(AppleNativeTargetDescriptionArg.class);
    if (appleTargetNode.isPresent() && isFocusedOnTarget) {
        AppleNativeTargetDescriptionArg appleArg = appleTargetNode.get().getConstructorArg();
        mutator = mutator.setExtraXcodeSources(ImmutableSet.copyOf(appleArg.extraXcodeSources));
    }

    if (options.contains(Option.CREATE_DIRECTORY_STRUCTURE) && isFocusedOnTarget) {
        mutator.setTargetGroupPath(StreamSupport.stream(buildTarget.getBasePath().spliterator(), false)
                .map(Object::toString).collect(MoreCollectors.toImmutableList()));
    }

    if (!recursiveAssetCatalogs.isEmpty() && isFocusedOnTarget) {
        mutator.setRecursiveAssetCatalogs(recursiveAssetCatalogs);
    }

    if (!directAssetCatalogs.isEmpty() && isFocusedOnTarget) {
        mutator.setDirectAssetCatalogs(directAssetCatalogs);
    }

    if (includeFrameworks && isFocusedOnTarget) {
        ImmutableSet.Builder<FrameworkPath> frameworksBuilder = ImmutableSet.builder();
        frameworksBuilder.addAll(targetNode.getConstructorArg().frameworks);
        frameworksBuilder.addAll(targetNode.getConstructorArg().libraries);
        frameworksBuilder.addAll(collectRecursiveFrameworkDependencies(ImmutableList.of(targetNode)));
        mutator.setFrameworks(frameworksBuilder.build());

        mutator.setArchives(collectRecursiveLibraryDependencies(ImmutableList.of(targetNode)));
    }

    // TODO(Task #3772930): Go through all dependencies of the rule
    // and add any shell script rules here
    ImmutableList.Builder<TargetNode<?, ?>> preScriptPhases = ImmutableList.builder();
    ImmutableList.Builder<TargetNode<?, ?>> postScriptPhases = ImmutableList.builder();
    if (bundle.isPresent() && targetNode != bundle.get() && isFocusedOnTarget) {
        collectBuildScriptDependencies(targetGraph.getAll(bundle.get().getDeclaredDeps()), preScriptPhases,
                postScriptPhases);
    }
    collectBuildScriptDependencies(targetGraph.getAll(targetNode.getDeclaredDeps()), preScriptPhases,
            postScriptPhases);
    if (isFocusedOnTarget) {
        mutator.setPreBuildRunScriptPhasesFromTargetNodes(preScriptPhases.build());
        if (copyFilesPhases.isPresent()) {
            mutator.setCopyFilesPhases(copyFilesPhases.get());
        }
        mutator.setPostBuildRunScriptPhasesFromTargetNodes(postScriptPhases.build());
    }

    NewNativeTargetProjectMutator.Result targetBuilderResult;
    targetBuilderResult = mutator.buildTargetAndAddToProject(project, isFocusedOnTarget);
    Optional<PBXGroup> targetGroup = targetBuilderResult.targetGroup;

    if (isFocusedOnTarget) {
        SourceTreePath buckFilePath = new SourceTreePath(PBXReference.SourceTree.SOURCE_ROOT,
                pathRelativizer.outputPathToBuildTargetPath(buildTarget).resolve(buildFileName),
                Optional.empty());
        PBXFileReference buckReference = targetGroup.get()
                .getOrCreateFileReferenceBySourceTreePath(buckFilePath);
        buckReference.setExplicitFileType(Optional.of("text.script.python"));
    }

    // -- configurations
    ImmutableMap.Builder<String, String> extraSettingsBuilder = ImmutableMap.builder();
    extraSettingsBuilder.put("TARGET_NAME", buildTargetName).put("SRCROOT",
            pathRelativizer.outputPathToBuildTargetPath(buildTarget).toString());
    if (productType == ProductType.UI_TEST && isFocusedOnTarget) {
        if (bundleLoaderNode.isPresent()) {
            BuildTarget testTarget = bundleLoaderNode.get().getBuildTarget();
            extraSettingsBuilder.put("TEST_TARGET_NAME", getXcodeTargetName(testTarget));
        } else {
            throw new HumanReadableException(
                    "The test rule '%s' is configured with 'is_ui_test' but has no test_host_app",
                    buildTargetName);
        }
    } else if (bundleLoaderNode.isPresent() && isFocusedOnTarget) {
        TargetNode<AppleBundleDescription.Arg, ?> bundleLoader = bundleLoaderNode.get();
        String bundleLoaderProductName = getProductNameForBuildTarget(bundleLoader.getBuildTarget());
        String bundleLoaderBundleName = bundleLoaderProductName + "."
                + getExtensionString(bundleLoader.getConstructorArg().getExtension());
        // NOTE(grp): This is a hack. We need to support both deep (OS X) and flat (iOS)
        // style bundles for the bundle loader, but at this point we don't know what platform
        // the bundle loader (or current target) is going to be built for. However, we can be
        // sure that it's the same as the target (presumably a test) we're building right now.
        //
        // Using that knowledge, we can do build setting tricks to defer choosing the bundle
        // loader path until Xcode build time, when the platform is known. There's no build
        // setting that conclusively says whether the current platform uses deep bundles:
        // that would be too easy. But in the cases we care about (unit test bundles), the
        // current bundle will have a style matching the style of the bundle loader app, so
        // we can take advantage of that to do the determination.
        //
        // Unfortunately, the build setting for the bundle structure (CONTENTS_FOLDER_PATH)
        // includes the WRAPPER_NAME, so we can't just interpolate that in. Instead, we have
        // to use another trick with build setting operations and evaluation. By using the
        // $(:file) operation, we can extract the last component of the contents path: either
        // "Contents" or the current bundle name. Then, we can interpolate with that expected
        // result in the build setting name to conditionally choose a different loader path.

        // The conditional that decdies which path is used. This is a complex Xcode build setting
        // expression that expands to one of two values, depending on the last path component of
        // the CONTENTS_FOLDER_PATH variable. As described above, this will be either "Contents"
        // for deep bundles or the bundle file name itself for flat bundles. Finally, to santiize
        // the potentially invalid build setting names from the bundle file name, it converts that
        // to an identifier. We rely on BUNDLE_LOADER_BUNDLE_STYLE_CONDITIONAL_<bundle file name>
        // being undefined (and thus expanding to nothing) for the path resolution to work.
        //
        // The operations on the CONTENTS_FOLDER_PATH are documented here:
        // http://codeworkshop.net/posts/xcode-build-setting-transformations
        String bundleLoaderOutputPathConditional = "$(BUNDLE_LOADER_BUNDLE_STYLE_CONDITIONAL_$(CONTENTS_FOLDER_PATH:file:identifier))";

        // If the $(CONTENTS_FOLDER_PATH:file:identifier) expands to this, we add the deep bundle
        // path into the bundle loader. See above for the case when it will expand to this value.
        String bundleLoaderOutputPathDeepSetting = "BUNDLE_LOADER_BUNDLE_STYLE_CONDITIONAL_Contents";
        String bundleLoaderOutputPathDeepValue = "Contents/MacOS/";

        String bundleLoaderOutputPathValue = Joiner.on('/').join(getTargetOutputPath(bundleLoader),
                bundleLoaderBundleName, bundleLoaderOutputPathConditional, bundleLoaderProductName);

        extraSettingsBuilder.put(bundleLoaderOutputPathDeepSetting, bundleLoaderOutputPathDeepValue)
                .put("BUNDLE_LOADER", bundleLoaderOutputPathValue).put("TEST_HOST", "$(BUNDLE_LOADER)");
    }
    if (infoPlistOptional.isPresent()) {
        Path infoPlistPath = pathRelativizer.outputDirToRootRelative(infoPlistOptional.get());
        extraSettingsBuilder.put("INFOPLIST_FILE", infoPlistPath.toString());
    }
    if (arg.bridgingHeader.isPresent()) {
        Path bridgingHeaderPath = pathRelativizer
                .outputDirToRootRelative(sourcePathResolver.apply(arg.bridgingHeader.get()));
        extraSettingsBuilder.put("SWIFT_OBJC_BRIDGING_HEADER",
                Joiner.on('/').join("$(SRCROOT)", bridgingHeaderPath.toString()));
    }
    Optional<String> swiftVersion = swiftBuckConfig.getVersion();
    if (swiftVersion.isPresent()) {
        extraSettingsBuilder.put("SWIFT_VERSION", swiftVersion.get());
    }
    Optional<SourcePath> prefixHeaderOptional = targetNode.getConstructorArg().prefixHeader;
    if (prefixHeaderOptional.isPresent()) {
        Path prefixHeaderRelative = sourcePathResolver.apply(prefixHeaderOptional.get());
        Path prefixHeaderPath = pathRelativizer.outputDirToRootRelative(prefixHeaderRelative);
        extraSettingsBuilder.put("GCC_PREFIX_HEADER", prefixHeaderPath.toString());
        extraSettingsBuilder.put("GCC_PRECOMPILE_PREFIX_HEADER", "YES");
    }
    extraSettingsBuilder.put("USE_HEADERMAP", "NO");

    ImmutableMap.Builder<String, String> defaultSettingsBuilder = ImmutableMap.builder();
    defaultSettingsBuilder.put("REPO_ROOT",
            projectFilesystem.getRootPath().toAbsolutePath().normalize().toString());
    defaultSettingsBuilder.put(PRODUCT_NAME, getProductName(buildTargetNode, buildTarget));
    if (bundle.isPresent()) {
        defaultSettingsBuilder.put("WRAPPER_EXTENSION",
                getExtensionString(bundle.get().getConstructorArg().getExtension()));
    }

    // We use BUILT_PRODUCTS_DIR as the root for the everything being built. Target-
    // specific output is placed within CONFIGURATION_BUILD_DIR, inside BUILT_PRODUCTS_DIR.
    // That allows Copy Files build phases to reference files in the CONFIGURATION_BUILD_DIR
    // of other targets by using paths relative to the target-independent BUILT_PRODUCTS_DIR.
    defaultSettingsBuilder.put("BUILT_PRODUCTS_DIR",
            // $EFFECTIVE_PLATFORM_NAME starts with a dash, so this expands to something like:
            // $SYMROOT/Debug-iphonesimulator
            Joiner.on('/').join("$SYMROOT", "$CONFIGURATION$EFFECTIVE_PLATFORM_NAME"));
    defaultSettingsBuilder.put("CONFIGURATION_BUILD_DIR", "$BUILT_PRODUCTS_DIR");
    boolean nodeIsAppleLibrary = targetNode.getDescription() instanceof AppleLibraryDescription;
    boolean nodeIsCxxLibrary = targetNode.getDescription() instanceof CxxLibraryDescription;
    if (!bundle.isPresent() && (nodeIsAppleLibrary || nodeIsCxxLibrary)) {
        defaultSettingsBuilder.put("EXECUTABLE_PREFIX", "lib");
    }

    ImmutableMap.Builder<String, String> appendConfigsBuilder = ImmutableMap.builder();

    if (isFocusedOnTarget) {
        ImmutableSet<Path> recursiveHeaderSearchPaths = collectRecursiveHeaderSearchPaths(targetNode);
        ImmutableSet<Path> headerMapBases = recursiveHeaderSearchPaths.isEmpty() ? ImmutableSet.of()
                : ImmutableSet.of(pathRelativizer
                        .outputDirToRootRelative(buildTargetNode.getFilesystem().getBuckPaths().getBuckOut()));

        appendConfigsBuilder
                .put("HEADER_SEARCH_PATHS",
                        Joiner.on(' ').join(Iterables.concat(recursiveHeaderSearchPaths, headerMapBases)))
                .put("LIBRARY_SEARCH_PATHS",
                        Joiner.on(' ').join(collectRecursiveLibrarySearchPaths(ImmutableSet.of(targetNode))))
                .put("FRAMEWORK_SEARCH_PATHS", Joiner.on(' ')
                        .join(collectRecursiveFrameworkSearchPaths(ImmutableList.of(targetNode))));

        Iterable<String> otherCFlags = Iterables.concat(cxxBuckConfig.getFlags("cflags").orElse(DEFAULT_CFLAGS),
                collectRecursiveExportedPreprocessorFlags(ImmutableList.of(targetNode)),
                targetNode.getConstructorArg().compilerFlags, targetNode.getConstructorArg().preprocessorFlags);
        Iterable<String> otherCxxFlags = Iterables.concat(
                cxxBuckConfig.getFlags("cxxflags").orElse(DEFAULT_CXXFLAGS),
                collectRecursiveExportedPreprocessorFlags(ImmutableList.of(targetNode)),
                targetNode.getConstructorArg().compilerFlags, targetNode.getConstructorArg().preprocessorFlags);
        Iterable<String> otherLdFlags = Iterables.concat(targetNode.getConstructorArg().linkerFlags,
                collectRecursiveExportedLinkerFlags(ImmutableList.of(targetNode)));

        appendConfigsBuilder
                .put("OTHER_CFLAGS",
                        Joiner.on(' ').join(Iterables.transform(otherCFlags, Escaper.BASH_ESCAPER)))
                .put("OTHER_CPLUSPLUSFLAGS",
                        Joiner.on(' ').join(Iterables.transform(otherCxxFlags, Escaper.BASH_ESCAPER)))
                .put("OTHER_LDFLAGS",
                        Joiner.on(' ').join(Iterables.transform(otherLdFlags, Escaper.BASH_ESCAPER)));

        ImmutableMultimap.Builder<String, ImmutableList<String>> platformFlagsBuilder = ImmutableMultimap
                .builder();
        for (Pair<Pattern, ImmutableList<String>> flags : Iterables.concat(
                targetNode.getConstructorArg().platformCompilerFlags.getPatternsAndValues(),
                targetNode.getConstructorArg().platformPreprocessorFlags.getPatternsAndValues(),
                collectRecursiveExportedPlatformPreprocessorFlags(ImmutableList.of(targetNode)))) {
            String sdk = flags.getFirst().pattern().replaceAll("[*.]", "");
            platformFlagsBuilder.put(sdk, flags.getSecond());
        }
        ImmutableMultimap<String, ImmutableList<String>> platformFlags = platformFlagsBuilder.build();
        for (String sdk : platformFlags.keySet()) {
            appendConfigsBuilder.put(String.format("OTHER_CFLAGS[sdk=*%s*]", sdk),
                    Joiner.on(' ')
                            .join(Iterables.transform(
                                    Iterables.concat(otherCFlags, Iterables.concat(platformFlags.get(sdk))),
                                    Escaper.BASH_ESCAPER)))
                    .put(String.format("OTHER_CPLUSPLUSFLAGS[sdk=*%s*]", sdk), Joiner.on(' ')
                            .join(Iterables.transform(
                                    Iterables.concat(otherCxxFlags, Iterables.concat(platformFlags.get(sdk))),
                                    Escaper.BASH_ESCAPER)));
        }

        ImmutableMultimap.Builder<String, ImmutableList<String>> platformLinkerFlagsBuilder = ImmutableMultimap
                .builder();
        for (Pair<Pattern, ImmutableList<String>> flags : Iterables.concat(
                targetNode.getConstructorArg().platformLinkerFlags.getPatternsAndValues(),
                collectRecursiveExportedPlatformLinkerFlags(ImmutableList.of(targetNode)))) {
            String sdk = flags.getFirst().pattern().replaceAll("[*.]", "");
            platformLinkerFlagsBuilder.put(sdk, flags.getSecond());
        }
        ImmutableMultimap<String, ImmutableList<String>> platformLinkerFlags = platformLinkerFlagsBuilder
                .build();
        for (String sdk : platformLinkerFlags.keySet()) {
            appendConfigsBuilder
                    .put(String.format("OTHER_LDFLAGS[sdk=*%s*]", sdk),
                            Joiner.on(
                                    ' ').join(
                                            Iterables
                                                    .transform(
                                                            Iterables.concat(otherLdFlags,
                                                                    Iterables.concat(
                                                                            platformLinkerFlags.get(sdk))),
                                                            Escaper.BASH_ESCAPER)));
        }
    }

    PBXNativeTarget target = targetBuilderResult.target;

    if (isFocusedOnTarget) {
        ImmutableMap<String, String> appendedConfig = appendConfigsBuilder.build();

        Optional<ImmutableSortedMap<String, ImmutableMap<String, String>>> configs = getXcodeBuildConfigurationsForTargetNode(
                targetNode, appendedConfig);
        setTargetBuildConfigurations(getConfigurationNameToXcconfigPath(buildTarget), target,
                project.getMainGroup(), configs.get(), extraSettingsBuilder.build(),
                defaultSettingsBuilder.build(), appendedConfig);
    }

    // -- phases
    boolean headerMapDisabled = options.contains(Option.DISABLE_HEADER_MAPS);
    createHeaderSymlinkTree(sourcePathResolver, getPublicCxxHeaders(targetNode),
            getPathToHeaderSymlinkTree(targetNode, HeaderVisibility.PUBLIC),
            arg.xcodePublicHeadersSymlinks.orElse(true) || headerMapDisabled);
    if (isFocusedOnTarget) {
        createHeaderSymlinkTree(sourcePathResolver, getPrivateCxxHeaders(targetNode),
                getPathToHeaderSymlinkTree(targetNode, HeaderVisibility.PRIVATE),
                arg.xcodePrivateHeadersSymlinks.orElse(true) || headerMapDisabled);
    }

    if (appleTargetNode.isPresent() && isFocusedOnTarget) {
        // Use Core Data models from immediate dependencies only.
        addCoreDataModelsIntoTarget(appleTargetNode.get(), targetGroup.get());
        addSceneKitAssetsIntoTarget(appleTargetNode.get(), targetGroup.get());
    }

    return target;
}

From source file:com.facebook.presto.sql.analyzer.StatementAnalyzer.java

private List<FieldOrExpression> analyzeOrderBy(QuerySpecification node, RelationType tupleDescriptor,
        AnalysisContext context, List<FieldOrExpression> outputExpressions) {
    List<SortItem> items = node.getOrderBy();

    ImmutableList.Builder<FieldOrExpression> orderByExpressionsBuilder = ImmutableList.builder();

    if (!items.isEmpty()) {
        // Compute aliased output terms so we can resolve order by expressions against them first
        ImmutableMultimap.Builder<QualifiedName, Expression> byAliasBuilder = ImmutableMultimap.builder();
        for (SelectItem item : node.getSelect().getSelectItems()) {
            if (item instanceof SingleColumn) {
                Optional<String> alias = ((SingleColumn) item).getAlias();
                if (alias.isPresent()) {
                    byAliasBuilder.put(QualifiedName.of(alias.get()), ((SingleColumn) item).getExpression()); // TODO: need to know if alias was quoted
                }/* w  ww.  j a  v  a 2 s. co m*/
            }
        }
        Multimap<QualifiedName, Expression> byAlias = byAliasBuilder.build();

        for (SortItem item : items) {
            Expression expression = item.getSortKey();

            FieldOrExpression orderByExpression = null;
            if (expression instanceof QualifiedNameReference
                    && !((QualifiedNameReference) expression).getName().getPrefix().isPresent()) {
                // if this is a simple name reference, try to resolve against output columns

                QualifiedName name = ((QualifiedNameReference) expression).getName();
                Collection<Expression> expressions = byAlias.get(name);
                if (expressions.size() > 1) {
                    throw new SemanticException(AMBIGUOUS_ATTRIBUTE, expression,
                            "'%s' in ORDER BY is ambiguous", name.getSuffix());
                } else if (expressions.size() == 1) {
                    orderByExpression = new FieldOrExpression(Iterables.getOnlyElement(expressions));
                }

                // otherwise, couldn't resolve name against output aliases, so fall through...
            } else if (expression instanceof LongLiteral) {
                // this is an ordinal in the output tuple

                long ordinal = ((LongLiteral) expression).getValue();
                if (ordinal < 1 || ordinal > outputExpressions.size()) {
                    throw new SemanticException(INVALID_ORDINAL, expression,
                            "ORDER BY position %s is not in select list", ordinal);
                }

                orderByExpression = outputExpressions.get((int) (ordinal - 1));

                if (orderByExpression.isExpression()) {
                    Type type = analysis.getType(orderByExpression.getExpression());
                    if (!type.isOrderable()) {
                        throw new SemanticException(TYPE_MISMATCH, node,
                                "The type of expression in position %s is not orderable (actual: %s), and therefore cannot be used in ORDER BY: %s",
                                ordinal, type, orderByExpression);
                    }
                } else {
                    Type type = tupleDescriptor.getFieldByIndex(orderByExpression.getFieldIndex()).getType();
                    if (!type.isOrderable()) {
                        throw new SemanticException(TYPE_MISMATCH, node,
                                "The type of expression in position %s is not orderable (actual: %s), and therefore cannot be used in ORDER BY",
                                ordinal, type);
                    }
                }
            }

            // otherwise, just use the expression as is
            if (orderByExpression == null) {
                orderByExpression = new FieldOrExpression(expression);
            }

            if (orderByExpression.isExpression()) {
                ExpressionAnalysis expressionAnalysis = analyzeExpression(orderByExpression.getExpression(),
                        tupleDescriptor, context);
                analysis.addInPredicates(node, expressionAnalysis.getSubqueryInPredicates());

                Type type = expressionAnalysis.getType(orderByExpression.getExpression());
                if (!type.isOrderable()) {
                    throw new SemanticException(TYPE_MISMATCH, node,
                            "Type %s is not orderable, and therefore cannot be used in ORDER BY: %s", type,
                            expression);
                }
            }

            orderByExpressionsBuilder.add(orderByExpression);
        }
    }

    List<FieldOrExpression> orderByExpressions = orderByExpressionsBuilder.build();
    analysis.setOrderByExpressions(node, orderByExpressions);

    if (node.getSelect().isDistinct() && !outputExpressions.containsAll(orderByExpressions)) {
        throw new SemanticException(ORDER_BY_MUST_BE_IN_SELECT, node.getSelect(),
                "For SELECT DISTINCT, ORDER BY expressions must appear in select list");
    }
    return orderByExpressions;
}

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

/**
 * Constructs the feature configuration from a {@code CToolchain} protocol buffer.
 *
 * @param toolchain the toolchain configuration as specified by the user.
 * @throws InvalidConfigurationException if the configuration has logical errors.
 *///w ww  . ja  va  2  s . c o  m
@VisibleForTesting
public CcToolchainFeatures(CToolchain toolchain) throws InvalidConfigurationException {
    // Build up the feature/action config graph.  We refer to features/action configs as
    // 'selectables'.
    // First, we build up the map of name -> selectables in one pass, so that earlier selectables
    // can reference later features in their configuration.
    ImmutableList.Builder<CrosstoolSelectable> selectablesBuilder = ImmutableList.builder();
    HashMap<String, CrosstoolSelectable> selectablesByName = new HashMap<>();

    // Also build a map from action -> action_config, for use in tool lookups
    ImmutableMap.Builder<String, ActionConfig> actionConfigsByActionName = ImmutableMap.builder();

    for (CToolchain.Feature toolchainFeature : toolchain.getFeatureList()) {
        Feature feature = new Feature(toolchainFeature);
        selectablesBuilder.add(feature);
        selectablesByName.put(feature.getName(), feature);
    }

    for (CToolchain.ActionConfig toolchainActionConfig : toolchain.getActionConfigList()) {
        ActionConfig actionConfig = new ActionConfig(toolchainActionConfig);
        selectablesBuilder.add(actionConfig);
        selectablesByName.put(actionConfig.getName(), actionConfig);
        actionConfigsByActionName.put(actionConfig.getActionName(), actionConfig);
    }

    this.selectables = selectablesBuilder.build();
    this.selectablesByName = ImmutableMap.copyOf(selectablesByName);

    checkForActionNameDups(toolchain.getActionConfigList());
    checkForActivatableDups(this.selectables);

    this.actionConfigsByActionName = actionConfigsByActionName.build();

    ImmutableList.Builder<ArtifactNamePattern> artifactNamePatternsBuilder = ImmutableList.builder();
    for (CToolchain.ArtifactNamePattern artifactNamePattern : toolchain.getArtifactNamePatternList()) {
        artifactNamePatternsBuilder.add(new ArtifactNamePattern(artifactNamePattern));
    }
    this.artifactNamePatterns = artifactNamePatternsBuilder.build();

    // Next, we build up all forward references for 'implies' and 'requires' edges.
    ImmutableMultimap.Builder<CrosstoolSelectable, CrosstoolSelectable> implies = ImmutableMultimap.builder();
    ImmutableMultimap.Builder<CrosstoolSelectable, ImmutableSet<CrosstoolSelectable>> requires = ImmutableMultimap
            .builder();
    // We also store the reverse 'implied by' and 'required by' edges during this pass.
    ImmutableMultimap.Builder<CrosstoolSelectable, CrosstoolSelectable> impliedBy = ImmutableMultimap.builder();
    ImmutableMultimap.Builder<CrosstoolSelectable, CrosstoolSelectable> requiredBy = ImmutableMultimap
            .builder();

    for (CToolchain.Feature toolchainFeature : toolchain.getFeatureList()) {
        String name = toolchainFeature.getName();
        CrosstoolSelectable selectable = selectablesByName.get(name);
        for (CToolchain.FeatureSet requiredFeatures : toolchainFeature.getRequiresList()) {
            ImmutableSet.Builder<CrosstoolSelectable> allOf = ImmutableSet.builder();
            for (String requiredName : requiredFeatures.getFeatureList()) {
                CrosstoolSelectable required = getActivatableOrFail(requiredName, name);
                allOf.add(required);
                requiredBy.put(required, selectable);
            }
            requires.put(selectable, allOf.build());
        }
        for (String impliedName : toolchainFeature.getImpliesList()) {
            CrosstoolSelectable implied = getActivatableOrFail(impliedName, name);
            impliedBy.put(implied, selectable);
            implies.put(selectable, implied);
        }
    }

    for (CToolchain.ActionConfig toolchainActionConfig : toolchain.getActionConfigList()) {
        String name = toolchainActionConfig.getConfigName();
        CrosstoolSelectable selectable = selectablesByName.get(name);
        for (String impliedName : toolchainActionConfig.getImpliesList()) {
            CrosstoolSelectable implied = getActivatableOrFail(impliedName, name);
            impliedBy.put(implied, selectable);
            implies.put(selectable, implied);
        }
    }

    this.implies = implies.build();
    this.requires = requires.build();
    this.impliedBy = impliedBy.build();
    this.requiredBy = requiredBy.build();
}