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

The following examples show how to use com.google.javascript.rhino.jstype.JSType#isFunctionType() . 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_43_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 2
Source File: Closure_17_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 != 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 3
Source File: Closure_117_TypeValidator_s.java    From coming with MIT License 6 votes vote down vote up
private void registerMismatch(JSType found, JSType required, JSError error) {
  // Don't register a mismatch for differences in null or undefined or if the
  // code didn't downcast.
  found = found.restrictByNotNullOrUndefined();
  required = required.restrictByNotNullOrUndefined();
  if (found.isSubtype(required) || required.isSubtype(found)) {
    return;
  }

  mismatches.add(new TypeMismatch(found, required, error));
  if (found.isFunctionType() &&
      required.isFunctionType()) {
    FunctionType fnTypeA = found.toMaybeFunctionType();
    FunctionType fnTypeB = required.toMaybeFunctionType();
    Iterator<Node> paramItA = fnTypeA.getParameters().iterator();
    Iterator<Node> paramItB = fnTypeB.getParameters().iterator();
    while (paramItA.hasNext() && paramItB.hasNext()) {
      registerIfMismatch(paramItA.next().getJSType(),
          paramItB.next().getJSType(), error);
    }

    registerIfMismatch(
        fnTypeA.getReturnType(), fnTypeB.getReturnType(), error);
  }
}
 
Example 4
Source File: Closure_35_TypeInference_s.java    From coming with MIT License 6 votes vote down vote up
private FlowScope traverseCall(Node n, FlowScope scope) {
  scope = traverseChildren(n, scope);

  Node left = n.getFirstChild();
  JSType functionType = getJSType(left).restrictByNotNullOrUndefined();
  if (functionType != null) {
    if (functionType.isFunctionType()) {
      FunctionType fnType = functionType.toMaybeFunctionType();
      n.setJSType(fnType.getReturnType());
      backwardsInferenceFromCallSite(n, fnType);
    } else if (functionType.equals(getNativeType(CHECKED_UNKNOWN_TYPE))) {
      n.setJSType(getNativeType(CHECKED_UNKNOWN_TYPE));
    }
  }

  scope = tightenTypesAfterAssertions(scope, n);
  return scope;
}
 
Example 5
Source File: Nopol2017_0027_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 != 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 6
Source File: TypeInspector.java    From js-dossier with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the known sub-types of the inspected type. For classes, this will only return the
 * direct sub-types.
 */
public ImmutableSet<NamedType> getSubtypes() {
  JSType type = inspectedType.getType();
  if (!type.isFunctionType()) {
    return ImmutableSet.of();
  }

  TypeExpressionParser parser =
      expressionParserFactory.create(linkFactory.withTypeContext(inspectedType));

  return Stream.concat(
          parseTypes(registry.getSubInterfaces(type.toMaybeFunctionType()), parser),
          parseTypes(registry.getDirectSubTypes(type.toMaybeFunctionType()), parser))
      .sorted(compareNamedTypes())
      .collect(toImmutableSet());
}
 
Example 7
Source File: Closure_117_TypeValidator_t.java    From coming with MIT License 6 votes vote down vote up
private void registerMismatch(JSType found, JSType required, JSError error) {
  // Don't register a mismatch for differences in null or undefined or if the
  // code didn't downcast.
  found = found.restrictByNotNullOrUndefined();
  required = required.restrictByNotNullOrUndefined();
  if (found.isSubtype(required) || required.isSubtype(found)) {
    return;
  }

  mismatches.add(new TypeMismatch(found, required, error));
  if (found.isFunctionType() &&
      required.isFunctionType()) {
    FunctionType fnTypeA = found.toMaybeFunctionType();
    FunctionType fnTypeB = required.toMaybeFunctionType();
    Iterator<Node> paramItA = fnTypeA.getParameters().iterator();
    Iterator<Node> paramItB = fnTypeB.getParameters().iterator();
    while (paramItA.hasNext() && paramItB.hasNext()) {
      registerIfMismatch(paramItA.next().getJSType(),
          paramItB.next().getJSType(), error);
    }

    registerIfMismatch(
        fnTypeA.getReturnType(), fnTypeB.getReturnType(), error);
  }
}
 
