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

The following examples show how to use com.google.javascript.rhino.jstype.JSType#isConstructor() . 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: DeclarationGenerator.java    From clutz with MIT License 6 votes vote down vote up
private boolean needsAlias(Set<String> shadowedSymbols, String provide, TypedVar symbol) {
  if (!shadowedSymbols.contains(provide)) {
    return false;
  }
  // Emit var foo : any for provided but not declared symbols.
  if (symbol == null) {
    return true;
  }
  JSType type = symbol.getType();
  if (type == null) {
    return false;
  }

  // Emit var foo : PrivateType for private symbols.
  if (isPrivate(type.getJSDocInfo()) && !isConstructor(type.getJSDocInfo())) {
    return true;
  }
  // Only var declarations have collisions, while class, interface, function, and typedef can
  // coexist with namespaces.
  if (type.isInterface() || type.isConstructor() || type.isFunctionType() || isTypedef(type)) {
    return false;
  }
  return isDefaultExport(symbol);
}
 
Example 2
Source File: Closure_2_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();
  JSType type = getJSType(constructor).restrictByNotNullOrUndefined();
  if (type.isConstructor() || type.isEmptyType() || type.isUnknownType()) {
    FunctionType fnType = type.toMaybeFunctionType();
    if (fnType != null) {
      visitParameterList(t, n, fnType);
      ensureTyped(t, n, fnType.getInstanceType());
    } else {
      ensureTyped(t, n);
    }
  } else {
    report(t, n, NOT_A_CONSTRUCTOR);
    ensureTyped(t, n);
  }
}
 
Example 3
Source File: TypeCollectionPass.java    From js-dossier with Apache License 2.0 6 votes vote down vote up
private boolean isExternAlias(JSType type, JSDocInfo info) {
  if (externTypes.contains(type)) {
    return true;
  }

  // If something is typed as {function(new: Foo)}, it will actually be represented as
  // {function(new: Foo): ?}, which is different than the real constructor. We can get the real
  // constructor, however, with a little type manipulation.
  if (type.isConstructor() && type.toMaybeFunctionType() != null) {
    JSType ctorType = type.toMaybeFunctionType().getInstanceType().getConstructor();
    if (externTypes.contains(ctorType)) {
      return true;
    }
  }

  if (info != null && info.getTypedefType() != null) {
    JSTypeExpression expression = info.getTypedefType();
    type = Types.evaluate(expression, compiler.getTopScope(), compiler.getTypeRegistry());
    return externTypes.contains(type);
  }

  return false;
}
 
Example 4
Source File: TypeInspector.java    From js-dossier with Apache License 2.0 6 votes vote down vote up
private void resolveNames(Node node) {
  if (node.isName() || node.isString()) {
    String name = node.getString();
    if (registry.isType(name)) {
      NominalType nominalType = registry.getType(name);
      JSType jsType = nominalType.getType();
      if (jsType.isConstructor() || jsType.isInterface()) {
        String referenceName = jsType.toMaybeObjectType().getReferenceName();
        if (!name.equals(referenceName)
            && !isNullOrEmpty(referenceName)
            && !jsRegistry.getGlobalType(referenceName).isNamedType()) {
          node.setString(referenceName);
        }
      }
    }
  }

  for (Node child = node.getFirstChild(); child != null; child = child.getNext()) {
    resolveNames(child);
  }
}
 
Example 5
Source File: Closure_11_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();
  JSType type = getJSType(constructor).restrictByNotNullOrUndefined();
  if (type.isConstructor() || type.isEmptyType() || type.isUnknownType()) {
    FunctionType fnType = type.toMaybeFunctionType();
    if (fnType != null) {
      visitParameterList(t, n, fnType);
      ensureTyped(t, n, fnType.getInstanceType());
    } else {
      ensureTyped(t, n);
    }
  } else {
    report(t, n, NOT_A_CONSTRUCTOR);
    ensureTyped(t, n);
  }
}
 
