Example usage for com.google.common.collect ImmutableSortedSet copyOf

List of usage examples for com.google.common.collect ImmutableSortedSet copyOf

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableSortedSet copyOf.

Prototype

public static <E extends Comparable<? super E>> ImmutableSortedSet<E> copyOf(E[] elements) 

Source Link

Usage

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

public JavaFileFeatures extractFeaturesFromJavaCode(String code) {
    // For now, we will harcode this. Ultimately, we probably want to make this configurable via
    // .buckconfig. For example, the Buck project itself is diligent about disallowing wildcard
    // imports, but the one exception is the Java code generated via Thrift in src-gen.
    final boolean shouldThrowForUnsupportedWildcardImport = false;

    final AtomicBoolean isPoisonedByUnsupportedWildcardImport = new AtomicBoolean(false);

    final CompilationUnit compilationUnit = makeCompilationUnitFromSource(code);

    final ImmutableSortedSet.Builder<String> providedSymbols = ImmutableSortedSet.naturalOrder();
    final ImmutableSortedSet.Builder<String> requiredSymbols = ImmutableSortedSet.naturalOrder();
    final ImmutableSortedSet.Builder<String> exportedSymbols = ImmutableSortedSet.naturalOrder();
    final ImmutableSortedSet.Builder<String> requiredSymbolsFromExplicitImports = ImmutableSortedSet
            .naturalOrder();/*from w ww.  j av  a2 s . co  m*/

    compilationUnit.accept(new ASTVisitor() {

        @Nullable
        private String packageName;

        /** Maps simple name to fully-qualified name. */
        private Map<String, String> simpleImportedTypes = new HashMap<>();

        /**
         * Maps wildcard import prefixes, such as {@code "java.util"} to the types in the respective
         * package if a wildcard import such as {@code import java.util.*} is used.
         */
        private Map<String, ImmutableSet<String>> wildcardImports = new HashMap<>();

        @Override
        public boolean visit(PackageDeclaration node) {
            Preconditions.checkState(packageName == null, "There should be at most one package declaration");
            packageName = node.getName().getFullyQualifiedName();
            return false;
        }

        // providedSymbols

        @Override
        public boolean visit(TypeDeclaration node) {
            // Local classes can be declared inside of methods. Skip over these.
            if (node.getParent() instanceof TypeDeclarationStatement) {
                return true;
            }

            String fullyQualifiedName = getFullyQualifiedTypeName(node);
            if (fullyQualifiedName != null) {
                providedSymbols.add(fullyQualifiedName);
            }

            @SuppressWarnings("unchecked")
            List<Type> interfaceTypes = node.superInterfaceTypes();
            for (Type interfaceType : interfaceTypes) {
                tryAddType(interfaceType, DependencyType.EXPORTED);
            }

            Type superclassType = node.getSuperclassType();
            if (superclassType != null) {
                tryAddType(superclassType, DependencyType.EXPORTED);
            }

            return true;
        }

        @Override
        public boolean visit(EnumDeclaration node) {
            String fullyQualifiedName = getFullyQualifiedTypeName(node);
            if (fullyQualifiedName != null) {
                providedSymbols.add(fullyQualifiedName);
            }
            return true;
        }

        @Override
        public boolean visit(AnnotationTypeDeclaration node) {
            String fullyQualifiedName = getFullyQualifiedTypeName(node);
            if (fullyQualifiedName != null) {
                providedSymbols.add(fullyQualifiedName);
            }
            return true;
        }

        // requiredSymbols

        /**
         * Uses heuristics to try to figure out what type of QualifiedName this is. Returns a non-null
         * value if this is believed to be a reference that qualifies as a "required symbol"
         * relationship.
         */
        @Override
        public boolean visit(QualifiedName node) {
            QualifiedName ancestor = findMostQualifiedAncestor(node);
            ASTNode parent = ancestor.getParent();
            if (!(parent instanceof PackageDeclaration) && !(parent instanceof ImportDeclaration)) {
                String symbol = ancestor.getFullyQualifiedName();

                // If it does not start with an uppercase letter, it is probably because it is a property
                // lookup.
                if (CharMatcher.javaUpperCase().matches(symbol.charAt(0))) {
                    addTypeFromDotDelimitedSequence(symbol, DependencyType.REQUIRED);
                }
            }

            return false;
        }

        /**
         * @param expr could be "Example", "Example.field", "com.example.Example". Note it could also
         *     be a built-in type, such as "java.lang.Integer", in which case it will not be added to
         *     the set of required symbols.
         */
        private void addTypeFromDotDelimitedSequence(String expr, DependencyType dependencyType) {
            // At this point, symbol could be `System.out`. We want to reduce it to `System` and then
            // check it against JAVA_LANG_TYPES.
            if (startsWithUppercaseChar(expr)) {
                int index = expr.indexOf('.');
                if (index >= 0) {
                    String leftmostComponent = expr.substring(0, index);
                    if (JAVA_LANG_TYPES.contains(leftmostComponent)) {
                        return;
                    }
                }
            }

            expr = qualifyWithPackageNameIfNecessary(expr);
            addSymbol(expr, dependencyType);
        }

        @Override
        public boolean visit(ImportDeclaration node) {
            String fullyQualifiedName = node.getName().getFullyQualifiedName();

            // Apparently, "on demand" means "uses a wildcard," such as "import java.util.*". Although
            // we can choose to prohibit these in our own code, it is much harder to enforce for
            // third-party code. As such, we will tolerate these for some of the common cases.
            if (node.isOnDemand()) {
                ImmutableSet<String> value = SUPPORTED_WILDCARD_IMPORTS.get(fullyQualifiedName);
                if (value != null) {
                    wildcardImports.put(fullyQualifiedName, value);
                    return false;
                } else if (shouldThrowForUnsupportedWildcardImport) {
                    throw new RuntimeException(String.format(
                            "Use of wildcard 'import %s.*' makes it impossible to statically determine "
                                    + "required symbols in this file. Please enumerate explicit imports.",
                            fullyQualifiedName));
                } else {
                    isPoisonedByUnsupportedWildcardImport.set(true);
                    return false;
                }
            }

            // Only worry about the dependency on the enclosing type.
            Optional<String> simpleName = getSimpleNameFromFullyQualifiedName(fullyQualifiedName);
            if (simpleName.isPresent()) {
                String name = simpleName.get();
                int index = fullyQualifiedName.indexOf("." + name);
                String enclosingType = fullyQualifiedName.substring(0, index + name.length() + 1);
                requiredSymbolsFromExplicitImports.add(enclosingType);

                simpleImportedTypes.put(name, enclosingType);
            } else {
                LOG.warn("Suspicious import lacks obvious enclosing type: %s", fullyQualifiedName);
                // The one example we have seen of this in the wild is
                // "org.whispersystems.curve25519.java.curve_sigs". In practice, we still need to add it
                // as a required symbol in this case.
                requiredSymbols.add(fullyQualifiedName);
            }
            return false;
        }

        @Override
        public boolean visit(MethodInvocation node) {
            if (node.getExpression() == null) {
                return true;
            }

            String receiver = node.getExpression().toString();
            if (looksLikeAType(receiver)) {
                addTypeFromDotDelimitedSequence(receiver, DependencyType.REQUIRED);
            }
            return true;
        }

        /** An annotation on a member with zero arguments. */
        @Override
        public boolean visit(MarkerAnnotation node) {
            DependencyType dependencyType = findDependencyTypeForAnnotation(node);
            addSimpleTypeName(node.getTypeName(), dependencyType);
            return true;
        }

        /** An annotation on a member with named arguments. */
        @Override
        public boolean visit(NormalAnnotation node) {
            DependencyType dependencyType = findDependencyTypeForAnnotation(node);
            addSimpleTypeName(node.getTypeName(), dependencyType);
            return true;
        }

        /** An annotation on a member with a single, unnamed argument. */
        @Override
        public boolean visit(SingleMemberAnnotation node) {
            DependencyType dependencyType = findDependencyTypeForAnnotation(node);
            addSimpleTypeName(node.getTypeName(), dependencyType);
            return true;
        }

        private DependencyType findDependencyTypeForAnnotation(Annotation annotation) {
            ASTNode parentNode = annotation.getParent();
            if (parentNode == null) {
                return DependencyType.REQUIRED;
            }

            if (parentNode instanceof BodyDeclaration) {
                // Note that BodyDeclaration is an abstract class. Its subclasses are things like
                // FieldDeclaration and MethodDeclaration. We want to be sure that an annotation on any
                // non-private declaration is considered an exported symbol.
                BodyDeclaration declaration = (BodyDeclaration) parentNode;

                int modifiers = declaration.getModifiers();
                if ((modifiers & Modifier.PRIVATE) == 0) {
                    return DependencyType.EXPORTED;
                }
            }
            return DependencyType.REQUIRED;
        }

        @Override
        public boolean visit(SimpleType node) {
            // This method is responsible for finding the overwhelming majority of the required symbols
            // in the AST.
            tryAddType(node, DependencyType.REQUIRED);
            return true;
        }

        // exportedSymbols

        @Override
        public boolean visit(MethodDeclaration node) {
            // Types from private method signatures need not be exported.
            if ((node.getModifiers() & Modifier.PRIVATE) != 0) {
                return true;
            }

            Type returnType = node.getReturnType2();
            if (returnType != null) {
                tryAddType(returnType, DependencyType.EXPORTED);
            }

            @SuppressWarnings("unchecked")
            List<SingleVariableDeclaration> params = node.parameters();
            for (SingleVariableDeclaration decl : params) {
                tryAddType(decl.getType(), DependencyType.EXPORTED);
            }

            @SuppressWarnings("unchecked")
            List<Type> exceptions = node.thrownExceptionTypes();
            for (Type exception : exceptions) {
                tryAddType(exception, DependencyType.EXPORTED);
            }

            return true;
        }

        @Override
        public boolean visit(FieldDeclaration node) {
            // Types from private fields need not be exported.
            if ((node.getModifiers() & Modifier.PRIVATE) == 0) {
                tryAddType(node.getType(), DependencyType.EXPORTED);
            }
            return true;
        }

        private void tryAddType(Type type, DependencyType dependencyType) {
            if (type.isSimpleType()) {
                SimpleType simpleType = (SimpleType) type;
                Name simpleTypeName = simpleType.getName();
                String simpleName = simpleTypeName.toString();

                // For a Type such as IExample<T>, both "IExample" and "T" will be submitted here as
                // simple types. As such, we use this imperfect heuristic to filter out "T" from being
                // added. Note that this will erroneously exclude "URI". In practice, this should
                // generally be OK. For example, assuming "URI" is also imported, then at least it will
                // end up in the set of required symbols. To this end, we perform a second check for
                // "all caps" types to see if there is a corresponding import and if it should be exported
                // rather than simply required.
                if (!CharMatcher.JAVA_UPPER_CASE.matchesAllOf(simpleName)
                        || (dependencyType == DependencyType.EXPORTED
                                && simpleImportedTypes.containsKey(simpleName))) {
                    addSimpleTypeName(simpleTypeName, dependencyType);
                }
            } else if (type.isArrayType()) {
                ArrayType arrayType = (ArrayType) type;
                tryAddType(arrayType.getElementType(), dependencyType);
            } else if (type.isParameterizedType()) {
                ParameterizedType parameterizedType = (ParameterizedType) type;
                tryAddType(parameterizedType.getType(), dependencyType);
                @SuppressWarnings("unchecked")
                List<Type> argTypes = parameterizedType.typeArguments();
                for (Type argType : argTypes) {
                    tryAddType(argType, dependencyType);
                }
            }
        }

        private void addSimpleTypeName(Name simpleTypeName, DependencyType dependencyType) {
            String simpleName = simpleTypeName.toString();
            if (JAVA_LANG_TYPES.contains(simpleName)) {
                return;
            }

            String fullyQualifiedNameForSimpleName = simpleImportedTypes.get(simpleName);
            if (fullyQualifiedNameForSimpleName != null) {
                // May need to promote from required to exported in this case.
                if (dependencyType == DependencyType.EXPORTED) {
                    addSymbol(fullyQualifiedNameForSimpleName, DependencyType.EXPORTED);
                }
                return;
            }

            // For well-behaved source code, this will always be empty, so don't even bother to create
            // the iterator most of the time.
            if (!wildcardImports.isEmpty()) {
                for (Map.Entry<String, ImmutableSet<String>> entry : wildcardImports.entrySet()) {
                    Set<String> types = entry.getValue();
                    if (types.contains(simpleName)) {
                        String packageName = entry.getKey();
                        addSymbol(packageName + "." + simpleName, dependencyType);
                        return;
                    }
                }
            }

            String symbol = simpleTypeName.getFullyQualifiedName();
            symbol = qualifyWithPackageNameIfNecessary(symbol);
            addSymbol(symbol, dependencyType);
        }

        private void addSymbol(String symbol, DependencyType dependencyType) {
            ((dependencyType == DependencyType.REQUIRED) ? requiredSymbols : exportedSymbols).add(symbol);
        }

        private String qualifyWithPackageNameIfNecessary(String symbol) {
            if (!startsWithUppercaseChar(symbol)) {
                return symbol;
            }

            // If the symbol starts with a capital letter, then we assume that it is a reference to
            // a type in the same package.
            int index = symbol.indexOf('.');
            if (index >= 0) {
                symbol = symbol.substring(0, index);
            }
            if (packageName != null) {
                symbol = packageName + "." + symbol;
            }

            return symbol;
        }
    });

    // TODO(bolinfest): Special treatment for exportedSymbols when poisoned by wildcard import.
    ImmutableSortedSet<String> totalExportedSymbols = exportedSymbols.build();

    // If we were poisoned by an unsupported wildcard import, then we should rely exclusively on
    // the explicit imports to determine the required symbols.
    Set<String> totalRequiredSymbols = new HashSet<>();
    if (isPoisonedByUnsupportedWildcardImport.get()) {
        totalRequiredSymbols.addAll(requiredSymbolsFromExplicitImports.build());
    } else {
        totalRequiredSymbols.addAll(requiredSymbolsFromExplicitImports.build());
        totalRequiredSymbols.addAll(requiredSymbols.build());
    }
    // Make sure that required and exported symbols are disjoint sets.
    totalRequiredSymbols.removeAll(totalExportedSymbols);

    return new JavaFileFeatures(providedSymbols.build(), ImmutableSortedSet.copyOf(totalRequiredSymbols),
            totalExportedSymbols);
}

