Java Code Examples for com.google.javascript.rhino.jstype.JSType#isUnionType()

The following examples show how to use com.google.javascript.rhino.jstype.JSType#isUnionType() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Closure_118_DisambiguateProperties_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Invalidates the given type, so that no properties on it will be renamed.
 */
private void addInvalidatingType(JSType type, JSError error) {
  type = type.restrictByNotNullOrUndefined();
  if (type.isUnionType()) {
    for (JSType alt : type.toMaybeUnionType().getAlternates()) {
      addInvalidatingType(alt, error);
    }
  } else if (type.isEnumElementType()) {
    addInvalidatingType(
        type.toMaybeEnumElementType().getPrimitiveType(), error);
  } else {
    typeSystem.addInvalidatingType(type);
    recordInvalidationError(type, error);
    ObjectType objType = ObjectType.cast(type);
    if (objType != null && objType.getImplicitPrototype() != null) {
      typeSystem.addInvalidatingType(objType.getImplicitPrototype());
      recordInvalidationError(objType.getImplicitPrototype(), error);
    }
  }
}
 
Example 2
Source File: DisambiguateProperties.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Override public Iterable<JSType> getTypeAlternatives(JSType type) {
  if (type.isUnionType()) {
    return type.toMaybeUnionType().getAlternates();
  } else {
    ObjectType objType = type.toObjectType();
    if (objType != null &&
        objType.getConstructor() != null &&
        objType.getConstructor().isInterface()) {
      List<JSType> list = Lists.newArrayList();
      for (FunctionType impl
               : registry.getDirectImplementors(objType)) {
        list.add(impl.getInstanceType());
      }
      return list;
    } else {
      return null;
    }
  }
}
 
Example 3
Source File: Closure_118_DisambiguateProperties_t.java    From coming with MIT License 6 votes vote down vote up
private ConcreteType maybeAddAutoboxes(
    ConcreteType cType, JSType jsType, String prop) {
  jsType = jsType.restrictByNotNullOrUndefined();
  if (jsType.isUnionType()) {
    for (JSType alt : jsType.toMaybeUnionType().getAlternates()) {
      cType = maybeAddAutoboxes(cType, alt, prop);
    }
    return cType;
  } else if (jsType.isEnumElementType()) {
    return maybeAddAutoboxes(
        cType, jsType.toMaybeEnumElementType().getPrimitiveType(), prop);
  }

  if (jsType.autoboxesTo() != null) {
    JSType autoboxed = jsType.autoboxesTo();
    return cType.unionWith(tt.getConcreteInstance((ObjectType) autoboxed));
  } else if (jsType.unboxesTo() != null) {
    return cType.unionWith(tt.getConcreteInstance((ObjectType) jsType));
  }

  return cType;
}
 
Example 4
Source File: RuntimeTypeCheck.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a function call to check that the given expression matches the
 * given type at runtime.
 *
 * <p>For example, if the type is {@code (string|Foo)}, the function call is
 * {@code checkType(expr, [valueChecker('string'), classChecker('Foo')])}.
 *
 * @return the function call node or {@code null} if the type is not checked
 */
private Node createCheckTypeCallNode(JSType type, Node expr) {
  Node arrayNode = IR.arraylit();
  Collection<JSType> alternates;
  if (type.isUnionType()) {
    alternates = Sets.newTreeSet(ALPHA);
    Iterables.addAll(alternates, type.toMaybeUnionType().getAlternates());
  } else {
    alternates = ImmutableList.of(type);
  }
  for (JSType alternate : alternates) {
    Node checkerNode = createCheckerNode(alternate);
    if (checkerNode == null) {
      return null;
    }
    arrayNode.addChildToBack(checkerNode);
  }
  return IR.call(jsCode("checkType"), expr, arrayNode);
}
 