Example 6
Source File: Nopol2017_0029_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();
  JSType type = getJSType(constructor).restrictByNotNullOrUndefined();
  if (type.isConstructor() || type.isEmptyType() || type.isUnknownType()) {
    FunctionType fnType = type.toMaybeFunctionType();
    if (fnType != null) {
      visitParameterList(t, n, fnType);
      ensureTyped(t, n, fnType.getInstanceType());
    } else {
      ensureTyped(t, n);
    }
  } else {
    report(t, n, NOT_A_CONSTRUCTOR);
    ensureTyped(t, n);
  }
}
 
Example 7
Source File: AbstractClosureVisitor.java    From jsinterop-generator with Apache License 2.0 6 votes vote down vote up
private void accept(StaticTypedSlot var, boolean isStatic) {
  JSType type = var.getType();

  if ((type.isInterface() || type.isConstructor())
      && !type.isInstanceType()
      && toFunctionType(type).getSource() != null
      && !isTypeAlias(var)) {
    acceptClassOrInterface(toFunctionType(type));
  } else if (isModule(type)) {
    acceptModule(var);
  } else if (isTypedef(var)) {
    acceptTypedef(var);
  } else if (type.isEnumType()) {
    acceptEnumType(toEnumType(type));
  } else if (isTypeAlias(var)) {
    // We don't process type alias.
    //   /** @constructor */ function Foo() {};
    //   /** @const */ var Bar = Foo;
  } else {
    acceptMember(var, isStatic);
  }
}
 
Example 8
Source File: TypeRegistry.java    From js-dossier with Apache License 2.0 5 votes vote down vote up
private JSType getSuperInstance(
    ObjectType instance,
    FunctionType ctor,
    StaticTypedScope globalScope,
    JSTypeRegistry jsRegistry) {
  JSType superInstance;
  if (ctor.getJSDocInfo() != null && ctor.getJSDocInfo().getBaseType() != null) {
    List<TemplateType> templateTypes = instance.getTemplateTypeMap().getTemplateKeys();
    StaticTypedScope scope =
        templateTypes.isEmpty()
            ? globalScope
            : jsRegistry.createScopeWithTemplates(globalScope, templateTypes);

    JSTypeExpression baseTypeExpression = ctor.getJSDocInfo().getBaseType();
    superInstance = Types.evaluate(baseTypeExpression, scope, jsRegistry);

    // The type expression will resolve to a named type if it is an aliased reference to
    // a module's exported type. Compensate by checking dossier's type registry, which
    // tracks exported types by their exported name (whereas the compiler tracks them by
    // their initially declared name from within the module).
    if (superInstance.isNamedType()
        && isType(superInstance.toMaybeNamedType().getReferenceName())) {
      superInstance = getType(superInstance.toMaybeNamedType().getReferenceName()).getType();
      if (superInstance.isConstructor() || superInstance.isInterface()) {
        superInstance = superInstance.toMaybeFunctionType().getTypeOfThis();
      }
    }

  } else {
    FunctionType superCtor = ctor.getSuperClassConstructor();
    if (superCtor == null) {
      return null;
    }
    superInstance = superCtor.getTypeOfThis();
  }
  return superInstance;
}
 
Example 9
Source File: DeclarationGenerator.java    From clutz with MIT License 5 votes vote down vote up
private boolean isAliasedClassOrInterface(TypedVar symbol, JSType type) {
  // Confusingly typedefs are constructors. However, they cannot be aliased AFAICT.
  if (type.isNoType()) return false;
  if (!type.isConstructor() && !type.isInterface()) return false;
  String symbolName = symbol.getName();
  String typeName = type.getDisplayName();
  // Turns out that for aliases the symbol and type name differ.
  return !symbolName.equals(typeName) || KNOWN_CLASS_ALIASES.containsKey(symbolName);
}
 
Example 10
Source File: CheckAccessControls.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Checks if a constructor is trying to override a final class.
 * @param t The current traversal.
 * @param name The name node.
 */
