com.google.javascript.rhino.jstype.FunctionType Java Examples

The following examples show how to use com.google.javascript.rhino.jstype.FunctionType. 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: Nopol2017_0051_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Enforces type casts, and ensures the node is typed.
 *
 * A cast in the way that we use it in JSDoc annotations never
 * alters the generated code and therefore never can induce any runtime
 * operation. What this means is that a 'cast' is really just a compile
 * time constraint on the underlying value. In the future, we may add
 * support for run-time casts for compiled tests.
 *
 * To ensure some shred of sanity, we enforce the notion that the
 * type you are casting to may only meaningfully be a narrower type
 * than the underlying declared type. We also invalidate optimizations
 * on bad type casts.
 *
 * @param t The traversal object needed to report errors.
 * @param n The node getting a type assigned to it.
 * @param type The type to be assigned.
 */
private void ensureTyped(NodeTraversal t, Node n, JSType type) {
  // Make sure FUNCTION nodes always get function type.
  Preconditions.checkState(n.getType() != Token.FUNCTION ||
          type instanceof FunctionType ||
          type.isUnknownType());
  JSDocInfo info = n.getJSDocInfo();
  if (info != null) {
    if (info.hasType()) {
      JSType infoType = info.getType().evaluate(t.getScope(), typeRegistry);
      validator.expectCanCast(t, n, infoType, type);
      type = infoType;
    }

    if (info.isImplicitCast() && !inExterns) {
      String propName = n.getType() == Token.GETPROP ?
          n.getLastChild().getString() : "(missing)";
      compiler.report(
          t.makeError(n, ILLEGAL_IMPLICIT_CAST, propName));
    }
  }

  if (n.getJSType() == null) {
    n.setJSType(type);
  }
}
 
Example #2
Source File: SemanticReverseAbstractInterpreter.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@Override
public JSType caseObjectType(ObjectType type) {
  if (target.isUnknownType()) {
    return type;
  }

  FunctionType funcTarget = target.toMaybeFunctionType();
  if (funcTarget.hasInstanceType()) {
    if (type.isSubtype(funcTarget.getInstanceType())) {
      return null;
    }

    return type;
  }

  return null;
}
 
Example #3
Source File: Closure_70_TypedScopeCreator_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Declares all of a function's arguments.
 */
private void declareArguments(Node functionNode) {
  Node astParameters = functionNode.getFirstChild().getNext();
  Node body = astParameters.getNext();
  FunctionType functionType = (FunctionType) functionNode.getJSType();
  if (functionType != null) {
    Node jsDocParameters = functionType.getParametersNode();
    if (jsDocParameters != null) {
      Node jsDocParameter = jsDocParameters.getFirstChild();
      for (Node astParameter : astParameters.children()) {
        if (jsDocParameter != null) {
          defineSlot(astParameter, functionNode,
              jsDocParameter.getJSType(), false);
          jsDocParameter = jsDocParameter.getNext();
        } else {
          defineSlot(astParameter, functionNode, null, true);
        }
      }
    }
  }
}
 
Example #4
Source File: Closure_69_TypeCheck_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Visits a NEW node.
 */
private void visitNew(NodeTraversal t, Node n) {
  Node constructor = n.getFirstChild();
  FunctionType type = getFunctionType(constructor);
  if (type != null && type.isConstructor()) {
    visitParameterList(t, n, type);
    ensureTyped(t, n, type.getInstanceType());
  } else {
    // TODO(user): add support for namespaced objects.
    if (constructor.getType() != Token.GETPROP) {
      // TODO(user): make the constructor node have lineno/charno
      // and use constructor for a more precise error indication.
      // It seems that GETPROP nodes are missing this information.
      Node line;
      if (constructor.getLineno() < 0 || constructor.getCharno() < 0) {
        line = n;
      } else {
        line = constructor;
      }
      report(t, line, NOT_A_CONSTRUCTOR);
    }
    ensureTyped(t, n);
  }
}
 
Example #5
Source File: Closure_95_TypedScopeCreator_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Find the function that's being overridden on this type, if any.
 */