Example 8
Source File: Closure_125_TypeCheck_t.java    From coming with MIT License 5 votes vote down vote up
private void checkPropertyInheritanceOnGetpropAssign(
    NodeTraversal t, Node assign, Node object, String property,
    JSDocInfo info, JSType propertyType) {
  // Inheritance checks for prototype properties.
  //
  // TODO(nicksantos): This isn't the right place to do this check. We
  // really want to do this when we're looking at the constructor.
  // We'd find all its properties and make sure they followed inheritance
  // rules, like we currently do for @implements to make sure
  // all the methods are implemented.
  //
  // As-is, this misses many other ways to override a property.
  //
  // object.prototype.property = ...;
  if (object.isGetProp()) {
    Node object2 = object.getFirstChild();
    String property2 = NodeUtil.getStringValue(object.getLastChild());

    if ("prototype".equals(property2)) {
      JSType jsType = getJSType(object2);
      if (jsType.isFunctionType()) {
        FunctionType functionType = jsType.toMaybeFunctionType();
        if (functionType.isConstructor() || functionType.isInterface()) {
          checkDeclaredPropertyInheritance(
              t, assign, functionType, property, info, propertyType);
        }
      }
    }
  }
}
 
Example 9
Source File: TightenTypes.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** Returns a concrete type from the given JSType. */
private ConcreteType createType(JSType jsType) {
  if (jsType.isUnknownType() || jsType.isEmptyType()) {
    return ConcreteType.ALL;
  }

  if (jsType.isUnionType()) {
    ConcreteType type = ConcreteType.NONE;
    for (JSType alt : jsType.toMaybeUnionType().getAlternates()) {
      type = type.unionWith(createType(alt));
    }
    return type;
  }

  if (jsType.isFunctionType()) {
    if (getConcreteFunction(jsType.toMaybeFunctionType()) != null) {
      return getConcreteFunction(jsType.toMaybeFunctionType());
    }
    // Since we don't have a declaration, it's not concrete.
    return ConcreteType.ALL;
  }

  if (jsType.isObject()) {
    return createConcreteInstance(jsType.toObjectType());
  }

  return ConcreteType.NONE;  // Not a reference type.
}
 
Example 10
Source File: Nopol2017_0029_t.java    From coming with MIT License 5 votes vote down vote up
private void checkPropertyInheritanceOnGetpropAssign(
    NodeTraversal t, Node assign, Node object, String property,
    JSDocInfo info, JSType propertyType) {
  // Inheritance checks for prototype properties.
  //
  // TODO(nicksantos): This isn't the right place to do this check. We
  // really want to do this when we're looking at the constructor.
  // We'd find all its properties and make sure they followed inheritance
  // rules, like we currently do for @implements to make sure
  // all the methods are implemented.
  //
  // As-is, this misses many other ways to override a property.
  //
  // object.prototype.property = ...;
  if (object.isGetProp()) {
    Node object2 = object.getFirstChild();
    String property2 = NodeUtil.getStringValue(object.getLastChild());

    if ("prototype".equals(property2)) {
      JSType jsType = getJSType(object2);
      if (jsType.isFunctionType()) {
        FunctionType functionType = jsType.toMaybeFunctionType();
        if (functionType.isConstructor() || functionType.isInterface()) {
          checkDeclaredPropertyInheritance(
              t, assign, functionType, property, info, propertyType);
        }
      }
    }
  }
}
 
Example 11
Source File: Nopol2017_0029_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Visits an ASSIGN node for cases such as
 * <pre>
 * interface.property2.property = ...;
 * </pre>
 */
private void visitInterfaceGetprop(NodeTraversal t, Node assign, Node object,
    String property, Node lvalue, Node rvalue) {

  JSType rvalueType = getJSType(rvalue);

  // Only 2 values are allowed for methods:
  //    goog.abstractMethod
  //    function () {};
  // or for properties, no assignment such as:
  //    InterfaceFoo.prototype.foobar;

  String abstractMethodName =
      compiler.getCodingConvention().getAbstractMethodName();
  if (!rvalueType.isFunctionType()) {
    // This is bad i18n style but we don't localize our compiler errors.
    String abstractMethodMessage = (abstractMethodName != null)
       ? ", or " + abstractMethodName
       : "";
    compiler.report(
        t.makeError(object, INVALID_INTERFACE_MEMBER_DECLARATION,
            abstractMethodMessage));
  }

  if (assign.getLastChild().isFunction()
      && !NodeUtil.isEmptyBlock(assign.getLastChild().getLastChild())) {
    compiler.report(
        t.makeError(object, INTERFACE_FUNCTION_NOT_EMPTY,
            abstractMethodName));
  }
}
 
