Example usage for com.google.common.collect ImmutableList get

List of usage examples for com.google.common.collect ImmutableList get

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableList get.

Prototype

E get(int index);

Source Link

Document

Returns the element at the specified position in this list.

Usage

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

/**
 * Given a list of sources, return the one which is the root based on the defaults and user
 * parameters.//from  ww  w  .j a  va2  s .co m
 *
 * @param resolver SourcePathResolver for rule
 * @param crate Name of crate
 * @param defaults Default names for this rule (library, binary, etc)
 * @param sources List of sources
 * @return The matching source
 */
public static Optional<SourcePath> getCrateRoot(SourcePathResolver resolver, String crate,
        ImmutableSet<String> defaults, Stream<SourcePath> sources) {
    String crateName = String.format("%s.rs", crate);
    ImmutableList<SourcePath> res = sources.filter(src -> {
        String name = resolver.getRelativePath(src).getFileName().toString();
        return defaults.contains(name) || name.equals(crateName);
    }).collect(ImmutableList.toImmutableList());

    if (res.size() == 1) {
        return Optional.of(res.get(0));
    } else {
        return Optional.empty();
    }
}

From source file:com.google.template.soy.jbcsrc.BytecodeUtils.java

/**
 * Returns an expression that returns a new {@link LinkedHashMap} containing all the given 
 * entries./*from   w w w  .  j a v a 2s. c  om*/
 */
static Expression newLinkedHashMap(Iterable<? extends Expression> keys, Iterable<? extends Expression> values) {
    final ImmutableList<Expression> keysCopy = ImmutableList.copyOf(keys);
    final ImmutableList<Expression> valuesCopy = ImmutableList.copyOf(values);
    checkArgument(keysCopy.size() == valuesCopy.size());
    for (int i = 0; i < keysCopy.size(); i++) {
        checkArgument(keysCopy.get(i).resultType().getSort() == Type.OBJECT);
        checkArgument(valuesCopy.get(i).resultType().getSort() == Type.OBJECT);
    }
    final Expression construct = ConstructorRef.LINKED_HASH_MAP_SIZE
            .construct(constant(hashMapCapacity(keysCopy.size())));
    return new Expression(Type.getType(LinkedHashMap.class), Feature.NON_NULLABLE) {
        @Override
        void doGen(CodeBuilder mv) {
            construct.gen(mv);
            for (int i = 0; i < keysCopy.size(); i++) {
                Expression key = keysCopy.get(i);
                Expression value = valuesCopy.get(i);
                mv.dup();
                key.gen(mv);
                value.gen(mv);
                MethodRef.LINKED_HASH_MAP_PUT.invokeUnchecked(mv);
                mv.pop(); // pop the Object result of map.put
            }
        }
    };
}

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

private static Function<BuildTarget, PBXTarget> getTargetNodeToPBXTargetTransformFunction(
        final Multimap<BuildTarget, PBXTarget> buildTargetToTarget, final boolean buildWithBuck) {
    return input -> {
        ImmutableList<PBXTarget> targets = ImmutableList.copyOf(buildTargetToTarget.get(input));
        if (targets.size() == 1) {
            return targets.get(0);
        }/*from  w  w w.j a  v a2 s .co  m*/
        // The only reason why a build target would map to more than one project target is if
        // there are two project targets: one is the usual one, the other is a target that just
        // shells out to Buck.
        Preconditions.checkState(targets.size() == 2);
        PBXTarget first = targets.get(0);
        PBXTarget second = targets.get(1);
        Preconditions.checkState(first.getName().endsWith(ProjectGenerator.BUILD_WITH_BUCK_POSTFIX)
                ^ second.getName().endsWith(ProjectGenerator.BUILD_WITH_BUCK_POSTFIX));
        PBXTarget buildWithBuckTarget;
        PBXTarget buildWithXcodeTarget;
        if (first.getName().endsWith(ProjectGenerator.BUILD_WITH_BUCK_POSTFIX)) {
            buildWithBuckTarget = first;
            buildWithXcodeTarget = second;
        } else {
            buildWithXcodeTarget = first;
            buildWithBuckTarget = second;
        }
        return buildWithBuck ? buildWithBuckTarget : buildWithXcodeTarget;
    };
}

From source file:com.google.template.soy.jbcsrc.BytecodeUtils.java