From source file:com.facebook.buck.cxx.CxxDescriptionEnhancer.java

public static CxxLinkAndCompileRules createBuildRulesForCxxBinary(BuildRuleParams params,
        BuildRuleResolver resolver, CxxBuckConfig cxxBuckConfig, CxxPlatform cxxPlatform,
        ImmutableMap<String, CxxSource> srcs, ImmutableMap<Path, SourcePath> headers,
        Iterable<? extends BuildRule> deps, Optional<StripStyle> stripStyle,
        Optional<LinkerMapMode> flavoredLinkerMapMode, Linker.LinkableDepType linkStyle,
        ImmutableList<String> preprocessorFlags,
        PatternMatchedCollection<ImmutableList<String>> platformPreprocessorFlags,
        ImmutableMap<CxxSource.Type, ImmutableList<String>> langPreprocessorFlags,
        ImmutableSortedSet<FrameworkPath> frameworks, ImmutableSortedSet<FrameworkPath> libraries,
        ImmutableList<String> compilerFlags,
        ImmutableMap<CxxSource.Type, ImmutableList<String>> langCompilerFlags,
        PatternMatchedCollection<ImmutableList<String>> platformCompilerFlags,
        Optional<SourcePath> prefixHeader, Optional<SourcePath> precompiledHeader,
        ImmutableList<String> linkerFlags, PatternMatchedCollection<ImmutableList<String>> platformLinkerFlags,
        Optional<Linker.CxxRuntimeType> cxxRuntimeType, ImmutableList<String> includeDirs,
        Optional<Boolean> xcodePrivateHeadersSymlinks) throws NoSuchBuildTargetException {
    SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(resolver);
    SourcePathResolver sourcePathResolver = new SourcePathResolver(ruleFinder);
    //    TODO(beefon): should be:
    //    Path linkOutput = getLinkOutputPath(
    //        createCxxLinkTarget(params.getBuildTarget(), flavoredLinkerMapMode),
    //        params.getProjectFilesystem());

    BuildTarget target = params.getBuildTarget();
    if (flavoredLinkerMapMode.isPresent()) {
        target = target.withAppendedFlavors(flavoredLinkerMapMode.get().getFlavor());
    }//from w  ww  . j av a2s.co m
    Path linkOutput = getBinaryOutputPath(target, params.getProjectFilesystem(),
            cxxPlatform.getBinaryExtension());
    ImmutableList.Builder<Arg> argsBuilder = ImmutableList.builder();
    CommandTool.Builder executableBuilder = new CommandTool.Builder();

    // Setup the header symlink tree and combine all the preprocessor input from this rule
    // and all dependencies.
    boolean shouldCreatePrivateHeadersSymlinks = xcodePrivateHeadersSymlinks.orElse(true);
    HeaderSymlinkTree headerSymlinkTree = requireHeaderSymlinkTree(params, resolver, sourcePathResolver,
            cxxPlatform, headers, HeaderVisibility.PRIVATE, shouldCreatePrivateHeadersSymlinks);
    Optional<SymlinkTree> sandboxTree = Optional.empty();
    if (cxxBuckConfig.sandboxSources()) {
        sandboxTree = createSandboxTree(params, resolver, cxxPlatform);
    }
    ImmutableList<CxxPreprocessorInput> cxxPreprocessorInput = collectCxxPreprocessorInput(params, cxxPlatform,
            CxxFlags.getLanguageFlags(
                    preprocessorFlags, platformPreprocessorFlags, langPreprocessorFlags, cxxPlatform),
            ImmutableList.of(headerSymlinkTree), frameworks,
            CxxPreprocessables.getTransitiveCxxPreprocessorInput(cxxPlatform,
                    RichStream.from(deps).filter(CxxPreprocessorDep.class::isInstance).toImmutableList()),
            includeDirs, sandboxTree);

    // Generate and add all the build rules to preprocess and compile the source to the
    // resolver and get the `SourcePath`s representing the generated object files.
    ImmutableMap<CxxPreprocessAndCompile, SourcePath> objects = CxxSourceRuleFactory
            .requirePreprocessAndCompileRules(params, resolver, sourcePathResolver, ruleFinder, cxxBuckConfig,
                    cxxPlatform, cxxPreprocessorInput,
                    CxxFlags.getLanguageFlags(compilerFlags, platformCompilerFlags, langCompilerFlags,
                            cxxPlatform),
                    prefixHeader, precompiledHeader, srcs,
                    linkStyle == Linker.LinkableDepType.STATIC ? CxxSourceRuleFactory.PicType.PDC
                            : CxxSourceRuleFactory.PicType.PIC,
                    sandboxTree);

    // Build up the linker flags, which support macro expansion.
    ImmutableList<String> resolvedLinkerFlags = CxxFlags.getFlags(linkerFlags, platformLinkerFlags,
            cxxPlatform);
    argsBuilder.addAll(resolvedLinkerFlags.stream().map(MacroArg.toMacroArgFunction(MACRO_HANDLER,
            params.getBuildTarget(), params.getCellRoots(), resolver)::apply).iterator());

    // Special handling for dynamically linked binaries.
    if (linkStyle == Linker.LinkableDepType.SHARED) {

        // Create a symlink tree with for all shared libraries needed by this binary.
        SymlinkTree sharedLibraries = requireSharedLibrarySymlinkTree(params, resolver, sourcePathResolver,
                cxxPlatform, deps, NativeLinkable.class::isInstance);

        // Embed a origin-relative library path into the binary so it can find the shared libraries.
        // The shared libraries root is absolute. Also need an absolute path to the linkOutput

        Path absLinkOut = params.getBuildTarget().getCellPath().resolve(linkOutput);

        argsBuilder.addAll(StringArg.from(Linkers.iXlinker("-rpath",
                String.format("%s/%s", cxxPlatform.getLd().resolve(resolver).origin(),
                        absLinkOut.getParent().relativize(sharedLibraries.getRoot()).toString()))));

        // Add all the shared libraries and the symlink tree as inputs to the tool that represents
        // this binary, so that users can attach the proper deps.
        executableBuilder.addDep(sharedLibraries);
        executableBuilder.addInputs(sharedLibraries.getLinks().values());
    }

    // Add object files into the args.
    ImmutableList<SourcePathArg> objectArgs = SourcePathArg.from(sourcePathResolver, objects.values()).stream()
            .map(input -> {
                Preconditions.checkArgument(input instanceof SourcePathArg);
                return (SourcePathArg) input;
            }).collect(MoreCollectors.toImmutableList());
    argsBuilder.addAll(FileListableLinkerInputArg.from(objectArgs));

    BuildTarget linkRuleTarget = createCxxLinkTarget(params.getBuildTarget(), flavoredLinkerMapMode);

    CxxLink cxxLink = createCxxLinkRule(params, resolver, cxxBuckConfig, cxxPlatform,
            RichStream.from(deps).filter(NativeLinkable.class).toImmutableList(), linkStyle, frameworks,
            libraries, cxxRuntimeType, sourcePathResolver, ruleFinder, linkOutput, argsBuilder, linkRuleTarget);

    BuildRule binaryRuleForExecutable;
    Optional<CxxStrip> cxxStrip = Optional.empty();
    if (stripStyle.isPresent()) {
        BuildRuleParams cxxParams = params;
        if (flavoredLinkerMapMode.isPresent()) {
            cxxParams = params.withFlavor(flavoredLinkerMapMode.get().getFlavor());
        }
        CxxStrip stripRule = createCxxStripRule(cxxParams, resolver, stripStyle.get(), sourcePathResolver,
                cxxLink, cxxPlatform);
        cxxStrip = Optional.of(stripRule);
        binaryRuleForExecutable = stripRule;
    } else {
        binaryRuleForExecutable = cxxLink;
    }

    // Add the output of the link as the lone argument needed to invoke this binary as a tool.
    executableBuilder.addArg(new SourcePathArg(sourcePathResolver,
            new BuildTargetSourcePath(binaryRuleForExecutable.getBuildTarget())));

    return new CxxLinkAndCompileRules(cxxLink, cxxStrip, ImmutableSortedSet.copyOf(objects.keySet()),
            executableBuilder.build());
}