private FunctionType findOverriddenFunction(
    ObjectType ownerType, String propName) {
  // First, check to see if the property is implemented
  // on a superclass.
  JSType propType = ownerType.getPropertyType(propName);
  if (propType instanceof FunctionType) {
    return (FunctionType) propType;
  } else {
    // If it's not, then check to see if it's implemented
    // on an implemented interface.
    for (ObjectType iface :
             ownerType.getCtorImplementedInterfaces()) {
      propType = iface.getPropertyType(propName);
      if (propType instanceof FunctionType) {
        return (FunctionType) propType;
      }
    }
  }

  return null;
}
 
Example #6
Source File: Closure_96_TypeCheck_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Enforces type casts, and ensures the node is typed.
 *
 * A cast in the way that we use it in JSDoc annotations never
 * alters the generated code and therefore never can induce any runtime
 * operation. What this means is that a 'cast' is really just a compile
 * time constraint on the underlying value. In the future, we may add
 * support for run-time casts for compiled tests.
 *
 * To ensure some shred of sanity, we enforce the notion that the
 * type you are casting to may only meaningfully be a narrower type
 * than the underlying declared type. We also invalidate optimizations
 * on bad type casts.
 *
 * @param t The traversal object needed to report errors.
 * @param n The node getting a type assigned to it.
 * @param type The type to be assigned.
 */
private void ensureTyped(NodeTraversal t, Node n, JSType type) {
  // Make sure FUNCTION nodes always get function type.
  Preconditions.checkState(n.getType() != Token.FUNCTION ||
          type instanceof FunctionType ||
          type.isUnknownType());
  JSDocInfo info = n.getJSDocInfo();
  if (info != null) {
    if (info.hasType()) {
      JSType infoType = info.getType().evaluate(t.getScope(), typeRegistry);
      validator.expectCanCast(t, n, infoType, type);
      type = infoType;
    }

    if (info.isImplicitCast() && !inExterns) {
      String propName = n.getType() == Token.GETPROP ?
          n.getLastChild().getString() : "(missing)";
      compiler.report(
          t.makeError(n, ILLEGAL_IMPLICIT_CAST, propName));
    }
  }

  if (n.getJSType() == null) {
    n.setJSType(type);
  }
}
 
Example #7
Source File: Nopol2017_0051_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Given a constructor or an interface type, find out whether the unknown
 * type is a supertype of the current type.
 */
private static boolean hasUnknownOrEmptySupertype(FunctionType ctor) {
  Preconditions.checkArgument(ctor.isConstructor() || ctor.isInterface());
  Preconditions.checkArgument(!ctor.isUnknownType());

  // The type system should notice inheritance cycles on its own
  // and break the cycle.
  while (true) {
    ObjectType maybeSuperInstanceType =
        ctor.getPrototype().getImplicitPrototype();
    if (maybeSuperInstanceType == null) {
      return false;
    }
    if (maybeSuperInstanceType.isUnknownType() ||
        maybeSuperInstanceType.isEmptyType()) {
      return true;
    }
    ctor = maybeSuperInstanceType.getConstructor();
    if (ctor == null) {
      return false;
    }
    Preconditions.checkState(ctor.isConstructor() || ctor.isInterface());
  }
}
 
Example #8
Source File: TightenTypes.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Adds all subtypes of the given type to the provided set.
 * @return false if the all type was encountered, else true.
 */
private boolean getSubTypes(FunctionType type, Set<ConcreteType> set) {
  if (type.getSubTypes() != null) {
    for (FunctionType sub : type.getSubTypes()) {
      ConcreteType concrete = createType(sub);
      if (concrete.isFunction()
          && concrete.toFunction().getInstanceType() != null) {
        concrete = concrete.toFunction().getInstanceType();
        if (!set.contains(concrete)) {
          set.add(concrete);
          if (!getSubTypes(sub, set)) {
            return false;
          }
        }
      } else {
        // The only time we should find a subtype that doesn't have an
        // instance type is for the odd case of ActiveXObject, which is
        // of the NoObject type and will be returned as a subtype of Object.
        set.clear();
        set.add(ConcreteType.ALL);
        return false;
      }
    }
  }
  return true;
}
 