private static Expression doShortCircuitingLogicalOperator(
        final ImmutableList<? extends Expression> expressions, final boolean isOrOperator) {
    checkArgument(!expressions.isEmpty());
    for (Expression expr : expressions) {
        expr.checkAssignableTo(Type.BOOLEAN_TYPE);
    }//w ww . j a v a  2  s  . com
    if (expressions.size() == 1) {
        return expressions.get(0);
    }

    return new Expression(Type.BOOLEAN_TYPE,
            Expression.areAllCheap(expressions) ? Features.of(Feature.CHEAP) : Features.of()) {
        @Override
        void doGen(CodeBuilder adapter) {
            Label end = new Label();
            Label shortCircuit = new Label();
            for (int i = 0; i < expressions.size(); i++) {
                Expression expr = expressions.get(i);
                expr.gen(adapter);
                if (i == expressions.size() - 1) {
                    // if we are the last one, just goto end. Whatever the result of the last expression is
                    // determines the result of the whole expression (when all prior tests fail).
                    adapter.goTo(end);
                } else {
                    adapter.ifZCmp(isOrOperator ? Opcodes.IFNE : Opcodes.IFEQ, shortCircuit);
                }
            }
            adapter.mark(shortCircuit);
            adapter.pushBoolean(isOrOperator); // default for || is true && is false
            adapter.mark(end);
        }
    };
}

From source file:com.facebook.presto.sql.gen.VarArgsToMapAdapterGenerator.java

/**
 * Generate byte code that/*from w  w w .jav a  2s . c  o  m*/
 * <p><ul>
 * <li>takes a specified number of variables as arguments (types of the arguments are provided in {@code javaTypes})
 * <li>put the variables in a map (keys of the map are provided in {@code names})
 * <li>invoke the provided {@code function} with the map
 * <li>return with the result of the function call (type must match {@code returnType})
 * </ul></p>
 */
public static MethodHandle generateVarArgsToMapAdapter(Class<?> returnType, List<Class<?>> javaTypes,
        List<String> names, Function<Map<String, Object>, Object> function) {
    CallSiteBinder callSiteBinder = new CallSiteBinder();

    ClassDefinition classDefinition = new ClassDefinition(a(PUBLIC, FINAL),
            makeClassName("VarArgsToMapAdapter"), type(Object.class));

    ImmutableList.Builder<Parameter> parameterListBuilder = ImmutableList.builder();
    for (int i = 0; i < javaTypes.size(); i++) {
        Class<?> javaType = javaTypes.get(i);
        parameterListBuilder.add(arg("input_" + i, javaType));
    }
    ImmutableList<Parameter> parameterList = parameterListBuilder.build();

    MethodDefinition methodDefinition = classDefinition.declareMethod(a(PUBLIC, STATIC), "varArgsToMap",
            type(returnType), parameterList);
    BytecodeBlock body = methodDefinition.getBody();

    // ImmutableMap.Builder can not be used here because it doesn't allow nulls.
    Variable map = methodDefinition.getScope().declareVariable("map", methodDefinition.getBody(), invokeStatic(
            Maps.class, "newHashMapWithExpectedSize", HashMap.class, constantInt(javaTypes.size())));
    for (int i = 0; i < javaTypes.size(); i++) {
        body.append(map.invoke("put", Object.class, constantString(names.get(i)).cast(Object.class),
                parameterList.get(i).cast(Object.class)));
    }
    body.append(loadConstant(callSiteBinder, function, Function.class)
            .invoke("apply", Object.class, map.cast(Object.class)).cast(returnType).ret());

    Class<?> generatedClass = defineClass(classDefinition, Object.class, callSiteBinder.getBindings(),
            new DynamicClassLoader(VarArgsToMapAdapterGenerator.class.getClassLoader()));
    return Reflection.methodHandle(generatedClass, "varArgsToMap",
            javaTypes.toArray(new Class<?>[javaTypes.size()]));
}

From source file:io.prestosql.sql.gen.VarArgsToMapAdapterGenerator.java

/**
 * Generate byte code that//  www . java  2  s .  c  o  m
 * <p><ul>
 * <li>takes a specified number of variables as arguments (types of the arguments are provided in {@code javaTypes})
 * <li>put the variables in a map (keys of the map are provided in {@code names})
 * <li>invoke the provided {@code function} with the map
 * <li>return with the result of the function call (type must match {@code returnType})
 * </ul></p>
 */