From source file:com.facebook.buck.skylark.parser.SkylarkProjectBuildFileParser.java

@Override
public ImmutableSortedSet<String> getIncludedFiles(Path buildFile)
        throws BuildFileParseException, InterruptedException, IOException {
    com.google.devtools.build.lib.vfs.Path buildFilePath = fileSystem.getPath(buildFile.toString());

    String basePath = getBasePath(buildFile);
    Label containingLabel = createContainingLabel(basePath);
    ImplicitlyLoadedExtension implicitLoad = loadImplicitExtension(basePath, containingLabel);
    BuildFileAST buildFileAst = parseBuildFile(buildFilePath, containingLabel);
    ImmutableList<IncludesData> dependencies = loadIncludes(containingLabel, buildFileAst.getImports());

    // it might be potentially faster to keep sorted sets for each dependency separately and just
    // merge sorted lists as we aggregate transitive close up
    // But Guava does not seem to have a built-in way of merging sorted lists/sets
    return ImmutableSortedSet
            .copyOf(toIncludedPaths(buildFile.toString(), dependencies, implicitLoad.getExtensionData()));
}

From source file:edu.mit.streamjit.impl.compiler2.Compiler2.java

/**
 * Removes an Actor from this compiler's data structures.  The Actor should
 * already have been unlinked from the graph (no incoming edges); this takes
 * care of removing it from the actors set, its actor group (possibly
 * removing the group if it's now empty), and the schedule.
 * @param a the actor to remove//from  w  ww.j  a v a  2 s.co m
 */