Example 5
Source File: AmbiguateProperties.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** Returns true if properties on this type should not be renamed. */
private boolean isInvalidatingType(JSType type) {
  if (type.isUnionType()) {
    type = type.restrictByNotNullOrUndefined();
    if (type.isUnionType()) {
      for (JSType alt : type.toMaybeUnionType().getAlternates()) {
        if (isInvalidatingType(alt)) {
          return true;
        }
      }
      return false;
    }
  }
  ObjectType objType = ObjectType.cast(type);
  return objType == null
      || invalidatingTypes.contains(objType)
      || !objType.hasReferenceName()
      || objType.isUnknownType()
      || objType.isEmptyType() /* unresolved types */
      || objType.isEnumType()
      || objType.autoboxesTo() != null;
}
 
Example 6
Source File: DisambiguateProperties.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Invalidates the given type, so that no properties on it will be renamed.
 */
private void addInvalidatingType(JSType type, JSError error) {
  type = type.restrictByNotNullOrUndefined();
  if (type.isUnionType()) {
    for (JSType alt : type.toMaybeUnionType().getAlternates()) {
      addInvalidatingType(alt, error);
    }
  } else if (type.isEnumElementType()) {
    addInvalidatingType(
        type.toMaybeEnumElementType().getPrimitiveType(), error);
  } else {
    typeSystem.addInvalidatingType(type);
    recordInvalidationError(type, error);
    ObjectType objType = ObjectType.cast(type);
    if (objType != null && objType.getImplicitPrototype() != null) {
      typeSystem.addInvalidatingType(objType.getImplicitPrototype());
      recordInvalidationError(objType.getImplicitPrototype(), error);
    }
  }
}
 
Example 7
Source File: Closure_103_DisambiguateProperties_s.java    From coming with MIT License 6 votes vote down vote up
@Override public Iterable<JSType> getTypeAlternatives(JSType type) {
  if (type.isUnionType()) {
    return ((UnionType) type).getAlternates();
  } else {
    ObjectType objType = type.toObjectType();
    if (objType != null &&
        objType.getConstructor() != null &&
        objType.getConstructor().isInterface()) {
      List<JSType> list = Lists.newArrayList();
      for (FunctionType impl
               : registry.getDirectImplementors(objType)) {
        list.add(impl.getInstanceType());
      }
      return list;
    } else {
      return null;
    }
  }
}
 
Example 8
Source File: Closure_103_DisambiguateProperties_t.java    From coming with MIT License 6 votes vote down vote up
@Override public Iterable<JSType> getTypeAlternatives(JSType type) {
  if (type.isUnionType()) {
    return ((UnionType) type).getAlternates();
  } else {
    ObjectType objType = type.toObjectType();
    if (objType != null &&
        objType.getConstructor() != null &&
        objType.getConstructor().isInterface()) {
      List<JSType> list = Lists.newArrayList();
      for (FunctionType impl
               : registry.getDirectImplementors(objType)) {
        list.add(impl.getInstanceType());
      }
      return list;
    } else {
      return null;
    }
  }
}
 
Example 9
Source File: TightenTypes.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
private Collection<Action> getImplicitActionsFromArgument(
    Node arg, ObjectType thisType, JSType paramType) {
  if (paramType.isUnionType()) {
    List<Action> actions = Lists.newArrayList();
    for (JSType paramAlt : paramType.toMaybeUnionType().getAlternates()) {
      actions.addAll(
          getImplicitActionsFromArgument(arg, thisType, paramAlt));
    }
    return actions;
  } else if (paramType.isFunctionType()) {
    return Lists.<Action>newArrayList(createExternFunctionCall(
        arg, thisType, paramType.toMaybeFunctionType()));
  } else {
    return Lists.<Action>newArrayList(createExternFunctionCall(
        arg, thisType, null));
  }
}
 
