com.google.javascript.rhino.jstype.JSType Java Examples
The following examples show how to use
com.google.javascript.rhino.jstype.JSType.
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: AmbiguateProperties.java From astor with GNU General Public License v2.0 | 6 votes |
/** Returns true if properties on this type should not be renamed. */ private boolean isInvalidatingType(JSType type) { if (type.isUnionType()) { type = type.restrictByNotNullOrUndefined(); if (type.isUnionType()) { for (JSType alt : type.toMaybeUnionType().getAlternates()) { if (isInvalidatingType(alt)) { return true; } } return false; } } ObjectType objType = ObjectType.cast(type); return objType == null || invalidatingTypes.contains(objType) || !objType.hasReferenceName() || objType.isUnknownType() || objType.isEmptyType() /* unresolved types */ || objType.isEnumType() || objType.autoboxesTo() != null; }
Example #2
Source File: TypedScopeCreatorTest.java From astor with GNU General Public License v2.0 | 6 votes |
public void testTemplateType4a() { testSame( "/**\n" + " * @param {function():T} x\n" + " * @return {T}\n" + " * @template T\n" + " */\n" + "function f(x) {\n" + " return x;\n" + "}" + "/** @return {string} */\n" + "var g = function(){return 'hi'};\n" + "(function () {var result = f(g);})();"); JSType resultType = findNameType("result", lastLocalScope); assertEquals("string", resultType.toString()); }
Example #3
Source File: Closure_112_TypeInference_t.java From coming with MIT License | 6 votes |
/** * 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 #4
Source File: Closure_90_FunctionTypeBuilder_t.java From coming with MIT License | 6 votes |
@Override public boolean apply(JSType type) { ObjectType objectType = ObjectType.cast(type); if (objectType == null) { reportError(BAD_IMPLEMENTED_TYPE, fnName); } else if (objectType.isUnknownType() && // If this has a supertype that hasn't been resolved yet, // then we can assume this type will be ok once the super // type resolves. (objectType.getImplicitPrototype() == null || objectType.getImplicitPrototype().isResolved())) { reportWarning(RESOLVED_TAG_EMPTY, "@implements", fnName); } else { return true; } return false; }
Example #5
Source File: Closure_41_FunctionTypeBuilder_t.java From coming with MIT License | 6 votes |
@Override public boolean apply(JSType type) { ObjectType objectType = ObjectType.cast(type); if (objectType == null) { reportError(BAD_IMPLEMENTED_TYPE, fnName); return false; } else if (objectType.isEmptyType()) { reportWarning(RESOLVED_TAG_EMPTY, "@implements", fnName); return false; } else if (objectType.isUnknownType()) { if (hasMoreTagsToResolve(objectType)) { return true; } else { reportWarning(RESOLVED_TAG_EMPTY, "@implements", fnName); return false; } } else { return true; } }
Example #6
Source File: TypeInference.java From astor with GNU General Public License v2.0 | 6 votes |
private Map<TemplateType, JSType> inferTemplateTypesFromParameters( FunctionType fnType, Node call) { if (fnType.getTemplateKeys().isEmpty()) { return Collections.emptyMap(); } Map<TemplateType, JSType> resolvedTypes = Maps.newIdentityHashMap(); Node callTarget = call.getFirstChild(); if (NodeUtil.isGet(callTarget)) { Node obj = callTarget.getFirstChild(); maybeResolveTemplatedType( fnType.getTypeOfThis(), getJSType(obj), resolvedTypes); } if (call.hasMoreThanOneChild()) { maybeResolveTemplateTypeFromNodes( fnType.getParameters(), call.getChildAtIndex(1).siblings(), resolvedTypes); } return resolvedTypes; }
Example #7
Source File: Closure_117_TypeValidator_s.java From coming with MIT License | 6 votes |
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: DeclarationGenerator.java From clutz with MIT License | 6 votes |
private void emitIndexSignature(JSType keyType, JSType returnType, boolean emitBreak) { emit("["); // TS allows only number or string as index type of an object // https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#3.9.4 if (keyType.isNumberValueType()) { emit("key: number"); } else { if (!keyType.isStringValueType()) { emit("/* warning: coerced from " + keyType + " */"); } emit("key: string"); } emit("]:"); visitType(returnType); if (emitBreak) { emit(";"); emitBreak(); } }
Example #9
Source File: TypeCheck.java From astor with GNU General Public License v2.0 | 6 votes |
/** * Visits a GETPROP 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. * @param parent The parent of <code>n</code> */ private void visitGetProp(NodeTraversal t, Node n, Node parent) { // obj.prop or obj.method() // Lots of types can appear on the left, a call to a void function can // never be on the left. getPropertyType will decide what is acceptable // and what isn't. Node property = n.getLastChild(); Node objNode = n.getFirstChild(); JSType childType = getJSType(objNode); if (childType.isDict()) { report(t, property, TypeValidator.ILLEGAL_PROPERTY_ACCESS, "'.'", "dict"); } else if (validator.expectNotNullOrUndefined(t, n, childType, "No properties on this expression", getNativeType(OBJECT_TYPE))) { checkPropertyAccess(childType, property.getString(), t, n); } ensureTyped(t, n); }
Example #10
Source File: TypedScopeCreatorTest.java From astor with GNU General Public License v2.0 | 6 votes |
private JSType findTypeOnMatchedNode(Predicate<Node> matcher, Scope scope) { Node root = scope.getRootNode(); Deque<Node> queue = Lists.newLinkedList(); queue.push(root); while (!queue.isEmpty()) { Node current = queue.pop(); if (matcher.apply(current) && current.getJSType() != null) { return current.getJSType(); } for (Node child : current.children()) { queue.push(child); } } return null; }
Example #11
Source File: Closure_95_TypedScopeCreator_t.java From coming with MIT License | 6 votes |
private void maybeCollectMember(NodeTraversal t, Node member, Node nodeWithJsDocInfo) { JSDocInfo info = nodeWithJsDocInfo.getJSDocInfo(); // Do nothing if there is no JSDoc type info, or // if the node is not a member expression, or // if the member expression is not of the form: this.someProperty. if (info == null || member.getType() != Token.GETPROP || member.getFirstChild().getType() != Token.THIS) { return; } member.getFirstChild().setJSType(thisType); JSType jsType = getDeclaredTypeInAnnotation(t, member, info); Node name = member.getLastChild(); if (jsType != null && (name.getType() == Token.NAME || name.getType() == Token.STRING)) { thisType.defineDeclaredProperty( name.getString(), jsType, false /* functions with implementations are not in externs */); } }
Example #12
Source File: TypeValidator.java From astor with GNU General Public License v2.0 | 6 votes |
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 #13
Source File: Closure_112_TypeInference_s.java From coming with MIT License | 6 votes |
private FlowScope traverseCall(Node n, FlowScope scope) { scope = traverseChildren(n, scope); Node left = n.getFirstChild(); JSType functionType = getJSType(left).restrictByNotNullOrUndefined(); if (functionType.isFunctionType()) { FunctionType fnType = functionType.toMaybeFunctionType(); n.setJSType(fnType.getReturnType()); backwardsInferenceFromCallSite(n, fnType); } else if (functionType.isEquivalentTo( getNativeType(CHECKED_UNKNOWN_TYPE))) { n.setJSType(getNativeType(CHECKED_UNKNOWN_TYPE)); } scope = tightenTypesAfterAssertions(scope, n); return scope; }
Example #14
Source File: Closure_11_TypeCheck_s.java From coming with MIT License | 6 votes |
/** * 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 #15
Source File: Scope.java From astor with GNU General Public License v2.0 | 5 votes |
/** * Gets the type of {@code this} in the current scope. */ @Override public JSType getTypeOfThis() { if (isGlobal()) { return ObjectType.cast(rootNode.getJSType()); } Preconditions.checkState(rootNode.isFunction()); JSType nodeType = rootNode.getJSType(); if (nodeType != null && nodeType.isFunctionType()) { return nodeType.toMaybeFunctionType().getTypeOfThis(); } else { return parent.getTypeOfThis(); } }
Example #16
Source File: Closure_7_ChainableReverseAbstractInterpreter_t.java From coming with MIT License | 5 votes |
@Override public JSType caseEnumElementType(EnumElementType enumElementType) { JSType type = enumElementType.getPrimitiveType().visit(this); if (type != null && enumElementType.getPrimitiveType().isEquivalentTo(type)) { return enumElementType; } else { return type; } }
Example #17
Source File: TypeRegistry.java From js-dossier with Apache License 2.0 | 5 votes |
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 #18
Source File: Closure_19_ChainableReverseAbstractInterpreter_s.java From coming with MIT License | 5 votes |
@Override protected JSType caseTopType(JSType topType) { JSType result = topType; if (resultEqualsValue) { JSType typeByName = getNativeTypeForTypeOf(value); if (typeByName != null) { result = typeByName; } } return result; }
Example #19
Source File: Closure_96_TypeCheck_s.java From coming with MIT License | 5 votes |
/** * 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 #20
Source File: TypeInferenceTest.java From astor with GNU General Public License v2.0 | 5 votes |
public void testAssertObject5() { JSType startType = createNullableType(ALL_TYPE); assuming("x", startType); inFunction( "out1 = x;" + "out2 = /** @type {!Array} */ (goog.asserts.assertObject(x));"); verify("out1", startType); verify("out2", ARRAY_TYPE); }
Example #21
Source File: Closure_6_TypeValidator_t.java From coming with MIT License | 5 votes |
/** * Expect that the type of a switch condition matches the type of its * case condition. */ void expectSwitchMatchesCase(NodeTraversal t, Node n, JSType switchType, JSType caseType) { // ECMA-262, page 68, step 3 of evaluation of CaseBlock, // but allowing extra autoboxing. // TODO(user): remove extra conditions when type annotations // in the code base have adapted to the change in the compiler. if (!switchType.canTestForShallowEqualityWith(caseType) && (caseType.autoboxesTo() == null || !caseType.autoboxesTo().isSubtype(switchType))) { mismatch(t, n.getFirstChild(), "case expression doesn't match switch", caseType, switchType); } }
Example #22
Source File: TypeCheck.java From astor with GNU General Public License v2.0 | 5 votes |
/** * 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 #23
Source File: Cardumen_0095_s.java From coming with MIT License | 5 votes |
public static <T extends JSType, S extends JSType> void assertTypeCollectionEquals(Iterable<T> a, Iterable<S> b) { Assert.assertEquals(Iterables.size(a), Iterables.size(b)); Iterator<T> aIterator = a.iterator(); Iterator<S> bIterator = b.iterator(); while (aIterator.hasNext()) { assertTypeEquals(aIterator.next(), bIterator.next()); } }
Example #24
Source File: Closure_11_TypeCheck_t.java From coming with MIT License | 5 votes |
/** * Visits a NAME 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. * @param parent The parent of the node n. * @return whether the node is typeable or not */ boolean visitName(NodeTraversal t, Node n, Node parent) { // At this stage, we need to determine whether this is a leaf // node in an expression (which therefore needs to have a type // assigned for it) versus some other decorative node that we // can safely ignore. Function names, arguments (children of LP nodes) and // variable declarations are ignored. // TODO(user): remove this short-circuiting in favor of a // pre order traversal of the FUNCTION, CATCH, LP and VAR nodes. int parentNodeType = parent.getType(); if (parentNodeType == Token.FUNCTION || parentNodeType == Token.CATCH || parentNodeType == Token.PARAM_LIST || parentNodeType == Token.VAR) { return false; } JSType type = n.getJSType(); if (type == null) { type = getNativeType(UNKNOWN_TYPE); Var var = t.getScope().getVar(n.getString()); if (var != null) { JSType varType = var.getType(); if (varType != null) { type = varType; } } } ensureTyped(t, n, type); return true; }
Example #25
Source File: Closure_96_TypeCheck_t.java From coming with MIT License | 5 votes |
/** * <p>Checks the initializer of an enum. An enum can be initialized with an * object literal whose values must be subtypes of the declared enum element * type, or by copying another enum.</p> * * <p>In the case of an enum copy, we verify that the enum element type of the * enum used for initialization is a subtype of the enum element type of * the enum the value is being copied in.</p> * * <p>Examples:</p> * <pre>var myEnum = {FOO: ..., BAR: ...}; * var myEnum = myOtherEnum;</pre> * * @param value the value used for initialization of the enum * @param primitiveType The type of each element of the enum. */ private void checkEnumInitializer( NodeTraversal t, Node value, JSType primitiveType) { if (value.getType() == Token.OBJECTLIT) { // re-using value as the value of the object literal and advancing twice value = value.getFirstChild(); value = (value == null) ? null : value.getNext(); while (value != null) { // the value's type must be assignable to the enum's primitive type validator.expectCanAssignTo(t, value, getJSType(value), primitiveType, "element type must match enum's type"); // advancing twice value = value.getNext(); value = (value == null) ? null : value.getNext(); } } else if (value.getJSType() instanceof EnumType) { // TODO(user): Remove the instanceof check in favor // of a type.isEnumType() predicate. Currently, not all enum types are // implemented by the EnumClass, e.g. the unknown type and the any // type. The types need to be defined by interfaces such that an // implementation can implement multiple types interface. EnumType valueEnumType = (EnumType) value.getJSType(); JSType valueEnumPrimitiveType = valueEnumType.getElementsType().getPrimitiveType(); validator.expectCanAssignTo(t, value, valueEnumPrimitiveType, primitiveType, "incompatible enum element types"); } else { // The error condition is handled in TypedScopeCreator. } }
Example #26
Source File: Closure_96_TypeCheck_s.java From coming with MIT License | 5 votes |
/** * 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 #27
Source File: Closure_117_TypeValidator_t.java From coming with MIT License | 5 votes |
/** * This method gets the JSType from the Node argument and verifies that it is * present. */ private JSType getJSType(Node n) { JSType jsType = n.getJSType(); if (jsType == null) { // TODO(user): This branch indicates a compiler bug, not worthy of // halting the compilation but we should log this and analyze to track // down why it happens. This is not critical and will be resolved over // time as the type checker is extended. return getNativeType(UNKNOWN_TYPE); } else { return jsType; } }
Example #28
Source File: Closure_66_TypeCheck_s.java From coming with MIT License | 5 votes |
/** * Visits a NAME 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. * @param parent The parent of the node n. * @return whether the node is typeable or not */ boolean visitName(NodeTraversal t, Node n, Node parent) { // At this stage, we need to determine whether this is a leaf // node in an expression (which therefore needs to have a type // assigned for it) versus some other decorative node that we // can safely ignore. Function names, arguments (children of LP nodes) and // variable declarations are ignored. // TODO(user): remove this short-circuiting in favor of a // pre order traversal of the FUNCTION, CATCH, LP and VAR nodes. int parentNodeType = parent.getType(); if (parentNodeType == Token.FUNCTION || parentNodeType == Token.CATCH || parentNodeType == Token.LP || parentNodeType == Token.VAR) { return false; } JSType type = n.getJSType(); if (type == null) { type = getNativeType(UNKNOWN_TYPE); Var var = t.getScope().getVar(n.getString()); if (var != null) { JSType varType = var.getType(); if (varType != null) { type = varType; } } } ensureTyped(t, n, type); return true; }
Example #29
Source File: Closure_112_TypeInference_t.java From coming with MIT License | 5 votes |
private void redeclareSimpleVar( FlowScope scope, Node nameNode, JSType varType) { Preconditions.checkState(nameNode.isName()); String varName = nameNode.getString(); if (varType == null) { varType = getNativeType(JSTypeNative.UNKNOWN_TYPE); } if (isUnflowable(syntacticScope.getVar(varName))) { return; } scope.inferSlotType(varName, varType); }
Example #30
Source File: Asserts.java From ng-closure-runner with MIT License | 5 votes |
public static void assertTypeNotEquals(String message, JSType a, JSType b) { Assert.assertFalse( message + (message.isEmpty() ? "" : "\n") + "Type: " + b + "\n", a.isEquivalentTo(b)); Assert.assertFalse( message + " Equals is not symmetric.\n" + "Type: " + b + "\n", b.isEquivalentTo(a)); }