private void removeActor(Actor a) {
    assert actors.contains(a) : a;
    actors.remove(a);
    ActorGroup g = a.group();
    g.remove(a);
    if (g.actors().isEmpty()) {
        groups = ImmutableSortedSet.copyOf(Sets.difference(groups, ImmutableSet.of(g)));
        externalSchedule = ImmutableMap
                .copyOf(Maps.difference(externalSchedule, ImmutableMap.of(g, 0)).entriesOnlyOnLeft());
        initSchedule = ImmutableMap
                .copyOf(Maps.difference(initSchedule, ImmutableMap.of(g, 0)).entriesOnlyOnLeft());
    }
}

From source file:org.sosy_lab.cpachecker.util.predicates.pathformula.pointeraliasing.DynamicMemoryHandler.java

/**
 * The function removes local void * pointers (deferred allocations)
 * declared in current function scope from tracking after returning from the function.
 *
 * @param function The name of the function.
 *///  ww w. j  a v a2 s.  c  om
void handleDeferredAllocationInFunctionExit(final String function) {
    for (String v : CFAUtils.filterVariablesOfFunction(
            ImmutableSortedSet.copyOf(pts.getDeferredAllocationPointers()), function)) {
        if (!pts.removeDeferredAllocationPointer(v).isEmpty()) {
            conv.logger.logfOnce(Level.WARNING,
                    "%s: Destroying the void* pointer %s produces garbage or the memory pointed by it is unused: %s",
                    edge.getFileLocation(), v, edge.getDescription());
        }
    }
}