Example 10
Source File: AmbiguateProperties.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/** Add this type to this property, calculating */
void addType(JSType newType) {
  if (skipAmbiguating) {
    return;
  }

  ++numOccurrences;

  if (newType.isUnionType()) {
    newType = newType.restrictByNotNullOrUndefined();
    if (newType.isUnionType()) {
      for (JSType alt : newType.toMaybeUnionType().getAlternates()) {
        addNonUnionType(alt);
      }
      return;
    }
  }
  addNonUnionType(newType);
}
 
Example 11
Source File: Closure_118_DisambiguateProperties_s.java    From coming with MIT License 5 votes vote down vote up
@Override public ImmutableSet<JSType> getTypesToSkipForType(JSType type) {
  type = type.restrictByNotNullOrUndefined();
  if (type.isUnionType()) {
    Set<JSType> types = Sets.newHashSet(type);
    for (JSType alt : type.toMaybeUnionType().getAlternates()) {
      types.addAll(getTypesToSkipForTypeNonUnion(alt));
    }
    return ImmutableSet.copyOf(types);
  } else if (type.isEnumElementType()) {
    return getTypesToSkipForType(
        type.toMaybeEnumElementType().getPrimitiveType());
  }
  return ImmutableSet.copyOf(getTypesToSkipForTypeNonUnion(type));
}
 
Example 12
Source File: Closure_118_DisambiguateProperties_t.java    From coming with MIT License 5 votes vote down vote up
@Override public ImmutableSet<JSType> getTypesToSkipForType(JSType type) {
  type = type.restrictByNotNullOrUndefined();
  if (type.isUnionType()) {
    Set<JSType> types = Sets.newHashSet(type);
    for (JSType alt : type.toMaybeUnionType().getAlternates()) {
      types.addAll(getTypesToSkipForTypeNonUnion(alt));
    }
    return ImmutableSet.copyOf(types);
  } else if (type.isEnumElementType()) {
    return getTypesToSkipForType(
        type.toMaybeEnumElementType().getPrimitiveType());
  }
  return ImmutableSet.copyOf(getTypesToSkipForTypeNonUnion(type));
}
 
Example 13
Source File: AmbiguateProperties.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Invalidates the given type, so that no properties on it will be renamed.
 */
private void addInvalidatingType(JSType type) {
  type = type.restrictByNotNullOrUndefined();
  if (type.isUnionType()) {
    for (JSType alt : type.toMaybeUnionType().getAlternates()) {
      addInvalidatingType(alt);
    }
  }

  invalidatingTypes.add(type);
  ObjectType objType = ObjectType.cast(type);
  if (objType != null && objType.isInstanceType()) {
    invalidatingTypes.add(objType.getImplicitPrototype());
  }
}
 
Example 14
Source File: Closure_6_TypeValidator_s.java    From coming with MIT License 5 votes vote down vote up
private boolean containsForwardDeclaredUnresolvedName(JSType type) {
  if (type.isUnionType()) {
    for (JSType alt : type.toMaybeUnionType().getAlternates()) {
      if (containsForwardDeclaredUnresolvedName(alt)) {
        return true;
      }
    }
  }
  return type.isNoResolvedType();
}
 
Example 15
Source File: DeclarationGenerator.java    From clutz with MIT License 5 votes vote down vote up
/**
 * Adds parentheses to turn a Type grammar production into a PrimaryType. See
 * https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#a-grammar
 *
 * <p>Avoid adding extra parens where the type is already known to be Primary.
 *
 * <p>PrimaryType: ParenthesizedType ParenthesizedType: ( Type )
 */
private void visitTypeAsPrimary(JSType type) {
  // These types will produce a non-primary grammar production
  if (!isLiteralFunction(type)
      && (type.isConstructor() || type.isFunctionType() || type.isUnionType())) {
    emit("(");
    visitType(type);
    emit(")");
  } else {
    visitType(type);
  }
}
 
