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

The following examples show how to use com.google.javascript.rhino.jstype.JSType#isInstanceType() . 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: 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 2
Source File: TypeInspector.java    From js-dossier with Apache License 2.0 6 votes vote down vote up
/** Finds the properties defined on a class. */
@Nullable
@CheckReturnValue
private InstanceProperty findFirstClassOverride(Iterable<InstanceProperty> properties) {
  for (InstanceProperty property : properties) {
    JSType definedOn = property.getDefinedByType();
    if (definedOn.isInterface()) {
      continue;
    } else if (definedOn.isInstanceType()) {
      FunctionType ctor = definedOn.toObjectType().getConstructor();
      if (ctor != null && ctor.isInterface()) {
        continue;
      }
    }
    return property;
  }
  return null;
}
 
Example 3
Source File: DeclarationGenerator.java    From clutz with MIT License 5 votes vote down vote up
/**
 * A type representing an object literal that is inferred through goog.provide(...) or @const {}
 * and assigning properties to it.
 *
 * <p>We start with object types and narrow away known non-namespace types.
 *
 * <p>The terminology "namespace" type is non-standard.
 */
private static boolean isNamespaceType(JSType type) {
  if (!type.isObject()) return false;
  return !type.isInterface()
      && !type.isInstanceType()
      && !type.isEnumType()
      && !type.isFunctionType()
      && !isTypedef(type);
}
 
Example 4
Source File: Closure_41_FunctionTypeBuilder_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Returns a constructor function either by returning it from the
 * registry if it exists or creating and registering a new type. If
 * there is already a type, then warn if the existing type is
 * different than the one we are creating, though still return the
 * existing function if possible.  The primary purpose of this is
 * that registering a constructor will fail for all built-in types
 * that are initialized in {@link JSTypeRegistry}.  We a) want to
 * make sure that the type information specified in the externs file
 * matches what is in the registry and b) annotate the externs with
 * the {@link JSType} from the registry so that there are not two
 * separate JSType objects for one type.
 */
private FunctionType getOrCreateConstructor() {
  FunctionType fnType = typeRegistry.createConstructorType(
      fnName, contents.getSourceNode(), parametersNode, returnType);
  JSType existingType = typeRegistry.getType(fnName);

  if (existingType != null) {
    boolean isInstanceObject = existingType.isInstanceType();
    if (isInstanceObject || fnName.equals("Function")) {
      FunctionType existingFn =
          isInstanceObject ?
          existingType.toObjectType().getConstructor() :
          typeRegistry.getNativeFunctionType(FUNCTION_FUNCTION_TYPE);

      if (existingFn.getSource() == null) {
        existingFn.setSource(contents.getSourceNode());
      }

      if (!existingFn.hasEqualCallType(fnType)) {
        reportWarning(TYPE_REDEFINITION, fnName,
            fnType.toString(), existingFn.toString());
      }

      return existingFn;
    } else {
      // We fall through and return the created type, even though it will fail
      // to register. We have no choice as we have to return a function. We
      // issue an error elsewhere though, so the user should fix it.
    }
  }

  maybeSetBaseType(fnType);

  if (getScopeDeclaredIn().isGlobal() && !fnName.isEmpty()) {
    typeRegistry.declareType(fnName, fnType.getInstanceType());
  }
  return fnType;
}
 
Example 5
Source File: Closure_41_FunctionTypeBuilder_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Returns a constructor function either by returning it from the
 * registry if it exists or creating and registering a new type. If
 * there is already a type, then warn if the existing type is
 * different than the one we are creating, though still return the
 * existing function if possible.  The primary purpose of this is
 * that registering a constructor will fail for all built-in types
 * that are initialized in {@link JSTypeRegistry}.  We a) want to
 * make sure that the type information specified in the externs file
 * matches what is in the registry and b) annotate the externs with
 * the {@link JSType} from the registry so that there are not two
 * separate JSType objects for one type.
 */
private FunctionType getOrCreateConstructor() {
  FunctionType fnType = typeRegistry.createConstructorType(
      fnName, contents.getSourceNode(), parametersNode, returnType);
  JSType existingType = typeRegistry.getType(fnName);

  if (existingType != null) {
    boolean isInstanceObject = existingType.isInstanceType();
    if (isInstanceObject || fnName.equals("Function")) {
      FunctionType existingFn =
          isInstanceObject ?
          existingType.toObjectType().getConstructor() :
          typeRegistry.getNativeFunctionType(FUNCTION_FUNCTION_TYPE);

      if (existingFn.getSource() == null) {
        existingFn.setSource(contents.getSourceNode());
      }

      if (!existingFn.hasEqualCallType(fnType)) {
        reportWarning(TYPE_REDEFINITION, fnName,
            fnType.toString(), existingFn.toString());
      }

      return existingFn;
    } else {
      // We fall through and return the created type, even though it will fail
      // to register. We have no choice as we have to return a function. We
      // issue an error elsewhere though, so the user should fix it.
    }
  }

  maybeSetBaseType(fnType);

  if (getScopeDeclaredIn().isGlobal() && !fnName.isEmpty()) {
    typeRegistry.declareType(fnName, fnType.getInstanceType());
  }
  return fnType;
}
 