From source file:com.facebook.buck.cxx.CxxDescriptionEnhancer.java

public static BuildRule createUberCompilationDatabase(BuildRuleParams params, BuildRuleResolver ruleResolver)
        throws NoSuchBuildTargetException {
    Optional<CxxCompilationDatabaseDependencies> compilationDatabases = ruleResolver.requireMetadata(
            params.withoutFlavor(CxxCompilationDatabase.UBER_COMPILATION_DATABASE)
                    .withFlavor(CxxCompilationDatabase.COMPILATION_DATABASE).getBuildTarget(),
            CxxCompilationDatabaseDependencies.class);
    Preconditions.checkState(compilationDatabases.isPresent());
    SourcePathRuleFinder ruleFinder = new SourcePathRuleFinder(ruleResolver);
    SourcePathResolver pathResolver = new SourcePathResolver(ruleFinder);
    return new JsonConcatenate(
            params.copyWithDeps(//  w  ww. j a v  a 2 s .c  o  m
                    Suppliers.ofInstance(ImmutableSortedSet.copyOf(
                            ruleFinder.filterBuildRuleInputs(compilationDatabases.get().getSourcePaths()))),
                    Suppliers.ofInstance(ImmutableSortedSet.of())),
            pathResolver, pathResolver.getAllAbsolutePaths(compilationDatabases.get().getSourcePaths()),
            "compilation-database-concatenate", "Concatenate compilation databases",
            "uber-compilation-database", "compile_commands.json");
}