private void checkFinalClassOverrides(NodeTraversal t, Node fn, Node parent) {
  JSType type = fn.getJSType().toMaybeFunctionType();
  if (type != null && type.isConstructor()) {
    JSType finalParentClass = getFinalParentClass(getClassOfMethod(fn, parent));
    if (finalParentClass != null) {
      compiler.report(
          t.makeError(fn, EXTEND_FINAL_CLASS,
              type.getDisplayName(), finalParentClass.getDisplayName()));
    }
  }
}
 
Example 11
Source File: DeclarationGenerator.java    From clutz with MIT License 5 votes vote down vote up
private boolean isOrdinaryFunction(JSType ftype) {
  // Closure represents top-level functions as classes because they might be new-able.
  // This happens through externs es3.js which has Function marked as constructor.
  // See https://github.com/angular/closure-to-dts/issues/90
  boolean ordinaryFunctionAppearingAsClass =
      ftype.isConstructor() && "Function".equals(ftype.getDisplayName());
  return ftype.isOrdinaryFunction() || ordinaryFunctionAppearingAsClass;
}
 
Example 12
Source File: NameReferenceGraphConstruction.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @param assign The assignment node, null if it is just a "forward"
 *     declaration for recording the rValue's type.
 */
private Name recordPrototypePropDefinition(
    NodeTraversal t, Node qName, JSType type,
    @Nullable Node assign, @Nullable Node parent, @Nullable Node gParent) {
  JSType constructor = getType(NodeUtil.getPrototypeClassName(qName));
  FunctionType classType = null;
  String className = null;

  if (constructor != null && constructor.isConstructor()) {
    // Case where the class has been properly declared with @constructor
    classType = constructor.toMaybeFunctionType();
    className = classType.getReferenceName();
  } else {
    // We'll guess it is a constructor even if it didn't have @constructor
    classType = compiler.getTypeRegistry().getNativeFunctionType(
        JSTypeNative.U2U_CONSTRUCTOR_TYPE);
    className = NodeUtil.getPrototypeClassName(qName).getQualifiedName();
  }
  // In case we haven't seen the function yet.
  recordClassConstructorOrInterface(
      className, classType, null, null, null, null);

  String qNameStr = className + ".prototype." +
      NodeUtil.getPrototypePropertyName(qName);
  Name prototypeProp = graph.defineNameIfNotExists(qNameStr, isExtern);
  Preconditions.checkNotNull(prototypeProp,
      "%s should be in the name graph as a node.", qNameStr);
  if (assign != null) {
    prototypeProp.addAssignmentDeclaration(assign);
  }
  prototypeProp.setType(type);
  return prototypeProp;
}
 
Example 13
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 14
Source File: Closure_6_TypeValidator_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Expect that the first type can be assigned to a symbol of the second
 * type.
 *
 * @param t The node traversal.
 * @param n The node to issue warnings on.
 * @param rightType The type on the RHS of the assign.
 * @param leftType The type of the symbol on the LHS of the assign.
 * @param msg An extra message for the mismatch warning, if necessary.
 * @return True if the types matched, false otherwise.
 */
boolean expectCanAssignTo(NodeTraversal t, Node n, JSType rightType,
    JSType leftType, String msg) {
  if (!rightType.canAssignTo(leftType)) {
    if ((leftType.isConstructor() || leftType.isEnumType()) && (rightType.isConstructor() || rightType.isEnumType())) {
      registerMismatch(rightType, leftType, null);
    } else {
    mismatch(t, n, msg, rightType, leftType);
    }
    return false;
  }
  return true;
}
 
Example 15
Source File: Closure_71_CheckAccessControls_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Gets the type of the class that "owns" a method, or null if
 * we know that its un-owned.
 */
