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

The following examples show how to use com.google.javascript.rhino.jstype.JSType#isUnknownType() . 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_2_TypeCheck_t.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 2
Source File: TypeCheck.java    From astor with GNU General Public License v2.0 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: Nopol2017_0051_t.java    From coming with MIT License 6 votes vote down vote up
/**
 * Counts the given node in the typed statistics.
 * @param n a node that should be typed
 */
private void doPercentTypedAccounting(NodeTraversal t, Node n) {
  JSType type = n.getJSType();
  if (type == null) {
    if (com.google.javascript.jscomp.TypeCheck.this.inExterns) {
      nullCount++;
    }
  } else if (type.isUnknownType()) {
    if (reportUnknownTypes.isOn()) {
      compiler.report(
          t.makeError(n, reportUnknownTypes, UNKNOWN_EXPR_TYPE));
    }
    unknownCount++;
  } else {
    typedCount++;
  }
}
 
Example 4
Source File: Nopol2017_0029_t.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 5
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 6
Source File: NameReferenceGraphReport.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Dump a type in a nice, readable way.
 *
 * @param builder contents of the report to be generated.
 * @param defType type to describe
 */
private void generateType(StringBuilder builder, JSType defType) {
  if (defType == null) {
    builder.append(" (type: null) ");
  } else if (defType.isUnknownType()) {
    builder.append(" (type: unknown) ");
  } else {
    builder.append(" (type: " +
        defType.toString() + ") ");
  }
}
 
Example 7
Source File: Closure_69_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;
  }
}
 
Example 8
Source File: Closure_25_TypeInference_t.java    From coming with MIT License 5 votes vote down vote up
private FlowScope traverseAdd(Node n, FlowScope scope) {
  Node left = n.getFirstChild();
  Node right = left.getNext();
  scope = traverseChildren(n, scope);

  JSType leftType = left.getJSType();
  JSType rightType = right.getJSType();

  JSType type = getNativeType(UNKNOWN_TYPE);
  if (leftType != null && rightType != null) {
    boolean leftIsUnknown = leftType.isUnknownType();
    boolean rightIsUnknown = rightType.isUnknownType();
    if (leftIsUnknown && rightIsUnknown) {
      type = getNativeType(UNKNOWN_TYPE);
    } else if ((!leftIsUnknown && leftType.isString()) ||
               (!rightIsUnknown && rightType.isString())) {
      type = getNativeType(STRING_TYPE);
    } else if (leftIsUnknown || rightIsUnknown) {
      type = getNativeType(UNKNOWN_TYPE);
    } else if (isAddedAsNumber(leftType) && isAddedAsNumber(rightType)) {
      type = getNativeType(NUMBER_TYPE);
    } else {
      type = registry.createUnionType(STRING_TYPE, NUMBER_TYPE);
    }
  }
  n.setJSType(type);

  if (n.isAssignAdd()) {
    updateScopeForTypeChange(scope, left, leftType, type);
  }

  return scope;
}
 
Example 9
Source File: Closure_35_TypeInference_t.java    From coming with MIT License 5 votes vote down vote up
private FlowScope traverseAdd(Node n, FlowScope scope) {
  Node left = n.getFirstChild();
  Node right = left.getNext();
  scope = traverseChildren(n, scope);

  JSType leftType = left.getJSType();
  JSType rightType = right.getJSType();

  JSType type = getNativeType(UNKNOWN_TYPE);
  if (leftType != null && rightType != null) {
    boolean leftIsUnknown = leftType.isUnknownType();
    boolean rightIsUnknown = rightType.isUnknownType();
    if (leftIsUnknown && rightIsUnknown) {
      type = getNativeType(UNKNOWN_TYPE);
    } else if ((!leftIsUnknown && leftType.isString()) ||
               (!rightIsUnknown && rightType.isString())) {
      type = getNativeType(STRING_TYPE);
    } else if (leftIsUnknown || rightIsUnknown) {
      type = getNativeType(UNKNOWN_TYPE);
    } else if (isAddedAsNumber(leftType) && isAddedAsNumber(rightType)) {
      type = getNativeType(NUMBER_TYPE);
    } else {
      type = registry.createUnionType(STRING_TYPE, NUMBER_TYPE);
    }
  }
  n.setJSType(type);

  if (n.isAssignAdd()) {
    updateScopeForTypeChange(scope, left, leftType, type);
  }

  return scope;
}
 