From source file:edu.mit.streamjit.impl.compiler.Compiler.java

private void generateStaticInit() {
    Method clinit = new Method("<clinit>", module.types().getMethodType(void.class),
            EnumSet.of(Modifier.STATIC), blobKlass);

    //Generate fields in field helper, then copy them over in clinit.
    BasicBlock fieldBlock = new BasicBlock(module, "copyFieldsFromHelper");
    clinit.basicBlocks().add(fieldBlock);
    for (StreamNode node : ImmutableSet.copyOf(streamNodes.values()))
        for (Field cell : node.fields.values()) {
            Field helper = new Field(cell.getType().getFieldType(), cell.getName(),
                    EnumSet.of(Modifier.PUBLIC, Modifier.STATIC), fieldHelperKlass);
            LoadInst li = new LoadInst(helper);
            StoreInst si = new StoreInst(cell, li);
            fieldBlock.instructions().add(li);
            fieldBlock.instructions().add(si);
        }/*from w  ww  .  jav a2 s . co  m*/

    BasicBlock bufferBlock = new BasicBlock(module, "newBuffers");
    clinit.basicBlocks().add(bufferBlock);
    for (BufferData data : ImmutableSortedSet.copyOf(buffers.values()))
        for (String fieldName : new String[] { data.readerBufferFieldName, data.writerBufferFieldName })
            if (fieldName != null) {
                Field field = blobKlass.getField(fieldName);
                NewArrayInst nai = new NewArrayInst((ArrayType) field.getType().getFieldType(),
                        module.constants().getConstant(data.capacity));
                StoreInst si = new StoreInst(field, nai);
                bufferBlock.instructions().add(nai);
                bufferBlock.instructions().add(si);
            }

    BasicBlock exitBlock = new BasicBlock(module, "exit");
    clinit.basicBlocks().add(exitBlock);
    exitBlock.instructions().add(new ReturnInst(module.types().getVoidType()));

    for (int i = 0; i < clinit.basicBlocks().size() - 1; ++i)
        clinit.basicBlocks().get(i).instructions().add(new JumpInst(clinit.basicBlocks().get(i + 1)));
}

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