private JSType getClassOfMethod(Node n, Node parent) {
  if (parent.getType() == Token.ASSIGN) {
    Node lValue = parent.getFirstChild();
    if (lValue.isQualifiedName()) {
      if (lValue.getType() == Token.GETPROP) {
        // We have an assignment of the form "a.b = ...".
        JSType lValueType = lValue.getJSType();
        if (lValueType != null && lValueType.isConstructor()) {
          // If a.b is a constructor, then everything in this function
          // belongs to the "a.b" type.
          return ((FunctionType) lValueType).getInstanceType();
        } else {
          // If a.b is not a constructor, then treat this as a method
          // of whatever type is on "a".
          return normalizeClassType(lValue.getFirstChild().getJSType());
        }
      } else {
        // We have an assignment of the form "a = ...", so pull the
        // type off the "a".
        return normalizeClassType(lValue.getJSType());
      }
    }
  } else if (NodeUtil.isFunctionDeclaration(n) ||
             parent.getType() == Token.NAME) {
    return normalizeClassType(n.getJSType());
  }

  return null;
}
 
Example 16
Source File: Closure_71_CheckAccessControls_s.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 17
Source File: TypeRegistry.java    From js-dossier with Apache License 2.0 5 votes vote down vote up
/**
 * Recomputes the type hierarchy relationships for all nominal types in this registry using the
 * given global scope and JS registry.
 */
public void computeTypeRelationships(StaticTypedScope globalScope, JSTypeRegistry jsRegistry) {
  checkArgument(globalScope.getParentScope() == null, "not a global scope");

  knownImplementations.clear();
  subInterfaces.clear();
  directSubtypes.clear();
  implementedInterfaces.clear();

  Set<FunctionType> processed = new HashSet<>();
  for (NominalType nominalType : typesByName.values()) {
    JSType jsType = nominalType.getType();
    if (!jsType.isConstructor() && !jsType.isInterface()) {
      continue;
    }

    FunctionType ctor = jsType.toMaybeFunctionType();
    if (ctor == null || !processed.add(ctor)) {
      continue;
    }

    if (ctor.isInterface()) {
      scanExtendedInterfaces(new HashSet<>(), ctor);

    } else {
      scanImplementedInterfaces(ctor);
      computeTypeHiearchy(ctor, globalScope, jsRegistry);
    }
  }
}
 
Example 18
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 19
Source File: TypeInspector.java    From js-dossier with Apache License 2.0 5 votes vote down vote up
@Nullable
private DefinedByType getDefinedByComment(
    final LinkFactory linkFactory,
    final NominalType context,
    JSType currentType,
    InstanceProperty property) {
  JSType propertyDefinedOn = property.getDefinedByType();

  if (propertyDefinedOn.isConstructor() || propertyDefinedOn.isInterface()) {
    propertyDefinedOn = propertyDefinedOn.toMaybeFunctionType().getInstanceType();
  }
  if (currentType.equals(propertyDefinedOn)) {
    return null;
  }

  JSType definedByType = stripTemplateTypeInformation(propertyDefinedOn);

  List<NominalType> types = registry.getTypes(definedByType);
  if (types.isEmpty() && definedByType.isInstanceType()) {
    types = registry.getTypes(definedByType.toObjectType().getConstructor());
  }

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

  if (!types.isEmpty()) {
    definedByType = types.get(0).getType();
    if (definedByType.isConstructor() || definedByType.isInterface()) {
      definedByType =
          stripTemplateTypeInformation(definedByType.toMaybeFunctionType().getInstanceType());
    }
  }

  NamedType type = buildPropertyLink(parser, definedByType, property.getName());
  return DefinedByType.create(
      type, ObjectType.cast(definedByType).getConstructor().isInterface());
}
 
Example 20
Source File: TypeInspector.java    From js-dossier with Apache License 2.0 2 votes vote down vote up
/**
 * Returns whether the given {@code type} looks like the base function type constructor (that is,
 * {@code @type {!Function}}).
 */
private static boolean isFunctionTypeConstructor(JSType type) {
  return type.isConstructor() && ((FunctionType) type).getInstanceType().isUnknownType();
}