Search in sources :

Example 6 with UnionType

use of com.google.javascript.rhino.jstype.UnionType in project closure-compiler by google.

the class JSTypeReconserializer method recordUnionType.

private SeenTypeRecord recordUnionType(UnionType type) {
    checkNotNull(type);
    LinkedHashSet<SeenTypeRecord> altRecords = new LinkedHashSet<>();
    for (JSType altType : type.getAlternates()) {
        SeenTypeRecord alt = this.recordType(altType);
        if (alt.unionMembers == null) {
            altRecords.add(alt);
        } else {
            // Flatten out any nested unions. They are possible due to proxy-like types.
            altRecords.addAll(alt.unionMembers);
        }
    }
    // Some elements of the union may be equal as Colors
    if (altRecords.size() == 1) {
        return Iterables.getOnlyElement(altRecords);
    }
    ImmutableSet.Builder<ColorId> alternateIds = ImmutableSet.builder();
    for (SeenTypeRecord altRecord : altRecords) {
        alternateIds.add(altRecord.colorId);
    }
    ColorId unionId = ColorId.union(alternateIds.build());
    SeenTypeRecord record = this.getOrCreateRecord(unionId, type);
    if (record.unionMembers == null) {
        record.unionMembers = ImmutableSet.copyOf(altRecords);
    } else if (this.serializationMode.runValidation()) {
        checkState(altRecords.equals(record.unionMembers), "Unions with same ID must have same members: %s => %s == %s", unionId, altRecords.stream().map((r) -> r.colorId).collect(toImmutableSet()), record.unionMembers.stream().map((r) -> r.colorId).collect(toImmutableSet()));
    }
    return record;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) Iterables(com.google.common.collect.Iterables) JSType(com.google.javascript.rhino.jstype.JSType) Comparator.naturalOrder(java.util.Comparator.naturalOrder) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) ImmutableList(com.google.common.collect.ImmutableList) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) ColorId(com.google.javascript.jscomp.colors.ColorId) StandardColors(com.google.javascript.jscomp.colors.StandardColors) JSTypeRegistry(com.google.javascript.rhino.jstype.JSTypeRegistry) UnionType(com.google.javascript.rhino.jstype.UnionType) ImmutableMultimap(com.google.common.collect.ImmutableMultimap) InvalidatingTypes(com.google.javascript.jscomp.InvalidatingTypes) LinkedHashMultimap(com.google.common.collect.LinkedHashMultimap) LinkedHashSet(java.util.LinkedHashSet) Nullable(javax.annotation.Nullable) Node(com.google.javascript.rhino.Node) ObjectType(com.google.javascript.rhino.jstype.ObjectType) ImmutableSet(com.google.common.collect.ImmutableSet) IdentityHashMap(java.util.IdentityHashMap) ImmutableMap(com.google.common.collect.ImmutableMap) Predicate(java.util.function.Predicate) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) ClosurePrimitive(com.google.javascript.rhino.ClosurePrimitive) JSTypeNative(com.google.javascript.rhino.jstype.JSTypeNative) SetMultimap(com.google.common.collect.SetMultimap) Preconditions.checkState(com.google.common.base.Preconditions.checkState) Color(com.google.javascript.jscomp.colors.Color) FunctionType(com.google.javascript.rhino.jstype.FunctionType) TypePointers.isAxiomatic(com.google.javascript.jscomp.serialization.TypePointers.isAxiomatic) JSType(com.google.javascript.rhino.jstype.JSType) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) ImmutableSet(com.google.common.collect.ImmutableSet) ColorId(com.google.javascript.jscomp.colors.ColorId)

Example 7 with UnionType

use of com.google.javascript.rhino.jstype.UnionType in project closure-compiler by google.

the class PartialCompilationTest method testUnresolvedUnions.

@Test
public void testUnresolvedUnions() throws Exception {
    assertPartialCompilationSucceeds("/** @type {some.thing.Foo|some.thing.Bar} */", "var x;");
    TypedVar x = compiler.getTopScope().getSlot("x");
    assertWithMessage("type %s", x.getType()).that(x.getType().isUnionType()).isTrue();
    UnionType unionType = (UnionType) x.getType();
    Collection<JSType> alternatives = unionType.getAlternates();
    assertThat(alternatives).hasSize(3);
    int nullTypeCount = 0;
    List<String> namedTypes = new ArrayList<>();
    for (JSType alternative : alternatives) {
        assertThat(alternative.isNamedType() || alternative.isNullType()).isTrue();
        if (alternative.isNamedType()) {
            assertThat(alternative.isNoResolvedType()).isTrue();
            namedTypes.add(((NamedType) alternative).getReferenceName());
        }
        if (alternative.isNullType()) {
            nullTypeCount++;
        }
    }
    assertThat(nullTypeCount).isEqualTo(1);
    assertThat(namedTypes).containsExactly("some.thing.Foo", "some.thing.Bar");
}
Also used : UnionType(com.google.javascript.rhino.jstype.UnionType) JSType(com.google.javascript.rhino.jstype.JSType) ArrayList(java.util.ArrayList) Test(org.junit.Test)