/**
 * Asks the Skyframe evaluator to build the value for BuildConfigurationCollection and returns the
 * result. Also invalidates {@link PrecomputedValue#BLAZE_DIRECTORIES} if it has changed.
 *///from ww w .j  a  v a2s . c  o  m
public BuildConfigurationCollection createConfigurations(EventHandler eventHandler,
        ConfigurationFactory configurationFactory, BuildOptions buildOptions, Set<String> multiCpu,
        boolean keepGoing) throws InvalidConfigurationException, InterruptedException {
    this.configurationFactory.set(configurationFactory);
    this.configurationFragments.set(ImmutableList.copyOf(configurationFactory.getFactories()));

    SkyKey skyKey = ConfigurationCollectionValue.key(buildOptions, ImmutableSortedSet.copyOf(multiCpu));
    EvaluationResult<ConfigurationCollectionValue> result = buildDriver.evaluate(Arrays.asList(skyKey),
            keepGoing, DEFAULT_THREAD_COUNT, eventHandler);
    if (result.hasError()) {
        Throwable e = result.getError(skyKey).getException();
        // Wrap loading failed exceptions
        if (e instanceof NoSuchThingException) {
            e = new InvalidConfigurationException(e);
        }
        Throwables.propagateIfInstanceOf(e, InvalidConfigurationException.class);
        throw new IllegalStateException("Unknown error during ConfigurationCollectionValue evaluation", e);
    }
    ConfigurationCollectionValue configurationValue = result.get(skyKey);
    return configurationValue.getConfigurationCollection();
}

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