Example #9
Source File: Closure_35_TypeInference_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Traverse a return value.
 */
private FlowScope traverseReturn(Node n, FlowScope scope) {
  scope = traverseChildren(n, scope);

  Node retValue = n.getFirstChild();
  if (retValue != null) {
    JSType type = functionScope.getRootNode().getJSType();
    if (type != null) {
      FunctionType fnType = type.toMaybeFunctionType();
      if (fnType != null) {
        inferPropertyTypesToMatchConstraint(
            retValue.getJSType(), fnType.getReturnType());
      }
    }
  }
  return scope;
}
 
Example #10
Source File: RuntimeTypeCheck.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
private void visitFunction(NodeTraversal t, Node n) {
  FunctionType funType = n.getJSType().toMaybeFunctionType();
  if (funType != null && !funType.isConstructor()) {
    return;
  }

  Node nodeToInsertAfter = findNodeToInsertAfter(n);

  nodeToInsertAfter = addMarker(funType, nodeToInsertAfter, null);

  TreeSet<ObjectType> stuff = Sets.newTreeSet(ALPHA);
  Iterables.addAll(stuff, funType.getAllImplementedInterfaces());
  for (ObjectType interfaceType : stuff) {
    nodeToInsertAfter =
        addMarker(funType, nodeToInsertAfter, interfaceType);
  }
}
 
Example #11
Source File: InferJSDocInfoTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
public void testAbstractMethod() {
  testSame(
      "/** Abstract method. \n * @type {!Function} */ var abstractMethod;" +
      "/** @constructor */ function Foo() {}" +
      "/** Block description. \n * @param {number} x */" +
      "Foo.prototype.bar = abstractMethod;");
  FunctionType abstractMethod =
      (FunctionType) findGlobalNameType("abstractMethod");
  assertNull(abstractMethod.getJSDocInfo());

  FunctionType ctor = (FunctionType) findGlobalNameType("Foo");
  ObjectType proto = ctor.getInstanceType().getImplicitPrototype();
  FunctionType method = (FunctionType) proto.getPropertyType("bar");
  assertEquals(
      "Block description.",
      method.getJSDocInfo().getBlockDescription());
  assertEquals(
      "Block description.",
      proto.getOwnPropertyJSDocInfo("bar").getBlockDescription());
}
 
Example #12
Source File: ClosureCodingConventionTest.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
public void testApplySubclassRelationship() {
  JSTypeRegistry registry = new JSTypeRegistry(null);

  Node nodeA = new Node(Token.FUNCTION);
  FunctionType ctorA = registry.createConstructorType("A", nodeA,
      new Node(Token.PARAM_LIST), null, null);

  Node nodeB = new Node(Token.FUNCTION);
  FunctionType ctorB = registry.createConstructorType("B", nodeB,
      new Node(Token.PARAM_LIST), null, null);

  conv.applySubclassRelationship(ctorA, ctorB, SubclassType.INHERITS);

  assertTrue(ctorB.getPrototype().hasOwnProperty("constructor"));
  assertEquals(nodeB, ctorB.getPrototype().getPropertyNode("constructor"));

  assertTrue(ctorB.hasOwnProperty("superClass_"));
  assertEquals(nodeB, ctorB.getPropertyNode("superClass_"));
}
 
Example #13
Source File: Closure_69_TypeCheck_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Enforces type casts, and ensures the node is typed.
 *
 * A cast in the way that we use it in JSDoc annotations never
 * alters the generated code and therefore never can induce any runtime
 * operation. What this means is that a 'cast' is really just a compile
 * time constraint on the underlying value. In the future, we may add
 * support for run-time casts for compiled tests.
 *
 * To ensure some shred of sanity, we enforce the notion that the
 * type you are casting to may only meaningfully be a narrower type
 * than the underlying declared type. We also invalidate optimizations
 * on bad type casts.
 *
 * @param t The traversal object needed to report errors.
 * @param n The node getting a type assigned to it.
 * @param type The type to be assigned.
 */