Example 16
Source File: PeepholeFoldWithTypes.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Folds "typeof expression" based on the JSType of "expression" if the
 * expression has no side effects.
 *
 * <p>E.g.,
 * <pre>
 * var x = 6;
 * if (typeof(x) == "number") {
 * }
 * </pre>
 * folds to
 * <pre>
 * var x = 6;
 * if ("number" == "number") {
 * }
 * </pre>
 *
 * <p>This method doesn't fold literal values -- we leave that to
 * PeepholeFoldConstants.
 */
private Node tryFoldTypeof(Node typeofNode) {
  Preconditions.checkArgument(typeofNode.isTypeOf());
  Preconditions.checkArgument(typeofNode.getFirstChild() != null);

  Node argumentNode = typeofNode.getFirstChild();

  // We'll let PeepholeFoldConstants handle folding literals
  // and we can't remove arguments with possible side effects.
  if (!NodeUtil.isLiteralValue(argumentNode, true) &&
      !mayHaveSideEffects(argumentNode)) {
    JSType argumentType = argumentNode.getJSType();

    String typeName = null;

    if (argumentType != null) {
      // typeof null is "object" in JavaScript
      if (argumentType.isObject() || argumentType.isNullType()) {
        typeName = "object";
      } else if (argumentType.isStringValueType()) {
        typeName = "string";
      } else if (argumentType.isNumberValueType()) {
        typeName = "number";
      } else if (argumentType.isBooleanValueType()) {
        typeName = "boolean";
      } else if (argumentType.isVoidType()) {
         typeName = "undefined";
      } else if (argumentType.isUnionType()) {
        // TODO(dcc): We don't handle union types, for now,
        // but could support, say, unions of different object types
        // in the future.
        typeName = null;
      }

      if (typeName != null) {
        Node newNode = IR.string(typeName);
        typeofNode.getParent().replaceChild(typeofNode, newNode);
        reportCodeChange();

        return newNode;
      }
    }
  }
  return typeofNode;
}
 
Example 17
Source File: Closure_112_TypeInference_t.java    From coming with MIT License 4 votes vote down vote up
private void maybeResolveTemplatedType(
    JSType paramType,
    JSType argType,
    Map<TemplateType, JSType> resolvedTypes) {
  if (paramType.isTemplateType()) {
    // @param {T}
    resolvedTemplateType(
        resolvedTypes, paramType.toMaybeTemplateType(), argType);
  } else if (paramType.isUnionType()) {
    // @param {Array.<T>|NodeList|Arguments|{length:number}}
    UnionType unionType = paramType.toMaybeUnionType();
    for (JSType alernative : unionType.getAlternates()) {
      maybeResolveTemplatedType(alernative, argType, resolvedTypes);
    }
  } else if (paramType.isFunctionType()) {
    FunctionType paramFunctionType = paramType.toMaybeFunctionType();
    FunctionType argFunctionType = argType
        .restrictByNotNullOrUndefined()
        .collapseUnion()
        .toMaybeFunctionType();
    if (argFunctionType != null && argFunctionType.isSubtype(paramType)) {
      // infer from return type of the function type
      maybeResolveTemplatedType(
          paramFunctionType.getTypeOfThis(),
          argFunctionType.getTypeOfThis(), resolvedTypes);
      // infer from return type of the function type
      maybeResolveTemplatedType(
          paramFunctionType.getReturnType(),
          argFunctionType.getReturnType(), resolvedTypes);
      // infer from parameter types of the function type
      maybeResolveTemplateTypeFromNodes(
          paramFunctionType.getParameters(),
          argFunctionType.getParameters(), resolvedTypes);
    }
  } else if (paramType.isTemplatizedType()) {
    // @param {Array.<T>}
    ObjectType referencedParamType = paramType
        .toMaybeTemplatizedType()
        .getReferencedType();
    JSType argObjectType = argType
        .restrictByNotNullOrUndefined()
        .collapseUnion();

    if (argObjectType.isSubtype(referencedParamType)) {
      // If the argument type is a subtype of the parameter type, resolve any
      // template types amongst their templatized types.
      TemplateTypeMap paramTypeMap = paramType.getTemplateTypeMap();
      TemplateTypeMap argTypeMap = argObjectType.getTemplateTypeMap();
      for (TemplateType key : paramTypeMap.getTemplateKeys()) {
        maybeResolveTemplatedType(
            paramTypeMap.getTemplateType(key),
            argTypeMap.getTemplateType(key),
            resolvedTypes);
      }
    }
  }
}
 