public static MethodHandle generateVarArgsToMapAdapter(Class<?> returnType, List<Class<?>> javaTypes,
        List<String> names, Function<Map<String, Object>, Object> function) {
    checkCondition(javaTypes.size() <= 254, NOT_SUPPORTED, "Too many arguments for vararg function");
    CallSiteBinder callSiteBinder = new CallSiteBinder();

    ClassDefinition classDefinition = new ClassDefinition(a(PUBLIC, FINAL),
            makeClassName("VarArgsToMapAdapter"), type(Object.class));

    ImmutableList.Builder<Parameter> parameterListBuilder = ImmutableList.builder();
    for (int i = 0; i < javaTypes.size(); i++) {
        Class<?> javaType = javaTypes.get(i);
        parameterListBuilder.add(arg("input_" + i, javaType));
    }
    ImmutableList<Parameter> parameterList = parameterListBuilder.build();

    MethodDefinition methodDefinition = classDefinition.declareMethod(a(PUBLIC, STATIC), "varArgsToMap",
            type(returnType), parameterList);
    BytecodeBlock body = methodDefinition.getBody();

    // ImmutableMap.Builder can not be used here because it doesn't allow nulls.
    Variable map = methodDefinition.getScope().declareVariable("map", methodDefinition.getBody(), invokeStatic(
            Maps.class, "newHashMapWithExpectedSize", HashMap.class, constantInt(javaTypes.size())));
    for (int i = 0; i < javaTypes.size(); i++) {
        body.append(map.invoke("put", Object.class, constantString(names.get(i)).cast(Object.class),
                parameterList.get(i).cast(Object.class)));
    }
    body.append(loadConstant(callSiteBinder, function, Function.class)
            .invoke("apply", Object.class, map.cast(Object.class)).cast(returnType).ret());

    Class<?> generatedClass = defineClass(classDefinition, Object.class, callSiteBinder.getBindings(),
            new DynamicClassLoader(VarArgsToMapAdapterGenerator.class.getClassLoader()));
    return Reflection.methodHandle(generatedClass, "varArgsToMap",
            javaTypes.toArray(new Class<?>[javaTypes.size()]));
}

From source file:com.android.manifmerger.PreValidator.java

/**
 * Checks that an element which is supposed to have a key does have one.
 * @param mergingReport report to log warnings and errors.
 * @param xmlElement xml element to check for key presence.
 * @return true if the element has a valid key or false it does not need one or it is invalid.
 *///from w w  w  .  ja  va 2 s. c o m
private static boolean checkKeyPresence(MergingReport.Builder mergingReport, XmlElement xmlElement) {
    ManifestModel.NodeKeyResolver nodeKeyResolver = xmlElement.getType().getNodeKeyResolver();
    ImmutableList<String> keyAttributesNames = nodeKeyResolver.getKeyAttributesNames();
    if (keyAttributesNames.isEmpty()) {
        return false;
    }
    if (Strings.isNullOrEmpty(xmlElement.getKey())) {
        // we should have a key but we don't.
        String message = keyAttributesNames.size() > 1
                ? String.format("Missing one of the key attributes '%1$s' on element %2$s at %3$s",
                        Joiner.on(',').join(keyAttributesNames), xmlElement.getId(), xmlElement.printPosition())
                : String.format("Missing '%1$s' key attribute on element %2$s at %3$s",
                        keyAttributesNames.get(0), xmlElement.getId(), xmlElement.printPosition());
        xmlElement.addMessage(mergingReport, ERROR, message);
        return false;
    }
    return true;
}

From source file:me.Wundero.Ray.utils.TextSplitter.java

private static Text transformTranslationText(TranslatableText text, Locale locale) {
    // This is bad, don't look
    Translation translation = text.getTranslation();
    ImmutableList<Object> arguments = text.getArguments();
    Object[] markers = new Object[arguments.size()];
    for (int i = 0; i < markers.length; i++) {
        markers[i] = "$MARKER" + i + "$";
    }//  w  w w  . j  a v  a 2 s.c o  m
    String patched = translation.get(locale, markers);

    List<Object> sections = Lists.newArrayList();
    Matcher m = MARKER_PATTERN.matcher(patched);
    int prevPos = 0;
    while (m.find()) {
        if (m.start() != prevPos) {
            sections.add(patched.substring(prevPos, m.start()));
        }
        int index = Integer.parseInt(m.group(1));
        sections.add(arguments.get(index));
        prevPos = m.end();
    }
    if (prevPos != patched.length() - 1) {
        sections.add(patched.substring(prevPos));
    }
    Text.Builder builder = new Format(text).applyToBuilder(Text.builder());
    for (Object val : sections) {
        builder.append(Text.of(val));
    }
    builder.append(text.getChildren());
    return builder.build();
}

From source file:com.google.javascript.jscomp.PolymerClassDefinition.java

/**
 * Validates the class definition and if valid, destructively extracts the class definition from
 * the AST./*from   www .j a  v  a  2  s . c  om*/
 */
