Types.java revision 0
* Copyright 2003-2006 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * Utility class containing various operations on types. * <p>Unless other names are more illustrative, the following naming * conventions should be observed in this file: * <dd>If the first argument to an operation is a type, it should be named t.</dd> * <dd>Similarly, if the second argument to an operation is a type, it should be named s.</dd> * <dd>If an operations takes a list of types, the first should be named ts.</dd> * <dd>A second list of types should be named ss.</dd> * <p><b>This is NOT part of any API supported by Sun Microsystems. * If you write code that depends on this, you do so at your own risk. * This code and its internal interfaces are subject to change or * deletion without notice.</b> // <editor-fold defaultstate="collapsed" desc="Instantiating"> // <editor-fold defaultstate="collapsed" desc="upperBound"> * The "rvalue conversion".<br> * The upper bound of most types is the type * itself. Wildcards, on the other hand have upper * @return the upper bound of the given type // <editor-fold defaultstate="collapsed" desc="lowerBound"> * The "lvalue conversion".<br> * The lower bound of most types is the type * itself. Wildcards, on the other hand have upper * @return the lower bound of the given type // <editor-fold defaultstate="collapsed" desc="isUnbounded"> * Checks that all the arguments to a class are unbounded * wildcards or something else that doesn't make any restrictions * on the arguments. If a class isUnbounded, a raw super- or * subclass can be cast to it without a warning. * @return true iff the given type is unbounded or raw // <editor-fold defaultstate="collapsed" desc="asSub"> * Return the least specific subtype of t that starts with symbol * sym. If none exists, return null. The least specific subtype * is determined as follows: * <p>If there is exactly one parameterized instance of sym that is a * subtype of t, that parameterized instance is returned.<br> * Otherwise, if the plain type or raw type `sym' is a subtype of * type t, the type `sym' itself is returned. Otherwise, null is // The subtype of a raw type is raw // Unbound type arguments default to ? // <editor-fold defaultstate="collapsed" desc="isConvertible"> // <editor-fold defaultstate="collapsed" desc="isSubtype"> * Is t an unchecked subtype of s? * Is t an unchecked subtype of s? * Is t a subtype of s?<br> * (not defined for Method and ForAll types) // You're not allowed to write // Vector<Object> vec = new Vector<String>(); // But with wildcards you can write // Vector<? extends Object> vec = new Vector<String>(); // which means that subtype checking must be done // here instead of same-type checking (via containsType). //todo: test against origin needed? or replace with substitution? * Is t a subtype of every type in given list `ts'?<br> * (not defined for Method and ForAll types)<br> * Allows unchecked conversions. * Are corresponding elements of ts subtypes of ss? If lists are * of different length, return false. /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
/*inlined: ts.isEmpty() && ss.isEmpty();*/ * Are corresponding elements of ts subtypes of ss, allowing * unchecked conversions? If lists are of different length, /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
/*inlined: ts.isEmpty() && ss.isEmpty();*/ // <editor-fold defaultstate="collapsed" desc="isSuperType"> // <editor-fold defaultstate="collapsed" desc="isSameType"> * Are corresponding elements of the lists the same type? If * lists are of different length, return false. /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
/*inlined: ts.isEmpty() && ss.isEmpty();*/ * Is t the same type as s? // isSameType for methods does not take thrown // exceptions into account! // FIXME, this might be leftovers from before capture conversion // <editor-fold defaultstate="collapsed" desc="fromUnknownFun"> * A mapping that turns all unknown types in this type to fresh // <editor-fold defaultstate="collapsed" desc="Contains Type"> // Because of wildcard capture, s must be on the left // hand side of an assignment. Furthermore, t is an // underconstrained type variable, for example, one // that is only used in the return type of a method. // If the type variable is truly underconstrained, it // cannot have any low bounds: * <p>{@code L(T) <: L(S) && U(S) <: U(T)} * <p>This relation is only used by ClassType.isSubtype(), that * <p>{@code C<S> <: C<T> if T contains S.} * <p>Because of F-bounds, this relation can lead to infinite * recursion. Thus we must somehow break that recursion. Notice * that containsType() is only called from ClassType.isSubtype(). * Since the arguments have already been checked against their * <p>{@code U(S) <: U(T) if T is "super" bound (U(T) *is* the bound)} * <p>{@code L(T) <: L(S) if T is "extends" bound (L(T) is bottom)} // debugContainsType(t, s); // <editor-fold defaultstate="collapsed" desc="isCastable"> * Is t is castable to s?<br> * s is assumed to be an erased type.<br> * (not defined for Method and ForAll types). // call recursively to reuse the above code final boolean HIGH =
true;
final boolean LOW =
false;
// <editor-fold defaultstate="collapsed" desc="disjointTypes"> * Two types or wildcards are considered disjoint if it can be * proven that no type can be contained in both. It is * conservative in that it is allowed to say that two types are * not disjoint, even though they actually are. * The type C<X> is castable to C<Y> exactly if X and Y are not // <editor-fold defaultstate="collapsed" desc="lowerBoundArgtypes"> * Returns the lower bounds of the formals of a method. // <editor-fold defaultstate="collapsed" desc="notSoftSubtype"> * This relation answers the question: is impossible that * something of type `t' can be a subtype of `s'? This is * different from the question "is `t' not a subtype of `s'?" * when type variables are involved: Integer is not a subtype of T * where <T extends Number> but it is not true that Integer cannot * possibly be a subtype of T. if (t == s)
return false;
// <editor-fold defaultstate="collapsed" desc="isReifiable"> // <editor-fold defaultstate="collapsed" desc="Array Utils"> * The element type of an array. * Mapping to take element type of an arraytype * The number of dimensions of an array type. // <editor-fold defaultstate="collapsed" desc="asSuper"> * Return the (most specific) base type of t that starts with the * given symbol. If none exists, return null. * Return the base type of t or any of its outer types that starts * with the given symbol. If none exists, return null. * Return the base type of t or any of its enclosing types that * starts with the given symbol. If none exists, return null. // <editor-fold defaultstate="collapsed" desc="memberType"> * The type of given symbol, seen as a member of t. // then base is a raw type // <editor-fold defaultstate="collapsed" desc="isAssignable"> * Is t assignable to s?<br> * Equivalent to subtype except for constant values and raw * (not defined for Method and ForAll types) // <editor-fold defaultstate="collapsed" desc="erasure"> * The erasure of t {@code |t|} -- the type that results when all * type parameters in t are deleted. return t;
/* fast special case */ return t;
/*fast special case*/ // <editor-fold defaultstate="collapsed" desc="makeCompoundType"> * Make a compound type from non-empty list of types * @param bounds the types from which the compound type is formed * @param supertype is objectType if all bounds are interfaces, // error condition, recover * Same as {@link #makeCompoundType(List,Type)}, except that the * second parameter is computed directly. Note that this might * cause a symbol completion. Hence, this version of * makeCompoundType may not be called during a classfile read. * A convenience wrapper for {@link #makeCompoundType(List)}; the * arguments are converted to a list and passed to the other * method. Note that this might cause a symbol completion. * Hence, this version of makeCompoundType may not be called * during a classfile read. // <editor-fold defaultstate="collapsed" desc="supertype"> // A note on wildcards: there is no good way to // determine a supertype for a super bounded wildcard. // An interface has no superclass; its supertype is Object. // Should not happen. See comments below in interfaces * The supertype is always a class type. If the type * variable's bounds start with a class type, this is also * the supertype. Otherwise, the supertype is // <editor-fold defaultstate="collapsed" desc="interfaces"> * Return the interfaces implemented by this class. // If t.interfaces_field is null, then t must // be a parameterized type (not to be confused // with a generic type declaration). // Parameterized type: List<String> // Generic type declaration: class List<E> { ... } // So t corresponds to List<String> and // t.tsym.type corresponds to List<E>. // The reason t must be parameterized type is // that completion will happen as a side // ClassSymbol.getInterfaces. Since // t.interfaces_field is null after // completion, we can assume that t is not the // In this case t is not generic (nor raw). // So this should not happen. // <editor-fold defaultstate="collapsed" desc="isDerivedRaw"> // <editor-fold defaultstate="collapsed" desc="setBounds"> * Set the bounds field of the given type variable to reflect a * (possibly multiple) list of bounds. * @param t a type variable * @param bounds the bounds, must be nonempty * @param supertype is objectType if all bounds are interfaces, * Same as {@link #setBounds(Type.TypeVar,List,Type)}, except that * third parameter is computed directly. Note that this test * might cause a symbol completion. Hence, this version of * setBounds may not be called during a classfile read. // <editor-fold defaultstate="collapsed" desc="getBounds"> * Return list of bounds of the given type variable. // No superclass was given in bounds. // In this case, supertype is Object, erasure is first interface. // <editor-fold defaultstate="collapsed" desc="classBound"> * If the given type is a (possibly selected) type variable, * return the bounding class of this type, otherwise return the // <editor-fold defaultstate="collapsed" desc="sub signature / override equivalence"> * Returns true iff the first signature is a <em>sub * signature</em> of the other. This is <b>not</b> an equivalence * @see "The Java Language Specification, Third Ed. (8.4.2)." * @see #overrideEquivalent(Type t, Type s) * @param t first signature (possibly raw). * @param s second signature (could be subjected to erasure). * @return true if t is a sub signature of s. * Returns true iff these signatures are related by <em>override * equivalence</em>. This is the natural extension of * isSubSignature to an equivalence relation. * @see "The Java Language Specification, Third Ed. (8.4.2)." * @see #isSubSignature(Type t, Type s) * @param t a signature (possible raw, could be subjected to * @param s a signature (possible raw, could be subjected to * @return true if either argument is a sub signature of the other. * Does t have the same arguments as s? It is assumed that both * types are (possibly polymorphic) method types. Monomorphic * method types "have the same arguments", if their argument lists * are equal. Polymorphic method types "have the same arguments", * if they have the same arguments after renaming all type * variables of one to corresponding type variables in the other, * where correspondence is by position in the type parameter list. // <editor-fold defaultstate="collapsed" desc="subst"> * Substitute all occurrences of a type in `from' with the * corresponding type in `to' in 't'. Match lists `from' and `to' * from the right: If lists have different length, discard leading * elements of the longer list. // create new type variables without bounds // the new bounds should use the new type variables in place // set the bounds of new type variables to the new bounds // <editor-fold defaultstate="collapsed" desc="hasSameBounds"> * Does t have the same bounds for quantified variables as s? // <editor-fold defaultstate="collapsed" desc="newInstances"> /** Create new vector of type variables from list of variables * changing all recursive bounds from old to new list. // <editor-fold defaultstate="collapsed" desc="rank"> * The rank of a class is the length of the longest path between * the class and java.lang.Object in the class inheritance * graph. Undefined for all but reference types. // <editor-fold defaultstate="collapsed" desc="toString"> * This toString is slightly more descriptive than the one on Type. buf.
append(
" extends ");
// Java syntax; no need for i18n // No superclass was given in bounds. // In this case, supertype is Object, erasure is first interface. // <editor-fold defaultstate="collapsed" desc="Determining least upper bounds of types"> * <p>A closure is a list of all the supertypes and interfaces of * a class or interface type, ordered by ClassSymbol.precedes * (that is, subclasses come first, arbitrary but fixed * Returns the closure of a class or interface type. * Insert a type in a closure * Form the union of two closures * Return the minimum type of a closure, a compound type if no * Return the minimum types of a closure, suitable for computing * Return the least upper bound of pair of types. if the lub does * Return the least upper bound (lub) of set of types. If the lub * does not exist return the type of null (bottom). // calculate lub(A[], B[]) // if a primitive type is found, then return // arraySuperType unless all the types are the // lub(int[], B[]) is Cloneable & Serializable // all the array types are the same, return one // lub(int[], int[]) is int[] // lub(A[], B[]) is lub(A, B)[] if (t.
tag !=
ARRAY)
// Filter out any arrays // lub(A, B[]) is lub(A, arraySuperType) // initialized lazily to avoid problems during compiler startup // JLS 10.8: all arrays implement Cloneable and Serializable. // <editor-fold defaultstate="collapsed" desc="Greatest lower bound"> // <editor-fold defaultstate="collapsed" desc="hashCode"> * Compute a hash code on a type. // <editor-fold defaultstate="collapsed" desc="Return-Type-Substitutable"> * Does t have a result that is a subtype of the result type of s, * suitable for covariant returns? It is assumed that both types * are (possibly polymorphic) method types. Monomorphic method * types are handled in the obvious way. Polymorphic method types * require renaming all type variables of one to corresponding * type variables in the other, where correspondence is by * position in the type parameter list. */ * Return-Type-Substitutable. * Language Specification, Third Ed. (8.4.5)</a> * Is t an appropriate return type in an overrider for a // <editor-fold defaultstate="collapsed" desc="Box/unbox support"> * Return the class that boxes the given primitive. * Return the primitive type corresponding to a boxed type. // <editor-fold defaultstate="collapsed" desc="Capture conversion"> * JLS 3rd Ed. 5.1.10 Capture Conversion: * Let G name a generic type declaration with n formal type * parameters A1 ... An with corresponding bounds U1 ... Un. There * exists a capture conversion from G<T1 ... Tn> to G<S1 ... Sn>, * where, for 1 <= i <= n: * + If Ti is a wildcard type argument (4.5.1) of the form ? then * Si is a fresh type variable whose upper bound is * Ui[A1 := S1, ..., An := Sn] and whose lower bound is the null * + If Ti is a wildcard type argument of the form ? extends Bi, * then Si is a fresh type variable whose upper bound is * glb(Bi, Ui[A1 := S1, ..., An := Sn]) and whose lower bound is * the null type, where glb(V1,... ,Vm) is V1 & ... & Vm. It is * a compile-time error if for any two classes (not interfaces) * Vi and Vj,Vi is not a subclass of Vj or vice versa. * + If Ti is a wildcard type argument of the form ? super Bi, * then Si is a fresh type variable whose upper bound is * Ui[A1 := S1, ..., An := Sn] and whose lower bound is Bi. * Capture conversion on any type other than a parameterized type * (4.5) acts as an identity conversion (5.1.1). Capture * conversions never require a special action at run time and * therefore never throw an exception at run time. * Capture conversion is not applied recursively. * Capture conversion as specified by JLS 3rd Ed. return erasure(t);
// some "rare" type involved // <editor-fold defaultstate="collapsed" desc="Internal utility methods"> // We are casting from type $from$ to type $to$, which are // non-final unrelated types. This method // tries to reject a cast by transferring type parameters // from $to$ to $from$ by common superinterfaces. // The arguments to the supers could be unified here to // get a more accurate analysis // reject if there is a common method signature with // incompatible return types. // We are casting from type $from$ to type $to$, which are // unrelated types one of which is final and the other of // which is an interface. This method // tries to reject a cast by transferring type parameters // from the final class to the interface. // reject if there is a common method signature with // incompatible return types. // To and from are (possibly different) parameterizations // of the same class or interface * Adapt a type by computing a substitution which maps a source * @param source the source type * @param target the target type * @param from the type variables of the computed substitution * @param to the types of the computed substitution. // Check to see if there is // already a mapping for $source$, in which case // the old mapping will be merged with the new * Adapt a type by computing a substitution which maps a list of * source types to a list of target types. * @param source the source type * @param target the target type * @param from the type variables of the computed substitution * @param to the types of the computed substitution. // Adapt should never fail calculating a mapping from // t.tsym.type to t as there can be no merge problem. * Rewrite all type variables (universal quantifiers) in the given * type to wildcards (existential quantifiers). This is used to * determine if a cast is allowed. For example, if high is true * and {@code T <: Number}, then {@code List<T>} is rewritten to * {@code List<? extends Number>}. Since {@code List<Integer> <: * List<? extends Number>} a {@code List<T>} can be cast to {@code * List<Integer>} with a warning. * @param high if true return an upper bound; otherwise a lower * @param rewriteTypeVars only rewrite captured wildcards if false; * otherwise rewrite all type variables * @return the type rewritten with wildcards (existential * Create a wildcard with the given upper (extends) bound; create * an unbounded wildcard if bound is Object. * @param bound the upper bound * @param formal the formal type parameter that will be * substituted by the wildcard * Create a wildcard with the given lower (super) bound; create an * unbounded wildcard if bound is bottom (type of {@code null}). * @param bound the lower bound * @param formal the formal type parameter that will be * substituted by the wildcard * A wrapper for a type that allows use in sets. // <editor-fold defaultstate="collapsed" desc="Visitors"> * A default visitor for types. All visitor methods except * visitType are implemented by delegating to visitType. Concrete * subclasses must provide an implementation of visitType and can * override other methods as needed. * @param <R> the return type of the operation implemented by this * visitor; use Void if no return type is needed. * @param <S> the type of the second argument (the first being the * type itself) of the operation implemented by this visitor; use * Void if a second argument is not needed. * A <em>simple</em> visitor for types. This visitor is simple as * captured wildcards, for-all types (generic methods), and * undetermined type variables (part of inference) are hidden. * Captured wildcards are hidden by treating them as type * variables and the rest are hidden by visiting their qtypes. * @param <R> the return type of the operation implemented by this * visitor; use Void if no return type is needed. * @param <S> the type of the second argument (the first being the * type itself) of the operation implemented by this visitor; use * Void if a second argument is not needed. * A plain relation on types. That is a 2-ary function on the * form Type × Type → Boolean. * <!-- In plain text: Type x Type -> Boolean --> * A convenience visitor for implementing operations that only * require one argument (the type itself), that is, unary * @param <R> the return type of the operation implemented by this * visitor; use Void if no return type is needed. * A visitor for implementing a mapping from types to types. The * default behavior of this class is to implement the identity * mapping (mapping a type to itself). This can be overridden in * @param <S> the type of the second argument (the first being the * type itself) of this mapping; use Void if a second argument is