Example 10
Source File: Closure_112_TypeInference_t.java    From coming with MIT License 5 votes vote down vote up
private FlowScope traverseAdd(Node n, FlowScope scope) {
  Node left = n.getFirstChild();
  Node right = left.getNext();
  scope = traverseChildren(n, scope);

  JSType leftType = left.getJSType();
  JSType rightType = right.getJSType();

  JSType type = unknownType;
  if (leftType != null && rightType != null) {
    boolean leftIsUnknown = leftType.isUnknownType();
    boolean rightIsUnknown = rightType.isUnknownType();
    if (leftIsUnknown && rightIsUnknown) {
      type = unknownType;
    } else if ((!leftIsUnknown && leftType.isString()) ||
               (!rightIsUnknown && rightType.isString())) {
      type = getNativeType(STRING_TYPE);
    } else if (leftIsUnknown || rightIsUnknown) {
      type = unknownType;
    } else if (isAddedAsNumber(leftType) && isAddedAsNumber(rightType)) {
      type = getNativeType(NUMBER_TYPE);
    } else {
      type = registry.createUnionType(STRING_TYPE, NUMBER_TYPE);
    }
  }
  n.setJSType(type);

  if (n.isAssignAdd()) {
    updateScopeForTypeChange(scope, left, leftType, type);
  }

  return scope;
}
 
Example 11
Source File: Closure_66_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;
  }
}
 
Example 12
Source File: Closure_118_DisambiguateProperties_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Processes a GETPROP node.
 */
private void handleGetProp(NodeTraversal t, Node n) {
  String name = n.getLastChild().getString();
  T type = typeSystem.getType(getScope(), n.getFirstChild(), name);

  Property prop = getProperty(name);
  if (!prop.scheduleRenaming(n.getLastChild(),
                             processProperty(t, prop, type, null))) {
    if (propertiesToErrorFor.containsKey(name)) {
      String suggestion = "";
      if (type instanceof JSType) {
        JSType jsType = (JSType) type;
        if (jsType.isAllType() || jsType.isUnknownType()) {
          if (n.getFirstChild().isThis()) {
            suggestion = "The \"this\" object is unknown in the function," +
                "consider using @this";
          } else {
            String qName = n.getFirstChild().getQualifiedName();
            suggestion = "Consider casting " + qName +
                " if you know it's type.";
          }
        } else {
          List<String> errors = Lists.newArrayList();
          printErrorLocations(errors, jsType);
          if (!errors.isEmpty()) {
            suggestion = "Consider fixing errors for the following types:\n";
            suggestion += Joiner.on("\n").join(errors);
          }
        }
      }
      compiler.report(JSError.make(
          t.getSourceName(), n, propertiesToErrorFor.get(name),
          Warnings.INVALIDATION, name,
          (type == null ? "null" : type.toString()),
          n.toString(), suggestion));
    }
  }
}
 
Example 13
Source File: Closure_2_TypeCheck_t.java    From coming with MIT License 5 votes vote down vote up
/**
 * Counts the given node in the typed statistics.
 * @param n a node that should be typed
 */
private void doPercentTypedAccounting(NodeTraversal t, Node n) {
  JSType type = n.getJSType();
  if (type == null) {
    nullCount++;
  } else if (type.isUnknownType()) {
    if (reportUnknownTypes.isOn()) {
      compiler.report(
          t.makeError(n, reportUnknownTypes, UNKNOWN_EXPR_TYPE));
    }
    unknownCount++;
  } else {
    typedCount++;
  }
}
 
Example 14
Source File: LinkedFlowScope.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Look through the given scope, and try to find slots where it doesn't
 * have enough type information. Then fill in that type information
 * with stuff that we've inferred in the local flow.
 */
@Override
public void completeScope(StaticScope<JSType> staticScope) {
  Scope scope = (Scope) staticScope;
  for (Iterator<Var> it = scope.getVars(); it.hasNext();) {
    Var var = it.next();
    if (var.isTypeInferred()) {
      JSType type = var.getType();
      if (type == null || type.isUnknownType()) {
        JSType flowType = getSlot(var.getName()).getType();
        var.setType(flowType);
      }
    }
  }
}
 
Example 15
Source File: Nopol2017_0051_s.java    From coming with MIT License 5 votes vote down vote up
/**
 * Counts the given node in the typed statistics.
 * @param n a node that should be typed
 */
private void doPercentTypedAccounting(NodeTraversal t, Node n) {
  JSType type = n.getJSType();
  if (type == null) {
    nullCount++;
  } else if (type.isUnknownType()) {
    if (reportUnknownTypes.isOn()) {
      compiler.report(
          t.makeError(n, reportUnknownTypes, UNKNOWN_EXPR_TYPE));
    }
    unknownCount++;
  } else {
    typedCount++;
  }
}
 
Example 16
Source File: DisambiguateProperties.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@Override public boolean isInvalidatingType(JSType type) {
  if (type == null || invalidatingTypes.contains(type) ||
      type.isUnknownType() /* unresolved types */) {
    return true;
  }

  ObjectType objType = ObjectType.cast(type);
  return objType != null && !objType.hasReferenceName();
}
 
Example 17
Source File: Closure_96_TypeCheck_s.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;
  }
}
 