private void ensureTyped(NodeTraversal t, Node n, JSType type) {
  // Make sure FUNCTION nodes always get function type.
  Preconditions.checkState(n.getType() != Token.FUNCTION ||
          type instanceof FunctionType ||
          type.isUnknownType());
  JSDocInfo info = n.getJSDocInfo();
  if (info != null) {
    if (info.hasType()) {
      JSType infoType = info.getType().evaluate(t.getScope(), typeRegistry);
      validator.expectCanCast(t, n, infoType, type);
      type = infoType;
    }

    if (info.isImplicitCast() && !inExterns) {
      String propName = n.getType() == Token.GETPROP ?
          n.getLastChild().getString() : "(missing)";
      compiler.report(
          t.makeError(n, ILLEGAL_IMPLICIT_CAST, propName));
    }
  }

  if (n.getJSType() == null) {
    n.setJSType(type);
  }
}
 
Example #14
Source File: Nopol2017_0029_s.java    From coming with MIT License 6 votes vote down vote up
/**
 * Given a constructor or an interface type, find out whether the unknown
 * type is a supertype of the current type.
 */
private static boolean hasUnknownOrEmptySupertype(FunctionType ctor) {
  Preconditions.checkArgument(ctor.isConstructor() || ctor.isInterface());
  Preconditions.checkArgument(!ctor.isUnknownType());

  // The type system should notice inheritance cycles on its own
  // and break the cycle.
  while (true) {
    ObjectType maybeSuperInstanceType =
        ctor.getPrototype().getImplicitPrototype();
    if (maybeSuperInstanceType == null) {
      return false;
    }
    if (maybeSuperInstanceType.isUnknownType() ||
        maybeSuperInstanceType.isEmptyType()) {
      return true;
    }
    ctor = maybeSuperInstanceType.getConstructor();
    if (ctor == null) {
      return false;
    }
    Preconditions.checkState(ctor.isConstructor() || ctor.isInterface());
  }
}
 
Example #15
Source File: Closure_48_TypedScopeCreator_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Find the function that's being overridden on this type, if any.
 */
private FunctionType findOverriddenFunction(
    ObjectType ownerType, String propName) {
  // First, check to see if the property is implemented
  // on a superclass.
  JSType propType = ownerType.getPropertyType(propName);
  if (propType != null && propType.isFunctionType()) {
    return propType.toMaybeFunctionType();
  } else {
    // If it's not, then check to see if it's implemented
    // on an implemented interface.
    for (ObjectType iface :
             ownerType.getCtorImplementedInterfaces()) {
      propType = iface.getPropertyType(propName);
      if (propType != null && propType.isFunctionType()) {
        return propType.toMaybeFunctionType();
      }
    }
  }

  return null;
}
 
Example #16
Source File: TypeInspector.java    From js-dossier with Apache License 2.0 6 votes vote down vote up
private NamedType getPropertyLink(NominalType context, InstanceProperty property) {
  JSType type = property.getDefinedByType();
  TypeExpressionParser parser =
      expressionParserFactory.create(linkFactory.withTypeContext(context));

  if (property.getOwnerType().isPresent()) {
    type = property.getOwnerType().get().getType();
  }

  if (type.isConstructor() || type.isInterface()) {
    type = ((FunctionType) type).getInstanceType();
  }
  type = stripTemplateTypeInformation(type);

  return buildPropertyLink(parser, type, property.getName());
}
 
Example #17
Source File: AbstractClosureVisitor.java    From jsinterop-generator with Apache License 2.0 6 votes vote down vote up
protected ParameterNameInfo getParameterInfo(
    FunctionType functionType, int parameterIndex, String parentFqn) {

  if (functionType.getSource() != null) {
    String originalName =
        NodeUtil.getFunctionParameters(functionType.getSource())
            .getChildAtIndex(parameterIndex)
            .getString();
    return getParameterInfo(parentFqn, originalName, false);
  }

  // functionType doesn't have source, it's a anonymous function type.
  // e.g.: /** @type {function(Event):boolean} */ var eventCallback;
  // Parameters for anonymous FunctionType don't have names.
  return getParameterInfo(parentFqn, "p" + parameterIndex, true);
}
 