Example 12
Source File: Closure_25_TypeInference_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * For functions with function parameters, type inference will set the type of
 * a function literal argument from the function parameter type.
 */
private void updateTypeOfParameters(Node n, FunctionType fnType) {
  int i = 0;
  int childCount = n.getChildCount();
  for (Node iParameter : fnType.getParameters()) {
    if (i + 1 >= childCount) {
      // TypeCheck#visitParametersList will warn so we bail.
      return;
    }

    JSType iParameterType = getJSType(iParameter);
    Node iArgument = n.getChildAtIndex(i + 1);
    JSType iArgumentType = getJSType(iArgument);
    inferPropertyTypesToMatchConstraint(iArgumentType, iParameterType);

    if (iParameterType.isFunctionType()) {
      FunctionType iParameterFnType = iParameterType.toMaybeFunctionType();

      if (iArgument.isFunction() &&
          iArgumentType.isFunctionType() &&
          iArgument.getJSDocInfo() == null) {
        iArgument.setJSType(iParameterFnType);
      }
    }
    i++;
  }
}
 
Example 13
Source File: Closure_11_TypeCheck_t.java    From coming with MIT License 5 votes vote down vote up
private void checkPropertyInheritanceOnGetpropAssign(
    NodeTraversal t, Node assign, Node object, String property,
    JSDocInfo info, JSType propertyType) {
  // Inheritance checks for prototype properties.
  //
  // TODO(nicksantos): This isn't the right place to do this check. We
  // really want to do this when we're looking at the constructor.
  // We'd find all its properties and make sure they followed inheritance
  // rules, like we currently do for @implements to make sure
  // all the methods are implemented.
  //
  // As-is, this misses many other ways to override a property.
  //
  // object.prototype.property = ...;
  if (object.isGetProp()) {
    Node object2 = object.getFirstChild();
    String property2 = NodeUtil.getStringValue(object.getLastChild());

    if ("prototype".equals(property2)) {
      JSType jsType = getJSType(object2);
      if (jsType.isFunctionType()) {
        FunctionType functionType = jsType.toMaybeFunctionType();
        if (functionType.isConstructor() || functionType.isInterface()) {
          checkDeclaredPropertyInheritance(
              t, assign, functionType, property, info, propertyType);
        }
      }
    }
  }
}
 
Example 14
Source File: Closure_11_TypeCheck_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Visits a RETURN node.
 *
 * @param t The node traversal object that supplies context, such as the
 * scope chain to use in name lookups as well as error reporting.
 * @param n The node being visited.
 */
private void visitReturn(NodeTraversal t, Node n) {
  JSType jsType = getJSType(t.getEnclosingFunction());

  if (jsType.isFunctionType()) {
    FunctionType functionType = jsType.toMaybeFunctionType();

    JSType returnType = functionType.getReturnType();

    // if no return type is specified, undefined must be returned
    // (it's a void function)
    if (returnType == null) {
      returnType = getNativeType(VOID_TYPE);
    }

    // fetching the returned value's type
    Node valueNode = n.getFirstChild();
    JSType actualReturnType;
    if (valueNode == null) {
      actualReturnType = getNativeType(VOID_TYPE);
      valueNode = n;
    } else {
      actualReturnType = getJSType(valueNode);
    }

    // verifying
    validator.expectCanAssignTo(t, valueNode, actualReturnType, returnType,
        "inconsistent return type");
  }
}
 
Example 15
Source File: TypeInference.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * For functions with function parameters, type inference will set the type of
 * a function literal argument from the function parameter type.
 */
private void updateTypeOfParameters(Node n, FunctionType fnType) {
  int i = 0;
  int childCount = n.getChildCount();
  for (Node iParameter : fnType.getParameters()) {
    if (i + 1 >= childCount) {
      // TypeCheck#visitParametersList will warn so we bail.
      return;
    }

    JSType iParameterType = getJSType(iParameter);
    Node iArgument = n.getChildAtIndex(i + 1);
    JSType iArgumentType = getJSType(iArgument);
    inferPropertyTypesToMatchConstraint(iArgumentType, iParameterType);

    // TODO(johnlenz): Filter out non-function types
    // (such as null and undefined) as
    // we only care about FUNCTION subtypes here.
    JSType restrictedParameter = iParameterType
        .restrictByNotNullOrUndefined()
        .toMaybeFunctionType();
    if (restrictedParameter != null) {
      if (iArgument.isFunction() &&
          iArgumentType.isFunctionType() &&
          iArgument.getJSDocInfo() == null) {
        iArgument.setJSType(restrictedParameter);
      }
    }
    i++;
  }
}
 