Example 18
Source File: Closure_35_TypeInference_t.java    From coming with MIT License 4 votes vote down vote up
private BooleanOutcomePair traverseShortCircuitingBinOp(
    Node n, FlowScope scope, boolean condition) {
  Node left = n.getFirstChild();
  Node right = n.getLastChild();

  // type the left node
  BooleanOutcomePair leftLiterals =
      traverseWithinShortCircuitingBinOp(left,
          scope.createChildFlowScope());
  JSType leftType = left.getJSType();

  // reverse abstract interpret the left node to produce the correct
  // scope in which to verify the right node
  FlowScope rightScope = reverseInterpreter.
      getPreciserScopeKnowingConditionOutcome(
          left, leftLiterals.getOutcomeFlowScope(left.getType(), condition),
          condition);

  // type the right node
  BooleanOutcomePair rightLiterals =
      traverseWithinShortCircuitingBinOp(
          right, rightScope.createChildFlowScope());
  JSType rightType = right.getJSType();

  JSType type;
  BooleanOutcomePair literals;
  if (leftType != null && rightType != null) {
    leftType = leftType.getRestrictedTypeGivenToBooleanOutcome(!condition);
    if (leftLiterals.toBooleanOutcomes ==
        BooleanLiteralSet.get(!condition)) {
      // Use the restricted left type, since the right side never gets
      // evaluated.
      type = leftType;
      literals = leftLiterals;
    } else {
      // Use the join of the restricted left type knowing the outcome of the
      // ToBoolean predicate and of the right type.
      type = leftType.getLeastSupertype(rightType);
      literals =
          getBooleanOutcomePair(leftLiterals, rightLiterals, condition);
    }

    // Exclude the boolean type if the literal set is empty because a boolean
    // can never actually be returned.
    if (literals.booleanValues == BooleanLiteralSet.EMPTY &&
        getNativeType(BOOLEAN_TYPE).isSubtype(type)) {
      // Exclusion only make sense for a union type.
      if (type.isUnionType()) {
        type = type.toMaybeUnionType().getRestrictedUnion(
            getNativeType(BOOLEAN_TYPE));
      }
    }
  } else {
    type = null;
    literals = new BooleanOutcomePair(
        BooleanLiteralSet.BOTH, BooleanLiteralSet.BOTH,
        leftLiterals.getJoinedFlowScope(),
        rightLiterals.getJoinedFlowScope());
  }
  n.setJSType(type);

  return literals;
}
 