Example #18
Source File: InheritanceVisitor.java    From jsinterop-generator with Apache License 2.0 5 votes vote down vote up
private Optional<ObjectType> getSuperType(FunctionType type) {
  ObjectType proto = type.getPrototype();
  if (proto == null) {
    return Optional.empty();
  }

  ObjectType implicitProto = proto.getImplicitPrototype();
  if (implicitProto == null) {
    return Optional.empty();
  }

  return "Object".equals(implicitProto.getDisplayName())
      ? Optional.empty()
      : Optional.of(implicitProto);
}
 
Example #19
Source File: NameReferenceGraphConstruction.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Look for the super class implementation up the tree.
 */
private void recordSuperClassPrototypePropUse(
    FunctionType classType, String prop, Reference ref) {
  FunctionType superClass = classType.getSuperClassConstructor();
  while (superClass != null) {
    if (superClass.getPrototype().hasOwnProperty(prop)) {
      graph.connect(getNamedContainingFunction(), ref,
          graph.defineNameIfNotExists(
             superClass.getReferenceName() + ".prototype." + prop, false));
      return;
    } else {
      superClass = superClass.getSuperClassConstructor();
    }
  }
}
 
Example #20
Source File: Closure_43_TypedScopeCreator_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Apply special properties that only apply to delegates.
 */
private void applyDelegateRelationship(
    DelegateRelationship delegateRelationship) {
  ObjectType delegatorObject = ObjectType.cast(
      typeRegistry.getType(delegateRelationship.delegator));
  ObjectType delegateBaseObject = ObjectType.cast(
      typeRegistry.getType(delegateRelationship.delegateBase));
  ObjectType delegateSuperObject = ObjectType.cast(
      typeRegistry.getType(codingConvention.getDelegateSuperclassName()));
  if (delegatorObject != null &&
      delegateBaseObject != null &&
      delegateSuperObject != null) {
    FunctionType delegatorCtor = delegatorObject.getConstructor();
    FunctionType delegateBaseCtor = delegateBaseObject.getConstructor();
    FunctionType delegateSuperCtor = delegateSuperObject.getConstructor();

    if (delegatorCtor != null && delegateBaseCtor != null &&
        delegateSuperCtor != null) {
      FunctionParamBuilder functionParamBuilder =
          new FunctionParamBuilder(typeRegistry);
      functionParamBuilder.addRequiredParams(
          getNativeType(U2U_CONSTRUCTOR_TYPE));
      FunctionType findDelegate = typeRegistry.createFunctionType(
          typeRegistry.createDefaultObjectUnion(delegateBaseObject),
          functionParamBuilder.build());

      FunctionType delegateProxy = typeRegistry.createConstructorType(
          delegateBaseObject.getReferenceName() + DELEGATE_PROXY_SUFFIX,
          null, null, null);
      delegateProxy.setPrototypeBasedOn(delegateBaseObject);

      codingConvention.applyDelegateRelationship(
          delegateSuperObject, delegateBaseObject, delegatorObject,
          delegateProxy, findDelegate);
      delegateProxyPrototypes.add(delegateProxy.getPrototype());
    }
  }
}
 
Example #21
Source File: TypedScopeCreatorTest.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public void testGlobalThis1() {
  testSame(
      "/** @constructor */ function Window() {}" +
      "Window.prototype.alert = function() {};" +
      "var x = this;");

  ObjectType x = (ObjectType) (globalScope.getVar("x").getType());
  FunctionType windowCtor =
      (FunctionType) (globalScope.getVar("Window").getType());
  assertEquals("global this", x.toString());
  assertTrue(x.isSubtype(windowCtor.getInstanceType()));
  assertFalse(x.isEquivalentTo(windowCtor.getInstanceType()));
  assertTrue(x.hasProperty("alert"));
}
 
Example #22
Source File: Closure_17_TypedScopeCreator_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Apply special properties that only apply to delegates.
 */