Example 6
Source File: NameReferenceGraphConstruction.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @return true if n MUST be a prototype name reference.
 */
private boolean isPrototypeNameReference(Node n) {
  if (!n.isGetProp()) {
    return false;
  }
  JSType type = getType(n.getFirstChild());
  if (type.isUnknownType() || type.isUnionType()) {
    return false;
  }
  return (type.isInstanceType() || type.autoboxesTo() != null);
}
 
Example 7
Source File: RuntimeTypeCheck.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private String getName(JSType type) {
  if (type.isInstanceType()) {
    return ((ObjectType) type).getReferenceName();
  } else if (type.isNullType()
      || type.isBooleanValueType()
      || type.isNumberValueType()
      || type.isStringValueType()
      || type.isVoidType()) {
    return type.toString();
  } else {
    // Type unchecked at runtime, so we don't care about the sorting order.
    return "";
  }
}
 
Example 8
Source File: RuntimeTypeCheck.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a node which evaluates to a checker for the given type (which
 * must not be a union). We have checkers for value types, classes and
 * interfaces.
 *
 * @return the checker node or {@code null} if the type is not checked
 */
private Node createCheckerNode(JSType type) {
  if (type.isNullType()) {
    return jsCode("nullChecker");

  } else if (type.isBooleanValueType()
      || type.isNumberValueType()
      || type.isStringValueType()
      || type.isVoidType()) {
    return IR.call(
        jsCode("valueChecker"),
        IR.string(type.toString()));

  } else if (type.isInstanceType()) {
    ObjectType objType = (ObjectType) type;

    String refName = objType.getReferenceName();

    StaticSourceFile sourceFile =
        NodeUtil.getSourceFile(objType.getConstructor().getSource());
    if (sourceFile == null || sourceFile.isExtern()) {
      return IR.call(
              jsCode("externClassChecker"),
              IR.string(refName));
    }

    return IR.call(
            jsCode(objType.getConstructor().isInterface() ?
                    "interfaceChecker" : "classChecker"),
            IR.string(refName));

  } else {
    // We don't check this type (e.g. unknown & all types).
    return null;
  }
}
 
Example 9
Source File: TypeContext.java    From js-dossier with Apache License 2.0 5 votes vote down vote up
@Nullable
@CheckReturnValue
private NominalType resolve(@Nullable JSType type) {
  if (type == null) {
    return null;
  }
  Collection<NominalType> types = typeRegistry.findTypes(type);
  if (types.isEmpty() && type.isInstanceType()) {
    types = typeRegistry.findTypes(type.toObjectType().getConstructor());
  }
  if (!types.isEmpty()) {
    return types.iterator().next();
  }
  return null;
}
 
Example 10
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 11
Source File: TypeCollectionPass.java    From js-dossier with Apache License 2.0 5 votes vote down vote up
public void crawl(JSType type) {
  type.visit(this);
  if ((type.isNominalType() && !type.isInstanceType())
      || type.isNominalConstructor()
      || type.isEnumType()) {
    externs.add(type);
  }
}
 
Example 12
Source File: FunctionTypeBuilder.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Returns a constructor function either by returning it from the
 * registry if it exists or creating and registering a new type. If
 * there is already a type, then warn if the existing type is
 * different than the one we are creating, though still return the
 * existing function if possible.  The primary purpose of this is
 * that registering a constructor will fail for all built-in types
 * that are initialized in {@link JSTypeRegistry}.  We a) want to
 * make sure that the type information specified in the externs file
 * matches what is in the registry and b) annotate the externs with
 * the {@link JSType} from the registry so that there are not two
 * separate JSType objects for one type.
 */
private FunctionType getOrCreateConstructor() {
  FunctionType fnType = typeRegistry.createConstructorType(
      fnName, contents.getSourceNode(), parametersNode, returnType, null);
  JSType existingType = typeRegistry.getType(fnName);

  if (makesStructs) {
    fnType.setStruct();
  } else if (makesDicts) {
    fnType.setDict();
  }
  if (existingType != null) {
    boolean isInstanceObject = existingType.isInstanceType();
    if (isInstanceObject || fnName.equals("Function")) {
      FunctionType existingFn =
          isInstanceObject ?
          existingType.toObjectType().getConstructor() :
          typeRegistry.getNativeFunctionType(FUNCTION_FUNCTION_TYPE);

      if (existingFn.getSource() == null) {
        existingFn.setSource(contents.getSourceNode());
      }

      if (!existingFn.hasEqualCallType(fnType)) {
        reportWarning(TYPE_REDEFINITION, fnName,
            fnType.toString(), existingFn.toString());
      }

      return existingFn;
    } else {
      // We fall through and return the created type, even though it will fail
      // to register. We have no choice as we have to return a function. We
      // issue an error elsewhere though, so the user should fix it.
    }
  }

  maybeSetBaseType(fnType);

  if (getScopeDeclaredIn().isGlobal() && !fnName.isEmpty()) {
    typeRegistry.declareType(fnName, fnType.getInstanceType());
  }
  return fnType;
}
 