@Nullable
static PolymerClassDefinition extractFromCallNode(Node callNode, AbstractCompiler compiler,
        GlobalNamespace globalNames) {
    Node descriptor = NodeUtil.getArgumentForCallOrNew(callNode, 0);
    if (descriptor == null || !descriptor.isObjectLit()) {
        // report bad class definition
        compiler.report(JSError.make(callNode, PolymerPassErrors.POLYMER_DESCRIPTOR_NOT_VALID));
        return null;
    }

    int paramCount = callNode.getChildCount() - 1;
    if (paramCount != 1) {
        compiler.report(JSError.make(callNode, PolymerPassErrors.POLYMER_UNEXPECTED_PARAMS));
        return null;
    }

    Node elName = NodeUtil.getFirstPropMatchingKey(descriptor, "is");
    if (elName == null) {
        compiler.report(JSError.make(callNode, PolymerPassErrors.POLYMER_MISSING_IS));
        return null;
    }

    Node target;
    if (NodeUtil.isNameDeclaration(callNode.getGrandparent())) {
        target = IR.name(callNode.getParent().getString());
    } else if (callNode.getParent().isAssign()) {
        target = callNode.getParent().getFirstChild().cloneTree();
    } else {
        String elNameStringBase = elName.isQualifiedName() ? elName.getQualifiedName().replace('.', '$')
                : elName.getString();
        String elNameString = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, elNameStringBase);
        elNameString += "Element";
        target = IR.name(elNameString);
    }

    JSDocInfo classInfo = NodeUtil.getBestJSDocInfo(target);

    JSDocInfo ctorInfo = null;
    Node constructor = NodeUtil.getFirstPropMatchingKey(descriptor, "factoryImpl");
    if (constructor == null) {
        constructor = NodeUtil.emptyFunction();
        compiler.reportChangeToChangeScope(constructor);
        constructor.useSourceInfoFromForTree(callNode);
    } else {
        ctorInfo = NodeUtil.getBestJSDocInfo(constructor);
    }

    Node baseClass = NodeUtil.getFirstPropMatchingKey(descriptor, "extends");
    String nativeBaseElement = baseClass == null ? null : baseClass.getString();

    Node behaviorArray = NodeUtil.getFirstPropMatchingKey(descriptor, "behaviors");
    PolymerBehaviorExtractor behaviorExtractor = new PolymerBehaviorExtractor(compiler, globalNames);
    ImmutableList<BehaviorDefinition> behaviors = behaviorExtractor.extractBehaviors(behaviorArray);
    List<MemberDefinition> allProperties = new ArrayList<>();
    for (BehaviorDefinition behavior : behaviors) {
        overwriteMembersIfPresent(allProperties, behavior.props);
    }
    overwriteMembersIfPresent(allProperties,
            PolymerPassStaticUtils.extractProperties(descriptor, DefinitionType.ObjectLiteral, compiler,
                    /** constructor= */
                    null));

    FeatureSet newFeatures = null;
    if (!behaviors.isEmpty()) {
        newFeatures = behaviors.get(0).features;
        for (int i = 1; i < behaviors.size(); i++) {
            newFeatures = newFeatures.union(behaviors.get(i).features);
        }
    }

    List<MemberDefinition> methods = new ArrayList<>();
    for (Node keyNode : descriptor.children()) {
        boolean isFunctionDefinition = keyNode.isMemberFunctionDef()
                || (keyNode.isStringKey() && keyNode.getFirstChild().isFunction());
        if (isFunctionDefinition) {
            methods.add(
                    new MemberDefinition(NodeUtil.getBestJSDocInfo(keyNode), keyNode, keyNode.getFirstChild()));
        }
    }

    return new PolymerClassDefinition(DefinitionType.ObjectLiteral, callNode, target, descriptor, classInfo,
            new MemberDefinition(ctorInfo, null, constructor), nativeBaseElement, allProperties, methods,
            behaviors, newFeatures);
}

From source file:com.github.rinde.rinsim.central.arrays.ArraysSolvers.java

static int[][] toInventoriesArray(GlobalStateObject state, ArraysObject sva) {
    final UnmodifiableIterator<VehicleStateObject> iterator = state.getVehicles().iterator();

    final ImmutableList.Builder<ImmutableList<Integer>> invPairBuilder = ImmutableList.builder();
    for (int i = 0; i < state.getVehicles().size(); i++) {
        final VehicleStateObject cur = iterator.next();
        for (final Parcel dp : cur.getContents()) {
            invPairBuilder.add(ImmutableList.of(i, sva.parcel2index.get(dp).deliveryIndex));
        }/*from   w w w .ja  v  a2s .  c  om*/
    }
    final ImmutableList<ImmutableList<Integer>> inventoryPairs = invPairBuilder.build();

    final int[][] inventories = new int[inventoryPairs.size()][2];
    for (int i = 0; i < inventoryPairs.size(); i++) {
        inventories[i][0] = inventoryPairs.get(i).get(0);
        inventories[i][1] = inventoryPairs.get(i).get(1);
    }
    return inventories;
}