private void applyDelegateRelationship(
    DelegateRelationship delegateRelationship) {
  ObjectType delegatorObject = ObjectType.cast(
      typeRegistry.getType(delegateRelationship.delegator));
  ObjectType delegateBaseObject = ObjectType.cast(
      typeRegistry.getType(delegateRelationship.delegateBase));
  ObjectType delegateSuperObject = ObjectType.cast(
      typeRegistry.getType(codingConvention.getDelegateSuperclassName()));
  if (delegatorObject != null &&
      delegateBaseObject != null &&
      delegateSuperObject != null) {
    FunctionType delegatorCtor = delegatorObject.getConstructor();
    FunctionType delegateBaseCtor = delegateBaseObject.getConstructor();
    FunctionType delegateSuperCtor = delegateSuperObject.getConstructor();

    if (delegatorCtor != null && delegateBaseCtor != null &&
        delegateSuperCtor != null) {
      FunctionParamBuilder functionParamBuilder =
          new FunctionParamBuilder(typeRegistry);
      functionParamBuilder.addRequiredParams(
          getNativeType(U2U_CONSTRUCTOR_TYPE));
      FunctionType findDelegate = typeRegistry.createFunctionType(
          typeRegistry.createDefaultObjectUnion(delegateBaseObject),
          functionParamBuilder.build());

      FunctionType delegateProxy = typeRegistry.createConstructorType(
          delegateBaseObject.getReferenceName() + DELEGATE_PROXY_SUFFIX,
          null, null, null);
      delegateProxy.setPrototypeBasedOn(delegateBaseObject);

      codingConvention.applyDelegateRelationship(
          delegateSuperObject, delegateBaseObject, delegatorObject,
          delegateProxy, findDelegate);
      delegateProxyPrototypes.add(delegateProxy.getPrototype());
    }
  }
}
 
Example #23
Source File: 1_ClosureCodingConvention.java    From SimFix with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void applySingletonGetter(FunctionType functionType,
    FunctionType getterType, ObjectType objectType) {
  functionType.defineDeclaredProperty("getInstance", getterType,
      functionType.getSource());
  functionType.defineDeclaredProperty("instance_", objectType,
      functionType.getSource());
}
 
Example #24
Source File: Closure_71_CheckAccessControls_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Normalize the type of a constructor, its instance, and its prototype
 * all down to the same type (the instance type).
 */
private JSType normalizeClassType(JSType type) {
  if (type == null || type.isUnknownType()) {
    return type;
  } else if (type.isConstructor()) {
    return ((FunctionType) type).getInstanceType();
  } else if (type.isFunctionPrototypeType()) {
    FunctionType owner = ((FunctionPrototypeType) type).getOwnerFunction();
    if (owner.isConstructor()) {
      return owner.getInstanceType();
    }
  }
  return type;
}
 
Example #25
Source File: Closure_17_TypedScopeCreator_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Apply special properties that only apply to delegates.
 */
private void applyDelegateRelationship(
    DelegateRelationship delegateRelationship) {
  ObjectType delegatorObject = ObjectType.cast(
      typeRegistry.getType(delegateRelationship.delegator));
  ObjectType delegateBaseObject = ObjectType.cast(
      typeRegistry.getType(delegateRelationship.delegateBase));
  ObjectType delegateSuperObject = ObjectType.cast(
      typeRegistry.getType(codingConvention.getDelegateSuperclassName()));
  if (delegatorObject != null &&
      delegateBaseObject != null &&
      delegateSuperObject != null) {
    FunctionType delegatorCtor = delegatorObject.getConstructor();
    FunctionType delegateBaseCtor = delegateBaseObject.getConstructor();
    FunctionType delegateSuperCtor = delegateSuperObject.getConstructor();

    if (delegatorCtor != null && delegateBaseCtor != null &&
        delegateSuperCtor != null) {
      FunctionParamBuilder functionParamBuilder =
          new FunctionParamBuilder(typeRegistry);
      functionParamBuilder.addRequiredParams(
          getNativeType(U2U_CONSTRUCTOR_TYPE));
      FunctionType findDelegate = typeRegistry.createFunctionType(
          typeRegistry.createDefaultObjectUnion(delegateBaseObject),
          functionParamBuilder.build());

      FunctionType delegateProxy = typeRegistry.createConstructorType(
          delegateBaseObject.getReferenceName() + DELEGATE_PROXY_SUFFIX,
          null, null, null);
      delegateProxy.setPrototypeBasedOn(delegateBaseObject);

      codingConvention.applyDelegateRelationship(
          delegateSuperObject, delegateBaseObject, delegatorObject,
          delegateProxy, findDelegate);
      delegateProxyPrototypes.add(delegateProxy.getPrototype());
    }
  }
}
 