Example 18
Source File: Closure_17_TypedScopeCreator_s.java    From coming with MIT License 4 votes vote down vote up
/**
 * Determines whether a qualified name is inferred.
 * NOTE(nicksantos): Determining whether a property is declared or not
 * is really really obnoxious.
 *
 * The problem is that there are two (equally valid) coding styles:
 *
 * (function() {
 *   /* The authoritative definition of goog.bar. /
 *   goog.bar = function() {};
 * })();
 *
 * function f() {
 *   goog.bar();
 *   /* Reset goog.bar to a no-op. /
 *   goog.bar = function() {};
 * }
 *
 * In a dynamic language with first-class functions, it's very difficult
 * to know which one the user intended without looking at lots of
 * contextual information (the second example demonstrates a small case
 * of this, but there are some really pathological cases as well).
 *
 * The current algorithm checks if either the declaration has
 * JsDoc type information, or @const with a known type,
 * or a function literal with a name we haven't seen before.
 */
private boolean isQualifiedNameInferred(
    String qName, Node n, JSDocInfo info,
    Node rhsValue, JSType valueType) {
  if (valueType == null) {
    return true;
  }

  boolean inferred = true;
  if (info != null) {
    inferred = !(info.hasType()
        || info.hasEnumParameterType()
        || (info.isConstant() && valueType != null
            && !valueType.isUnknownType())
        || FunctionTypeBuilder.isFunctionTypeDeclaration(info));
  }

  if (inferred && rhsValue != null && rhsValue.isFunction()) {
    if (info != null) {
      return false;
    } else if (!scope.isDeclared(qName, false) &&
        n.isUnscopedQualifiedName()) {

      // Check if this is in a conditional block.
      // Functions assigned in conditional blocks are inferred.
      for (Node current = n.getParent();
           !(current.isScript() || current.isFunction());
           current = current.getParent()) {
        if (NodeUtil.isControlStructure(current)) {
          return true;
        }
      }

      // Check if this is assigned in an inner scope.
      // Functions assigned in inner scopes are inferred.
      AstFunctionContents contents =
          getFunctionAnalysisResults(scope.getRootNode());
      if (contents == null ||
          !contents.getEscapedQualifiedNames().contains(qName)) {
        return false;
      }
    }
  }
  return inferred;
}
 
Example 19
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 20
Source File: Closure_112_TypeInference_s.java    From coming with MIT License 4 votes vote down vote up
private JSType getPropertyType(JSType objType, String propName,
    Node n, FlowScope scope) {
  // We often have a couple of different types to choose from for the
  // property. Ordered by accuracy, we have
  // 1) A locally inferred qualified name (which is in the FlowScope)
  // 2) A globally declared qualified name (which is in the FlowScope)
  // 3) A property on the owner type (which is on objType)
  // 4) A name in the type registry (as a last resort)
  JSType propertyType = null;
  boolean isLocallyInferred = false;

  // Scopes sometimes contain inferred type info about qualified names.
  String qualifiedName = n.getQualifiedName();
  StaticSlot<JSType> var = scope.getSlot(qualifiedName);
  if (var != null) {
    JSType varType = var.getType();
    if (varType != null) {
      boolean isDeclared = !var.isTypeInferred();
      isLocallyInferred = (var != syntacticScope.getSlot(qualifiedName));
      if (isDeclared || isLocallyInferred) {
        propertyType = varType;
      }
    }
  }

  if (propertyType == null && objType != null) {
    JSType foundType = objType.findPropertyType(propName);
    if (foundType != null) {
      propertyType = foundType;
    }
  }

  if (propertyType != null && objType != null) {
    JSType restrictedObjType = objType.restrictByNotNullOrUndefined();
    if (!restrictedObjType.getTemplateTypeMap().isEmpty()
        && propertyType.hasAnyTemplateTypes()) {
      TemplateTypeMap typeMap = restrictedObjType.getTemplateTypeMap();
      TemplateTypeMapReplacer replacer = new TemplateTypeMapReplacer(
          registry, typeMap);
      propertyType = propertyType.visit(replacer);
    }
  }

  if ((propertyType == null || propertyType.isUnknownType())
      && qualifiedName != null) {
    // If we find this node in the registry, then we can infer its type.
    ObjectType regType = ObjectType.cast(registry.getType(qualifiedName));
    if (regType != null) {
      propertyType = regType.getConstructor();
    }
  }

  if (propertyType == null) {
    return unknownType;
  } else if (propertyType.isEquivalentTo(unknownType) && isLocallyInferred) {
    // If the type has been checked in this scope,
    // then use CHECKED_UNKNOWN_TYPE instead to indicate that.
    return getNativeType(CHECKED_UNKNOWN_TYPE);
  } else {
    return propertyType;
  }
}