Example 19
Source File: Closure_112_TypeInference_t.java    From coming with MIT License 4 votes vote down vote up
private BooleanOutcomePair traverseShortCircuitingBinOp(
    Node n, FlowScope scope, boolean condition) {
  Node left = n.getFirstChild();
  Node right = n.getLastChild();

  // type the left node
  BooleanOutcomePair leftLiterals =
      traverseWithinShortCircuitingBinOp(left,
          scope.createChildFlowScope());
  JSType leftType = left.getJSType();

  // reverse abstract interpret the left node to produce the correct
  // scope in which to verify the right node
  FlowScope rightScope = reverseInterpreter.
      getPreciserScopeKnowingConditionOutcome(
          left, leftLiterals.getOutcomeFlowScope(left.getType(), condition),
          condition);

  // type the right node
  BooleanOutcomePair rightLiterals =
      traverseWithinShortCircuitingBinOp(
          right, rightScope.createChildFlowScope());
  JSType rightType = right.getJSType();

  JSType type;
  BooleanOutcomePair literals;
  if (leftType != null && rightType != null) {
    leftType = leftType.getRestrictedTypeGivenToBooleanOutcome(!condition);
    if (leftLiterals.toBooleanOutcomes ==
        BooleanLiteralSet.get(!condition)) {
      // Use the restricted left type, since the right side never gets
      // evaluated.
      type = leftType;
      literals = leftLiterals;
    } else {
      // Use the join of the restricted left type knowing the outcome of the
      // ToBoolean predicate and of the right type.
      type = leftType.getLeastSupertype(rightType);
      literals =
          getBooleanOutcomePair(leftLiterals, rightLiterals, condition);
    }

    // Exclude the boolean type if the literal set is empty because a boolean
    // can never actually be returned.
    if (literals.booleanValues == BooleanLiteralSet.EMPTY &&
        getNativeType(BOOLEAN_TYPE).isSubtype(type)) {
      // Exclusion only make sense for a union type.
      if (type.isUnionType()) {
        type = type.toMaybeUnionType().getRestrictedUnion(
            getNativeType(BOOLEAN_TYPE));
      }
    }
  } else {
    type = null;
    literals = new BooleanOutcomePair(
        BooleanLiteralSet.BOTH, BooleanLiteralSet.BOTH,
        leftLiterals.getJoinedFlowScope(),
        rightLiterals.getJoinedFlowScope());
  }
  n.setJSType(type);

  return literals;
}
 
Example 20
Source File: DeclarationGenerator.java    From clutz with MIT License 4 votes vote down vote up
/**
 * Closure Compiler does not support tuple types, and thus cannot express the proper type for
 * "Map<K, V>.entries()", which is an IterableIterator of a [K, V] tuple. The tighter tuple type
 * [K, V] allows destructuring loops "for (const [x, y] of ...)" with the tuple values getting
 * the right types assigned.
 *
 * <p>Given that maps are very common, as are for loops over them, this special cases methods
 * called "entries" that have the right return type.
 */
private boolean specialCaseMapEntries(String propName, FunctionType propertyType) {
  if (propertyType.getMaxArity() != 0 || !propName.equals("entries")) {
    return false;
  }

  // we have entries(): returnType
  JSType returnType = propertyType.getReturnType();
  if (!returnType.getDisplayName().equals("IteratorIterable")) {
    return false;
  }

  // we have entries(): IteratorIterable<valueType, iteratorReturnType, nextParamType>
  // TODO(b/140560697): Stop ignoring return and param types when upgrade to TS 3.6 is complete.
  //
  // In incremental mode IteratorIterable is noResolvedType, while in total mode it is
  // TemplatizedType.
  // They both have getTemplateTypes, but neither extends the other in the class hierarchy.
  final JSType valueType;
  if (returnType.isTemplatizedType()) {
    valueType = returnType.toMaybeTemplatizedType().getTemplateTypes().get(0);
  } else {
    // IteratorIterable must always have template types, even if they're unknown
    checkState(returnType.isNoResolvedType(), returnType);
    valueType = ((NoResolvedType) returnType).getTemplateTypes().get(0);
  }

  if (!isTemplateOf(valueType, "Array")) {
    return false;
  }

  // we have entries() : IteratorIterable<Array<arrayMembers>>
  JSType arrayMembers = valueType.toMaybeTemplatizedType().getTemplateTypes().get(0);
  if (!arrayMembers.isUnionType()
      || arrayMembers.toMaybeUnionType().getAlternates().size() != 2) {
    return false;
  }

  // we have entries() : IteratorIterable<Array<KEY|VALUE>
  emit("(): IterableIterator<[");
  Iterator<JSType> it = arrayMembers.toMaybeUnionType().getAlternates().iterator();
  visitType(it.next());
  emit(",");
  visitType(it.next());
  emit("]>;");
  emitBreak();
  return true;
}