Example #26
Source File: CheckAccessControls.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Normalize the type of a constructor, its instance, and its prototype
 * all down to the same type (the instance type).
 */
private JSType normalizeClassType(JSType type) {
  if (type == null || type.isUnknownType()) {
    return type;
  } else if (type.isNominalConstructor()) {
    return (type.toMaybeFunctionType()).getInstanceType();
  } else if (type.isFunctionPrototypeType()) {
    FunctionType owner = ((ObjectType) type).getOwnerFunction();
    if (owner.isConstructor()) {
      return owner.getInstanceType();
    }
  }
  return type;
}
 
Example #27
Source File: DeclarationGenerator.java    From clutz with MIT License 5 votes vote down vote up
/**
 * If a constructor statement is not emitted TS will assume a constructor with no arguments and
 * no body (default ctor) for base classes, or the constructor of the superclass.
 *
 * <p>Omitting the constructor is correct only if the closure class and *all* its superclasses
 * have zero argument constructors. If the supertype is NoResolvedType we cannot know whether
 * that's the case so we must return true.
 */
private boolean mustEmitConstructor(FunctionType type) {
  while (type != null) {
    if (type.getParameters().iterator().hasNext()) return true;
    ObjectType oType = getSuperType(type);
    if (oType == null) return false;
    if (oType.isNoResolvedType()) return true;
    type = oType.getConstructor();
  }
  return false;
}
 
Example #28
Source File: Closure_112_TypeInference_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * For functions with function(this: T, ...) and T as parameters, type
 * inference will set the type of this on a function literal argument to the
 * the actual type of T.
 */
private boolean inferTemplatedTypesForCall(
    Node n, FunctionType fnType) {
  final ImmutableList<TemplateType> keys = fnType.getTemplateTypeMap()
      .getTemplateKeys();
  if (keys.isEmpty()) {
    return false;
  }

  // Try to infer the template types
  Map<TemplateType, JSType> inferred = 
      inferTemplateTypesFromParameters(fnType, n);


  // Replace all template types. If we couldn't find a replacement, we
  // replace it with UNKNOWN.
  TemplateTypeReplacer replacer = new TemplateTypeReplacer(
      registry, inferred);
  Node callTarget = n.getFirstChild();

  FunctionType replacementFnType = fnType.visit(replacer)
      .toMaybeFunctionType();
  Preconditions.checkNotNull(replacementFnType);

  callTarget.setJSType(replacementFnType);
  n.setJSType(replacementFnType.getReturnType());

  return replacer.madeChanges;
}
 
Example #29
Source File: DeclarationGenerator.java    From clutz with MIT License 5 votes vote down vote up
private void addRelatedInterfaces(ObjectType instance, Set<ObjectType> interfaces) {
  FunctionType constructor = instance.getConstructor();
  if (constructor != null && constructor.isInterface() && !interfaces.contains(instance)) {
    interfaces.add(instance);

    for (ObjectType interfaceType : instance.getCtorExtendedInterfaces()) {
      addRelatedInterfaces(interfaceType, interfaces);
    }
  }
}
 
Example #30
Source File: Closure_96_TypeCheck_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Gets the type of the node or {@code null} if the node's type is not a
 * function.
 */
private FunctionType getFunctionType(Node n) {
  JSType type = getJSType(n).restrictByNotNullOrUndefined();
  if (type.isUnknownType()) {
    return typeRegistry.getNativeFunctionType(U2U_CONSTRUCTOR_TYPE);
  } else if (type instanceof FunctionType) {
    return (FunctionType) type;
  } else {
    return null;
  }
}