Example 16
Source File: Closure_2_TypeCheck_t.java    From coming with MIT License 5 votes vote down vote up
private void checkPropertyInheritanceOnGetpropAssign(
    NodeTraversal t, Node assign, Node object, String property,
    JSDocInfo info, JSType propertyType) {
  // Inheritance checks for prototype properties.
  //
  // TODO(nicksantos): This isn't the right place to do this check. We
  // really want to do this when we're looking at the constructor.
  // We'd find all its properties and make sure they followed inheritance
  // rules, like we currently do for @implements to make sure
  // all the methods are implemented.
  //
  // As-is, this misses many other ways to override a property.
  //
  // object.prototype.property = ...;
  if (object.isGetProp()) {
    Node object2 = object.getFirstChild();
    String property2 = NodeUtil.getStringValue(object.getLastChild());

    if ("prototype".equals(property2)) {
      JSType jsType = getJSType(object2);
      if (jsType.isFunctionType()) {
        FunctionType functionType = jsType.toMaybeFunctionType();
        if (functionType.isConstructor() || functionType.isInterface()) {
          checkDeclaredPropertyInheritance(
              t, assign, functionType, property, info, propertyType);
        }
      }
    }
  }
}
 
Example 17
Source File: Closure_48_TypedScopeCreator_t.java    From coming with MIT License 4 votes vote down vote up
/**
 * Creates a scope with all types declared. Declares newly discovered types
 * and type properties in the type registry.
 */
@Override
public Scope createScope(Node root, Scope parent) {
  // Constructing the global scope is very different than constructing
  // inner scopes, because only global scopes can contain named classes that
  // show up in the type registry.
  Scope newScope = null;
  AbstractScopeBuilder scopeBuilder = null;
  if (parent == null) {
    // Run a first-order analysis over the syntax tree.
    (new FirstOrderFunctionAnalyzer(compiler, functionAnalysisResults))
        .process(root.getFirstChild(), root.getLastChild());

    // Find all the classes in the global scope.
    newScope = createInitialScope(root);

    GlobalScopeBuilder globalScopeBuilder = new GlobalScopeBuilder(newScope);
    scopeBuilder = globalScopeBuilder;
    NodeTraversal.traverse(compiler, root, scopeBuilder);
  } else {
    newScope = new Scope(parent, root);
    LocalScopeBuilder localScopeBuilder = new LocalScopeBuilder(newScope);
    scopeBuilder = localScopeBuilder;
    localScopeBuilder.build();
  }

  scopeBuilder.resolveStubDeclarations();
  scopeBuilder.resolveTypes();

  // Gather the properties in each function that we found in the
  // global scope, if that function has a @this type that we can
  // build properties on.
  for (Node functionNode : scopeBuilder.nonExternFunctions) {
    JSType type = functionNode.getJSType();
    if (type != null && type.isFunctionType()) {
      FunctionType fnType = type.toMaybeFunctionType();
      ObjectType fnThisType = fnType.getTypeOfThis();
      if (!fnThisType.isUnknownType()) {
        NodeTraversal.traverse(compiler, functionNode.getLastChild(),
            scopeBuilder.new CollectProperties(fnThisType));
      }
    }
  }

  if (parent == null) {
    codingConvention.defineDelegateProxyPrototypeProperties(
        typeRegistry, newScope, delegateProxyPrototypes,
        delegateCallingConventions);
  }
  return newScope;
}
 
Example 18
Source File: Closure_6_TypeValidator_t.java    From coming with MIT License 4 votes vote down vote up
/**
 * Given a node, get a human-readable name for the type of that node so
 * that will be easy for the programmer to find the original declaration.
 *
 * For example, if SubFoo's property "bar" might have the human-readable
 * name "Foo.prototype.bar".
 *
 * @param n The node.
 * @param dereference If true, the type of the node will be dereferenced
 *     to an Object type, if possible.
 */