Example 13
Source File: TypeInspector.java    From js-dossier with Apache License 2.0 4 votes vote down vote up
@Nullable
private TypeExpression getReturnType(
    PropertyDocs docs, Iterable<InstanceProperty> overrides, FunctionType function) {
  PropertyDocs returnDocs =
      findPropertyDocs(
          docs,
          overrides,
          input -> input != null && input.getReturnClause().getType().isPresent());

  JSType returnType = function.getReturnType();

  // Try to compensate for loss of information (how does this happen?). If the type compiler
  // says it is a templatized type, but does not have template types, or if it is an instance
  // type with a non-empty template type map, resort to JSDoc to figure out what the user wanted.
  boolean isUnknownType = returnType.isUnknownType() && !returnType.isTemplateType();
  boolean isEmptyTemplatizedType =
      returnType.isTemplatizedType() && returnType.getTemplateTypeMap().isEmpty();
  boolean isUnresolvedTemplateInstance =
      returnType.isInstanceType() && !returnType.getTemplateTypeMap().isEmpty();

  if (isUnknownType || isEmptyTemplatizedType || isUnresolvedTemplateInstance) {
    if (returnDocs != null && isKnownType(returnDocs.getJsDoc().getReturnClause())) {
      @SuppressWarnings("OptionalGetWithoutIsPresent") // Implied by isKnownType check above.
      JSTypeExpression expression = returnDocs.getJsDoc().getReturnClause().getType().get();
      returnType = evaluate(expression);
    } else {
      for (InstanceProperty property : overrides) {
        if (property.getType() != null && property.getType().isFunctionType()) {
          FunctionType fn = (FunctionType) property.getType();
          if (fn.getReturnType() != null && !fn.getReturnType().isUnknownType()) {
            returnType = fn.getReturnType();
            break;
          }
        }
      }
    }
  }

  if (returnType.isVoidType() || (returnType.isUnknownType() && !returnType.isTemplateType())) {
    return null;
  }

  NominalType context;
  if (returnDocs != null) {
    context = returnDocs.getContextType();
  } else {
    context = docs.getContextType();
  }

  TypeExpressionParser parser =
      expressionParserFactory.create(linkFactory.withTypeContext(context));
  return parser.parse(returnType);
}
 
Example 14
Source File: TypeCollectionPass.java    From js-dossier with Apache License 2.0 4 votes vote down vote up
private void processSymbol(Symbol symbol) {
  final JSType globalThis =
      compiler.getTypeRegistry().getNativeObjectType(JSTypeNative.GLOBAL_THIS);

  if (typeRegistry.isType(symbol.getName())) {
    return;
  }

  JSType type = null;
  boolean isFromCompilerRegistry = false;

  if (symbol.getReferencedSymbol() != null
      && typeRegistry.isType(symbol.getReferencedSymbol())) {
    type = typeRegistry.getType(symbol.getReferencedSymbol()).getType();
  }

  if (type == null) {
    type = compiler.getTypeRegistry().getGlobalType(symbol.getName());
    isFromCompilerRegistry = type != null;
  }

  if (type == null) {
    type = globalThis;
    for (String part : Splitter.on('.').split(symbol.getName())) {
      type = type.findPropertyType(part);
      if (type == null) {
        return;
      }
    }
  }

  if (type != null) {
    if (type.isInstanceType()
        && (isFromCompilerRegistry
            || shouldConvertToConstructor(type)
            || shouldConvertToConstructor(symbol))) {
      type = type.toObjectType().getConstructor();
    } else if (type.isEnumElementType()) {
      type = type.toMaybeEnumElementType().getEnumType();
    }
  }

  if (type == null) {
    log.warning("skipping " + symbol.getName() + "; no type");
    return;
  } else if (globalThis.equals(type)) {
    log.warning("skipping " + symbol.getName() + "; references global this");
    return;
  } else if (type.isOrdinaryFunction() && !typeRegistry.isProvided(symbol.getName())) {
    log.info("skipping " + symbol.getName() + "; is ordinary function");
    return;
  }
  collectTypes(symbol.getName(), type, symbol.getNode(), symbol.getJSDocInfo());
}