Example 8 with UnionType

use of com.google.javascript.rhino.jstype.UnionType in project closure-compiler by google.

the class TypeInference method updateTypeOfArguments.

/**
 * Performs a limited back-inference on function arguments based on the expected parameter types.
 *
 * <p>Currently this only does back-inference in two cases: it infers the type of function literal
 * arguments and adds inferred properties to inferred object-typed arguments.
 *
 * <p>For example: if someone calls `Promise<string>.prototype.then` with `(result) => ...` then
 * we infer that the type of the arrow function is `function(string): ?`, and inside the arrow
 * function body we know that `result` is a string.
 */
private void updateTypeOfArguments(Node n, FunctionType fnType) {
    checkState(NodeUtil.isInvocation(n), n);
    Iterator<Parameter> parameters = fnType.getParameters().iterator();
    if (n.isTaggedTemplateLit()) {
        // subs, not an actual AST node, so there's nothing to update.
        if (!parameters.hasNext()) {
            // TypeCheck will warn if there is no first parameter. Just bail out here.
            return;
        }
        parameters.next();
    }
    Iterator<Node> arguments = NodeUtil.getInvocationArgsAsIterable(n).iterator();
    Parameter iParameter;
    Node iArgument;
    // Note: if there are too many or too few arguments, TypeCheck will warn.
    while (parameters.hasNext() && arguments.hasNext()) {
        iArgument = arguments.next();
        JSType iArgumentType = getJSType(iArgument);
        iParameter = parameters.next();
        JSType iParameterType = iParameter.getJSType() != null ? iParameter.getJSType() : unknownType;
        inferPropertyTypesToMatchConstraint(iArgumentType, iParameterType);
        // If the parameter to the call is a function expression, propagate the
        // function signature from the call site to the function node.
        // Filter out non-function types (such as null and undefined) as
        // we only care about FUNCTION subtypes here.
        FunctionType restrictedParameter = null;
        if (iParameterType.isUnionType()) {
            UnionType union = iParameterType.toMaybeUnionType();
            for (JSType alternative : union.getAlternates()) {
                if (alternative.isFunctionType()) {
                    // There is only one function type per union.
                    restrictedParameter = alternative.toMaybeFunctionType();
                    break;
                }
            }
        } else {
            restrictedParameter = iParameterType.toMaybeFunctionType();
        }
        if (restrictedParameter != null && iArgument.isFunction() && iArgumentType.isFunctionType()) {
            FunctionType argFnType = iArgumentType.toMaybeFunctionType();
            JSDocInfo argJsdoc = iArgument.getJSDocInfo();
            // Treat the parameter & return types of the function as 'declared' if the function has
            // JSDoc with type annotations, or a parameter has inline JSDoc.
            // Note that this does not distinguish between cases where all parameters have JSDoc vs
            // only one parameter has JSDoc.
            boolean declared = (argJsdoc != null && argJsdoc.containsDeclaration()) || NodeUtil.functionHasInlineJsdocs(iArgument);
            iArgument.setJSType(matchFunction(restrictedParameter, argFnType, declared));
        }
    }
}
Also used : UnionType(com.google.javascript.rhino.jstype.UnionType) JSType(com.google.javascript.rhino.jstype.JSType) Node(com.google.javascript.rhino.Node) FunctionType(com.google.javascript.rhino.jstype.FunctionType) Parameter(com.google.javascript.rhino.jstype.FunctionType.Parameter) JSDocInfo(com.google.javascript.rhino.JSDocInfo)

Aggregations

JSType (com.google.javascript.rhino.jstype.JSType)8 UnionType (com.google.javascript.rhino.jstype.UnionType)8 FunctionType (com.google.javascript.rhino.jstype.FunctionType)5 Node (com.google.javascript.rhino.Node)3 ObjectType (com.google.javascript.rhino.jstype.ObjectType)3 ImmutableList (com.google.common.collect.ImmutableList)2 TemplateType (com.google.javascript.rhino.jstype.TemplateType)2 TemplateTypeMap (com.google.javascript.rhino.jstype.TemplateTypeMap)2 TemplatizedType (com.google.javascript.rhino.jstype.TemplatizedType)2 ArrayList (java.util.ArrayList)2 Set (java.util.Set)2 Preconditions.checkNotNull (com.google.common.base.Preconditions.checkNotNull)1 Preconditions.checkState (com.google.common.base.Preconditions.checkState)1 ImmutableList.toImmutableList (com.google.common.collect.ImmutableList.toImmutableList)1 ImmutableMap (com.google.common.collect.ImmutableMap)1 ImmutableMultimap (com.google.common.collect.ImmutableMultimap)1 ImmutableSet (com.google.common.collect.ImmutableSet)1 ImmutableSet.toImmutableSet (com.google.common.collect.ImmutableSet.toImmutableSet)1 Iterables (com.google.common.collect.Iterables)1 LinkedHashMultimap (com.google.common.collect.LinkedHashMultimap)1