String getReadableJSTypeName(Node n, boolean dereference) {
  // If we're analyzing a GETPROP, the property may be inherited by the
  // prototype chain. So climb the prototype chain and find out where
  // the property was originally defined.
  if (n.isGetProp()) {
    ObjectType objectType = getJSType(n.getFirstChild()).dereference();
    if (objectType != null) {
      String propName = n.getLastChild().getString();
      if (objectType.getConstructor() != null &&
          objectType.getConstructor().isInterface()) {
        objectType = FunctionType.getTopDefiningInterface(
            objectType, propName);
      } else {
        // classes
        while (objectType != null && !objectType.hasOwnProperty(propName)) {
          objectType = objectType.getImplicitPrototype();
        }
      }

      // Don't show complex function names or anonymous types.
      // Instead, try to get a human-readable type name.
      if (objectType != null &&
          (objectType.getConstructor() != null ||
           objectType.isFunctionPrototypeType())) {
        return objectType.toString() + "." + propName;
      }
    }
  }

  JSType type = getJSType(n);
  if (dereference) {
    ObjectType dereferenced = type.dereference();
    if (dereferenced != null) {
      type = dereferenced;
    }
  }

  String qualifiedName = n.getQualifiedName();
  if (type.isFunctionPrototypeType() ||
      (type.toObjectType() != null &&
       type.toObjectType().getConstructor() != null)) {
    return type.toString();
  } else if (qualifiedName != null) {
    return qualifiedName;
  } else if (type.isFunctionType()) {
    // Don't show complex function names.
    return "function";
  } else {
    return type.toString();
  }
}
 
Example 19
Source File: Nopol2017_0029_s.java    From coming with MIT License 4 votes vote down vote up
/**
 * Visits a CALL node.
 *
 * @param t The node traversal object that supplies context, such as the
 * scope chain to use in name lookups as well as error reporting.
 * @param n The node being visited.
 */
private void visitCall(NodeTraversal t, Node n) {
  Node child = n.getFirstChild();
  JSType childType = getJSType(child).restrictByNotNullOrUndefined();

  if (!childType.canBeCalled()) {
    report(t, n, NOT_CALLABLE, childType.toString());
    ensureTyped(t, n);
    return;
  }

  // A couple of types can be called as if they were functions.
  // If it is a function type, then validate parameters.
  if (childType.isFunctionType()) {
    FunctionType functionType = childType.toMaybeFunctionType();

    boolean isExtern = false;
    JSDocInfo functionJSDocInfo = functionType.getJSDocInfo();
    if( functionJSDocInfo != null  &&
        functionJSDocInfo.getAssociatedNode() != null) {
      isExtern = functionJSDocInfo.getAssociatedNode().isFromExterns();
    }

    // Non-native constructors should not be called directly
    // unless they specify a return type and are defined
    // in an extern.
    if (functionType.isConstructor() &&
        !functionType.isNativeObjectType() &&
        (functionType.getReturnType().isUnknownType() ||
         functionType.getReturnType().isVoidType() ||
         !isExtern)) {
      report(t, n, CONSTRUCTOR_NOT_CALLABLE, childType.toString());
    }

    // Functions with explicit 'this' types must be called in a GETPROP
    // or GETELEM.
    if (functionType.isOrdinaryFunction() &&
        !functionType.getTypeOfThis().isUnknownType() &&
        !(functionType.getTypeOfThis().toObjectType() != null &&
        functionType.getTypeOfThis().toObjectType().isNativeObjectType()) &&
        !(child.isGetElem() ||
          child.isGetProp())) {
      report(t, n, EXPECTED_THIS_TYPE, functionType.toString());
    }

    visitParameterList(t, n, functionType);
    ensureTyped(t, n, functionType.getReturnType());
  } else {
    ensureTyped(t, n);
  }

  // TODO: Add something to check for calls of RegExp objects, which is not
  // supported by IE.  Either say something about the return type or warn
  // about the non-portability of the call or both.
}
 
Example 20
Source File: AbstractClosureVisitor.java    From jsinterop-generator with Apache License 2.0 2 votes vote down vote up
/**
 * Returns true if the type is an anonymous function type defined in closure by <code>
 * {function(string):number}</code>. Returns false otherwise.
 */
protected boolean isAnonymousFunctionType(JSType type) {
  return type.isFunctionType() && type.getDisplayName() == null;
}