private String serializeBuildConfiguration(XcodeRuleConfiguration configuration,
        ImmutableList<Path> searchPaths, ImmutableMap<String, String> extra) {

    XcconfigStack.Builder builder = XcconfigStack.builder();
    for (XcodeRuleConfiguration.Layer layer : configuration.getLayers()) {
        switch (layer.getLayerType()) {
        case FILE:
            builder.addSettingsFromFile(projectFilesystem, searchPaths, layer.getPath().get());
            break;
        case INLINE_SETTINGS:
            ImmutableMap<String, String> entries = layer.getInlineSettings().get();
            for (ImmutableMap.Entry<String, String> entry : entries.entrySet()) {
                builder.addSetting(entry.getKey(), entry.getValue());
            }/*from  w ww  .j  a  v  a  2s . c  om*/
            break;
        }
        builder.pushLayer();
    }

    for (ImmutableMap.Entry<String, String> entry : extra.entrySet()) {
        builder.addSetting(entry.getKey(), entry.getValue());
    }
    builder.pushLayer();

    XcconfigStack stack = builder.build();

    ImmutableList<String> resolvedConfigs = stack.resolveConfigStack();
    ImmutableSortedSet<String> sortedConfigs = ImmutableSortedSet.copyOf(resolvedConfigs);
    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append("// This configuration is autogenerated.\n"
            + "// Re-run buck to update this file after modifying the hand-written configs.\n");
    for (String line : sortedConfigs) {
        stringBuilder.append(line);
        stringBuilder.append('\n');
    }
    return stringBuilder.toString();
}

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

@VisibleForTesting
static ImmutableMap<String, ImmutableSortedSet<String>> gatherExcludedSources(
        ImmutableSet<String> applePlatforms,
        ImmutableList<Pair<Pattern, ImmutableSortedSet<SourceWithFlags>>> platformSources,
        ImmutableList<Pair<Pattern, Iterable<SourcePath>>> platformHeaders, Path outputDirectory,
        SourcePathResolver pathResolver) {
    Set<String> allPlatformSpecificSources = new HashSet<>();
    Map<String, Set<String>> includedSourcesByPlatform = new HashMap<>();

    for (Pair<Pattern, ImmutableSortedSet<SourceWithFlags>> platformSource : platformSources) {
        String platformName = platformSource.getFirst().toString();
        includedSourcesByPlatform.putIfAbsent(platformName, new HashSet<>());

        for (SourceWithFlags source : platformSource.getSecond()) {
            appendPlatformSourceToAllPlatformSourcesAndSourcesByPlatform(allPlatformSpecificSources,
                    includedSourcesByPlatform, platformName,
                    sourceNameRelativeToOutput(source.getSourcePath(), pathResolver, outputDirectory));
        }/*from  ww w.j  a va 2s .  c  o m*/
    }

    for (Pair<Pattern, Iterable<SourcePath>> platformHeader : platformHeaders) {
        String platformName = platformHeader.getFirst().toString();
        includedSourcesByPlatform.putIfAbsent(platformName, new HashSet<>());

        for (SourcePath source : platformHeader.getSecond()) {
            appendPlatformSourceToAllPlatformSourcesAndSourcesByPlatform(allPlatformSpecificSources,
                    includedSourcesByPlatform, platformName,
                    sourceNameRelativeToOutput(source, pathResolver, outputDirectory));
        }
    }

    Map<String, SortedSet<String>> result = new HashMap<>();
    result.put("EXCLUDED_SOURCE_FILE_NAMES", ImmutableSortedSet
            .copyOf(allPlatformSpecificSources.stream().map(s -> "'" + s + "'").collect(Collectors.toSet())));
    // We need to convert the regex to a glob that Xcode will recognize so we match the regex
    // against the name of a known sdk with the matcher, then glob that.
    for (String platformMatcher : includedSourcesByPlatform.keySet()) {
        for (String flavor : applePlatforms) {
            Pattern pattern = Pattern.compile(platformMatcher);
            Matcher matcher = pattern.matcher(flavor);
            if (matcher.lookingAt()) {
                String key = "INCLUDED_SOURCE_FILE_NAMES[sdk=" + flavor + "*]";
                Set<String> sourcesMatchingPlatform = includedSourcesByPlatform.get(platformMatcher);
                if (sourcesMatchingPlatform != null) {
                    Set<String> quotedSources = sourcesMatchingPlatform.stream().map(s -> "'" + s + "'")
                            .collect(Collectors.toSet());
                    // They may have different matchers for similar things in which case the key will
                    // already
                    // be included
                    if (result.get(key) != null) {
                        result.get(key).addAll(quotedSources);
                    } else {
                        result.put("INCLUDED_SOURCE_FILE_NAMES[sdk=" + flavor + "*]",
                                new TreeSet<>(quotedSources));
                    }
                }
            }
        }
    }

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

    for (Map.Entry<String, SortedSet<String>> entry : result.entrySet()) {
        finalResultBuilder.put(entry.getKey(), ImmutableSortedSet.copyOf(entry.getValue()));
    }
    return finalResultBuilder.build();
}