Class JSType
java.lang.Object
com.google.javascript.rhino.jstype.JSType
- All Implemented Interfaces:
Serializable
- Direct Known Subclasses:
AllType,BooleanType,NullType,NumberType,ObjectType,StringType,UnionType,VoidType
Represents JavaScript value types.
Types are split into two separate families: value types and object types.
A special UnknownType exists to represent a wildcard type on which
no information can be gathered. In particular, it can assign to everyone,
is a subtype of everyone (and everyone is a subtype of it).
If you remove the UnknownType, the set of types in the type system
forms a lattice with the isSubtype(com.google.javascript.rhino.jstype.JSType) relation defining the partial
order of types. All types are united at the top of the lattice by the
AllType and at the bottom by the NoType.
- See Also:
-
Nested Class Summary
Nested Classes -
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final Stringstatic final intstatic final Stringstatic final Stringstatic final intprotected final TemplateTypeMapstatic final String -
Method Summary
Modifier and TypeMethodDescriptionautobox()Dereference a type for property access.Turn a scalar type to the corresponding object type.booleanThis predicate is used to test whether a given type can be used as the 'function' in a function call.booleanTests whether values ofthistype can be safely assigned to values ofthattype.final booleancanTestForEqualityWith(JSType that) Tests whetherthisandthatare meaningfully comparable.final booleanTests whetherthisandthatare meaningfully comparable using shallow comparison.final voidClears the resolved field.Gets the least supertype of this that's not a union.final ObjectTypeDereference a type for property access.final booleandiffersFrom(JSType that) Whether this type is meaningfully different fromthattype for the purposes of data flow analysis.booleanfindPropertyType(String propertyName) Coerces this type to an Object type, then gets the type of the property whose name is given.final JSTypeforceResolve(ErrorReporter t, StaticScope<JSType> scope) Force this type to resolve, even if the registry is in a lazy resolving mode.Returns a user meaningful label for the JSType instance.getGreatestSubtype(JSType that) Gets the greatest subtype ofthisandthat.Gets the docInfo for this type.getLeastSupertype(JSType that) Gets the least supertype ofthisandthat.abstract BooleanLiteralSetComputes the set of possible outcomes of theToBooleanpredicate for this type.getRestrictedTypeGivenToBooleanOutcome(boolean outcome) Computes the restricted type of this type knowing that theToBooleanpredicate has a specific value.Returns the template type map associated with this type.getTypesUnderEquality(JSType that) Computes the subset ofthisandthattypes if equality is observed.Computes the subset ofthisandthattypes if inequality is observed.Computes the subset ofthisandthattypes under shallow equality.Computes the subset ofthisandthattypes under shallow inequality.booleanbooleaninthashCode()booleanhasProperty(String pname) Checks whether the property is present on the object.booleanbooleanbooleanbooleanbooleanbooleanWhether this type is aFunctionTypethat is a constructor or a named type that points to such a type.booleanbooleanisDict()Returns true iffthiscan be adict.final booleanfinal booleanbooleanstatic booleanisEquivalent(JSType typeA, JSType typeB) final booleanisEquivalentTo(JSType that) Checks if two types are equivalent.booleanWhether this is the prototype of a function.final booleanReturns true if toMaybeFunctionType returns a non-null FunctionType.final booleanReturns true if this is a global this type.booleanWhether this type is an Instance object of some constructor.booleanWhether this type is aFunctionTypethat is an interface or a named type that points to such a type.final booleanisInvariant(JSType that) Checks if two types are invariant.final booleanWhether this type is the original constructor of a nominal type.booleanWhether this type is a nominal type (a named instance object or a named enum).booleanbooleanbooleanisNoType()booleanTests whether this type is nullable.booleanfinal booleanisNumber()Tests whether the type is a number (value or Object).booleanbooleanbooleanisObject()Tests whether this type is anObject, or any subtype thereof.booleanWhether this type is aFunctionTypethat is an ordinary function or a named type that points to such a type.booleanbooleanfinal booleanWhether the type has been resolved.final booleanisString()Tests whether the type is a string (value or Object).booleanbooleanbooleanisStruct()Returns true iffthiscan be astruct.booleanChecks whetherthisis a subtype ofthat.final booleanfinal booleanfinal booleanbooleanbooleanvoidmatchConstraint(JSType constraint) Modify this type so that it matches the specified type.final booleanThis predicate is used to test whether a given type can appear in a 'Int32' context.booleanThis predicate is used to test whether a given type can appear in a numeric context, such as an operand of a multiply operator.booleanThis predicate is used to test whether a given type can appear in anObjectcontext, such as the expression in a with statement.booleanThis predicate is used to test whether a given type can appear in aStringcontext, such as an operand of a string concat (+) operator.final booleanThis predicate is used to test whether a given type can appear in a 'Uint32' context.final JSTyperesolve(ErrorReporter t, StaticScope<JSType> scope) Resolve this type in the given scope.If this is a union type, returns a union type that does not include the null or undefined type.booleansetValidator(com.google.common.base.Predicate<JSType> validator) Certain types have constraints on them at resolution-time.testForEquality(JSType that) Comparesthisandthat.final StringA string representation of this type, suitable for printing in type annotations at code generation time.A hash code function for diagnosing complicated issues around type-identity.Downcasts this to an EnumElementType, or returns null if this is not an EnumElementType.Downcasts this to an EnumType, or returns null if this is not an EnumType.Downcasts this to a FunctionType, or returns null if this is not a function.static FunctionTypetoMaybeFunctionType(JSType type) Null-safe version of toMaybeFunctionType().Downcasts this to a TemplateType, or returns null if this is not a function.static TemplateTypetoMaybeTemplateType(JSType type) Null-safe version of toMaybeTemplateType().Downcasts this to a TemplatizedType, or returns null if this is not a function.static TemplatizedTypetoMaybeTemplatizedType(JSType type) Null-safe version of toMaybeTemplatizedType().Downcasts this to a UnionType, or returns null if this is not a UnionType.Casts this to an ObjectType, or returns null if this is not an ObjectType.toString()A string representation of this type, suitable for printing in warnings.Turn an object type to its corresponding scalar type.abstract <T> TVisit this type with the given visitor.
-
Field Details
-
templateTypeMap
-
UNKNOWN_NAME
- See Also:
-
NOT_A_CLASS
- See Also:
-
NOT_A_TYPE
- See Also:
-
EMPTY_TYPE_COMPONENT
- See Also:
-
ENUMDECL
public static final int ENUMDECL- See Also:
-
NOT_ENUMDECL
public static final int NOT_ENUMDECL- See Also:
-
-
Method Details
-
getJSDocInfo
Gets the docInfo for this type. By default, documentation cannot be attached to arbitrary types. This must be overridden for programmer-defined types. -
getDisplayName
Returns a user meaningful label for the JSType instance. For example, Functions and Enums will return their declaration name (if they have one). Some types will not have a meaningful display name. Calls to hasDisplayName() will return true IFF getDisplayName() will return null or a zero length string.- Returns:
- the display name of the type, or null if one is not available
-
hasDisplayName
public boolean hasDisplayName()- Returns:
- true if the JSType has a user meaningful label.
-
hasProperty
Checks whether the property is present on the object.- Parameters:
pname- The property name.
-
isNoType
public boolean isNoType() -
isNoResolvedType
public boolean isNoResolvedType() -
isNoObjectType
public boolean isNoObjectType() -
isEmptyType
public final boolean isEmptyType() -
isNumberObjectType
public boolean isNumberObjectType() -
isNumberValueType
public boolean isNumberValueType() -
isFunctionPrototypeType
public boolean isFunctionPrototypeType()Whether this is the prototype of a function. -
isStringObjectType
public boolean isStringObjectType() -
isStringValueType
public boolean isStringValueType() -
isString
public final boolean isString()Tests whether the type is a string (value or Object).- Returns:
this <: (String, string)
-
isNumber
public final boolean isNumber()Tests whether the type is a number (value or Object).- Returns:
this <: (Number, number)
-
isArrayType
public boolean isArrayType() -
isBooleanObjectType
public boolean isBooleanObjectType() -
isBooleanValueType
public boolean isBooleanValueType() -
isRegexpType
public boolean isRegexpType() -
isDateType
public boolean isDateType() -
isNullType
public boolean isNullType() -
isVoidType
public boolean isVoidType() -
isAllType
public boolean isAllType() -
isUnknownType
public boolean isUnknownType() -
isCheckedUnknownType
public boolean isCheckedUnknownType() -
isUnionType
public final boolean isUnionType() -
isStruct
public boolean isStruct()Returns true iffthiscan be astruct. UnionType overrides the method, assumethisis not a union here. -
isDict
public boolean isDict()Returns true iffthiscan be adict. UnionType overrides the method, assumethisis not a union here. -
toMaybeUnionType
Downcasts this to a UnionType, or returns null if this is not a UnionType. Named in honor of Haskell's Maybe type constructor. -
isGlobalThisType
public final boolean isGlobalThisType()Returns true if this is a global this type. -
isFunctionType
public final boolean isFunctionType()Returns true if toMaybeFunctionType returns a non-null FunctionType. -
toMaybeFunctionType
Downcasts this to a FunctionType, or returns null if this is not a function. For the purposes of this function, we define a MaybeFunctionType as any type in the sub-lattice { x | LEAST_FUNCTION_TYPE <= x <= GREATEST_FUNCTION_TYPE } This definition excludes bottom types like NoType and NoObjectType. This definition is somewhat arbitrary and axiomatic, but this is the definition that makes the most sense for the most callers. -
toMaybeFunctionType
Null-safe version of toMaybeFunctionType(). -
isEnumElementType
public final boolean isEnumElementType() -
toMaybeEnumElementType
Downcasts this to an EnumElementType, or returns null if this is not an EnumElementType. -
isEnumType
public boolean isEnumType() -
toMaybeEnumType
Downcasts this to an EnumType, or returns null if this is not an EnumType. -
isRecordType
public boolean isRecordType() -
isTemplatizedType
public final boolean isTemplatizedType() -
toMaybeTemplatizedType
Downcasts this to a TemplatizedType, or returns null if this is not a function. -
toMaybeTemplatizedType
Null-safe version of toMaybeTemplatizedType(). -
isTemplateType
public final boolean isTemplateType() -
toMaybeTemplateType
Downcasts this to a TemplateType, or returns null if this is not a function. -
toMaybeTemplateType
Null-safe version of toMaybeTemplateType(). -
hasAnyTemplateTypes
public boolean hasAnyTemplateTypes() -
getTemplateTypeMap
Returns the template type map associated with this type. -
isObject
public boolean isObject()Tests whether this type is anObject, or any subtype thereof.- Returns:
this <: Object
-
isConstructor
public boolean isConstructor()Whether this type is aFunctionTypethat is a constructor or a named type that points to such a type. -
isNominalType
public boolean isNominalType()Whether this type is a nominal type (a named instance object or a named enum). -
isNominalConstructor
public final boolean isNominalConstructor()Whether this type is the original constructor of a nominal type. Does not include structural constructors. -
isInstanceType
public boolean isInstanceType()Whether this type is an Instance object of some constructor. Does not necessarily mean this is anInstanceObjectType. -
isInterface
public boolean isInterface()Whether this type is aFunctionTypethat is an interface or a named type that points to such a type. -
isOrdinaryFunction
public boolean isOrdinaryFunction()Whether this type is aFunctionTypethat is an ordinary function or a named type that points to such a type. -
isEquivalentTo
Checks if two types are equivalent. -
isInvariant
Checks if two types are invariant.- See Also:
-
EquivalenceMethod
-
differsFrom
Whether this type is meaningfully different fromthattype for the purposes of data flow analysis. This is a trickier check than pure equality, because it has to properly handle unknown types. SeeEquivalenceMethodfor more info.- See Also:
-
isEquivalent
-
equals
-
hashCode
public int hashCode() -
matchesInt32Context
public final boolean matchesInt32Context()This predicate is used to test whether a given type can appear in a 'Int32' context. This context includes, for example, the operands of a bitwise or operator. Since we do not currently support integer types, this is a synonym forNumber. -
matchesUint32Context
public final boolean matchesUint32Context()This predicate is used to test whether a given type can appear in a 'Uint32' context. This context includes the right-hand operand of a shift operator. -
matchesNumberContext
public boolean matchesNumberContext()This predicate is used to test whether a given type can appear in a numeric context, such as an operand of a multiply operator. -
matchesStringContext
public boolean matchesStringContext()This predicate is used to test whether a given type can appear in aStringcontext, such as an operand of a string concat (+) operator. All types have at least the potential for converting toString. When we add externally defined types, such as a browser OM, we may choose to add types that do not automatically convert toString. -
matchesObjectContext
public boolean matchesObjectContext()This predicate is used to test whether a given type can appear in anObjectcontext, such as the expression in a with statement. Most types we will encounter, except notablynull, have at least the potential for converting toObject. Host defined objects can get peculiar. -
findPropertyType
Coerces this type to an Object type, then gets the type of the property whose name is given. UnlikeObjectType.getPropertyType(java.lang.String), returns null if the property is not found.- Returns:
- The property's type.
nullif the current type cannot have properties, or if the type is not found.
-
canBeCalled
public boolean canBeCalled()This predicate is used to test whether a given type can be used as the 'function' in a function call.- Returns:
trueif this type might be callable.
-
canCastTo
Tests whether values ofthistype can be safely assigned to values ofthattype.The default implementation verifies that
thisis a subtype ofthat. -
autoboxesTo
Turn a scalar type to the corresponding object type.- Returns:
- the auto-boxed type or
nullif this type is not a scalar.
-
unboxesTo
Turn an object type to its corresponding scalar type.- Returns:
- the unboxed type or
nullif this type does not unbox.
-
toObjectType
Casts this to an ObjectType, or returns null if this is not an ObjectType. If this is a scalar type, it will *not* be converted to an object type. If you want to simulate JS autoboxing or dereferencing, you should use autoboxesTo() or dereference(). -
autobox
Dereference a type for property access. Filters null/undefined and autoboxes the resulting type. Never returns null. -
dereference
Dereference a type for property access. Filters null/undefined, autoboxes the resulting type, and returns it iff it's an object. -
canTestForEqualityWith
Tests whetherthisandthatare meaningfully comparable. By meaningfully, we mean compatible types that do not lead to step 22 of the definition of the Abstract Equality Comparison Algorithm (11.9.3, page 55–56) of the ECMA-262 specification. -
testForEquality
Comparesthisandthat.- Returns:
TernaryValue.TRUEif the comparison of values ofthistype andthatalways succeed (such asundefinedcompared tonull)TernaryValue.FALSEif the comparison of values ofthistype andthatalways fails (such asundefinedcompared tonumber)TernaryValue.UNKNOWNif the comparison can succeed or fail depending on the concrete values
-
canTestForShallowEqualityWith
Tests whetherthisandthatare meaningfully comparable using shallow comparison. By meaningfully, we mean compatible types that are not rejected by step 1 of the definition of the Strict Equality Comparison Algorithm (11.9.6, page 56–57) of the ECMA-262 specification. -
isNullable
public boolean isNullable()Tests whether this type is nullable. -
collapseUnion
Gets the least supertype of this that's not a union. -
getLeastSupertype
Gets the least supertype ofthisandthat. The least supertype is the join (∨) or supremum of both types in the type lattice.Examples:
number ∨ *=*number ∨ Object=(number, Object)Number ∨ Object=Object
- Returns:
this ∨ that
-
getGreatestSubtype
Gets the greatest subtype ofthisandthat. The greatest subtype is the meet (∧) or infimum of both types in the type lattice.Examples
Number ∧ Any=Anynumber ∧ Object=AnyNumber ∧ Object=Number
- Returns:
this ∨ that
-
getRestrictedTypeGivenToBooleanOutcome
Computes the restricted type of this type knowing that theToBooleanpredicate has a specific value. For more information about theToBooleanpredicate, seegetPossibleToBooleanOutcomes().- Parameters:
outcome- the value of theToBooleanpredicate- Returns:
- the restricted type, or the Any Type if the underlying type could not have yielded this ToBoolean value TODO(user): Move this method to the SemanticRAI and use the visit method of types to get the restricted type.
-
getPossibleToBooleanOutcomes
Computes the set of possible outcomes of theToBooleanpredicate for this type. TheToBooleanpredicate is defined by the ECMA-262 standard, 3rd edition. Its behavior for simple types can be summarized by the following table:type result undefined{false} null{false} boolean{true, false} number{true, false} string{true, false} Object{true} - Returns:
- the set of boolean literals for this type
-
getTypesUnderEquality
Computes the subset ofthisandthattypes if equality is observed. If a valuev1of typenullis equal to a valuev2of type(undefined,number), we can infer that the type ofv1isnulland the type ofv2isundefined.- Returns:
- a pair containing the restricted type of
thisas the first component and the restricted type ofthatas the second element. The returned pair is nevernulleven though its components may benull
-
getTypesUnderInequality
Computes the subset ofthisandthattypes if inequality is observed. If a valuev1of typenumberis not equal to a valuev2of type(undefined,number), we can infer that the type ofv1isnumberand the type ofv2isnumberas well.- Returns:
- a pair containing the restricted type of
thisas the first component and the restricted type ofthatas the second element. The returned pair is nevernulleven though its components may benull
-
getTypesUnderShallowEquality
Computes the subset ofthisandthattypes under shallow equality.- Returns:
- a pair containing the restricted type of
thisas the first component and the restricted type ofthatas the second element. The returned pair is nevernulleven though its components may benull.
-
getTypesUnderShallowInequality
Computes the subset ofthisandthattypes under shallow inequality.- Returns:
- A pair containing the restricted type of
thisas the first component and the restricted type ofthatas the second element. The returned pair is nevernulleven though its components may benull
-
restrictByNotNullOrUndefined
If this is a union type, returns a union type that does not include the null or undefined type. -
isSubtype
Checks whetherthisis a subtype ofthat.Subtyping rules:
- (unknown) — every type is a subtype of the Unknown type.
- (no) — the No type is a subtype of every type.
- (no-object) — the NoObject type is a subtype of every object type (i.e. subtypes of the Object type).
- (ref) — a type is a subtype of itself.
- (union-l) — A union type is a subtype of a type U if all the
union type's constituents are a subtype of U. Formally
(T<sub>1</sub>, …, T<sub>n</sub>) <: Uif and onlyT<sub>k</sub> <: Ufor allk ∈ 1..n. - (union-r) — A type U is a subtype of a union type if it is a
subtype of one of the union type's constituents. Formally
U <: (T<sub>1</sub>, …, T<sub>n</sub>)if and only ifU <: T<sub>k</sub>for some indexk. - (objects) — an Object
O<sub>1</sub>is a subtype of an objectO<sub>2</sub>if it has more properties thanO<sub>2</sub>and all common properties are pairwise subtypes.
- Returns:
this <: that
-
visit
Visit this type with the given visitor.- Returns:
- the value returned by the visitor
- See Also:
-
forceResolve
Force this type to resolve, even if the registry is in a lazy resolving mode. -
resolve
Resolve this type in the given scope. The returned value must be equal tothis, as defined byisEquivalentTo(com.google.javascript.rhino.jstype.JSType). It may or may not be the same object. This method may modify the internal state ofthis, as long as it does so in a way that preserves Object equality. For efficiency, we should only resolve a type once per compilation job. For incremental compilations, one compilation job may need the artifacts from a previous generation, so we will eventually need a generational flag instead of a boolean one. -
isResolved
public final boolean isResolved()Whether the type has been resolved. -
clearResolved
public final void clearResolved()Clears the resolved field. -
setValidator
Certain types have constraints on them at resolution-time. For example, a type in an@extendsannotation must be an object. Clients should inject a validator that emits a warning if the type does not validate, and return false. -
toString
A string representation of this type, suitable for printing in warnings. -
toDebugHashCodeString
A hash code function for diagnosing complicated issues around type-identity. -
toAnnotationString
A string representation of this type, suitable for printing in type annotations at code generation time. -
matchConstraint
Modify this type so that it matches the specified type. This is useful for reverse type-inference, where we want to infer that an object literal matches its constraint (much like how the java compiler does reverse-inference to figure out generics).- Parameters:
constraint-
-