src/share/classes/com/sun/tools/javac/code/Types.java

Tue, 16 Sep 2008 18:35:18 -0700

author
jjg
date
Tue, 16 Sep 2008 18:35:18 -0700
changeset 113
eff38cc97183
parent 110
91eea580fbe9
child 121
609fb59657b4
permissions
-rw-r--r--

6574134: Allow for alternative implementation of Name Table with garbage collection of name bytes
Reviewed-by: darcy, mcimadamore

     1 /*
     2  * Copyright 2003-2008 Sun Microsystems, Inc.  All Rights Reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Sun designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Sun in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
    22  * CA 95054 USA or visit www.sun.com if you need additional information or
    23  * have any questions.
    24  */
    26 package com.sun.tools.javac.code;
    28 import java.util.*;
    30 import com.sun.tools.javac.util.*;
    31 import com.sun.tools.javac.util.List;
    33 import com.sun.tools.javac.jvm.ClassReader;
    34 import com.sun.tools.javac.comp.Check;
    36 import static com.sun.tools.javac.code.Type.*;
    37 import static com.sun.tools.javac.code.TypeTags.*;
    38 import static com.sun.tools.javac.code.Symbol.*;
    39 import static com.sun.tools.javac.code.Flags.*;
    40 import static com.sun.tools.javac.code.BoundKind.*;
    41 import static com.sun.tools.javac.util.ListBuffer.lb;
    43 /**
    44  * Utility class containing various operations on types.
    45  *
    46  * <p>Unless other names are more illustrative, the following naming
    47  * conventions should be observed in this file:
    48  *
    49  * <dl>
    50  * <dt>t</dt>
    51  * <dd>If the first argument to an operation is a type, it should be named t.</dd>
    52  * <dt>s</dt>
    53  * <dd>Similarly, if the second argument to an operation is a type, it should be named s.</dd>
    54  * <dt>ts</dt>
    55  * <dd>If an operations takes a list of types, the first should be named ts.</dd>
    56  * <dt>ss</dt>
    57  * <dd>A second list of types should be named ss.</dd>
    58  * </dl>
    59  *
    60  * <p><b>This is NOT part of any API supported by Sun Microsystems.
    61  * If you write code that depends on this, you do so at your own risk.
    62  * This code and its internal interfaces are subject to change or
    63  * deletion without notice.</b>
    64  */
    65 public class Types {
    66     protected static final Context.Key<Types> typesKey =
    67         new Context.Key<Types>();
    69     final Symtab syms;
    70     final Names names;
    71     final boolean allowBoxing;
    72     final ClassReader reader;
    73     final Source source;
    74     final Check chk;
    75     List<Warner> warnStack = List.nil();
    76     final Name capturedName;
    78     // <editor-fold defaultstate="collapsed" desc="Instantiating">
    79     public static Types instance(Context context) {
    80         Types instance = context.get(typesKey);
    81         if (instance == null)
    82             instance = new Types(context);
    83         return instance;
    84     }
    86     protected Types(Context context) {
    87         context.put(typesKey, this);
    88         syms = Symtab.instance(context);
    89         names = Names.instance(context);
    90         allowBoxing = Source.instance(context).allowBoxing();
    91         reader = ClassReader.instance(context);
    92         source = Source.instance(context);
    93         chk = Check.instance(context);
    94         capturedName = names.fromString("<captured wildcard>");
    95     }
    96     // </editor-fold>
    98     // <editor-fold defaultstate="collapsed" desc="upperBound">
    99     /**
   100      * The "rvalue conversion".<br>
   101      * The upper bound of most types is the type
   102      * itself.  Wildcards, on the other hand have upper
   103      * and lower bounds.
   104      * @param t a type
   105      * @return the upper bound of the given type
   106      */
   107     public Type upperBound(Type t) {
   108         return upperBound.visit(t);
   109     }
   110     // where
   111         private final MapVisitor<Void> upperBound = new MapVisitor<Void>() {
   113             @Override
   114             public Type visitWildcardType(WildcardType t, Void ignored) {
   115                 if (t.isSuperBound())
   116                     return t.bound == null ? syms.objectType : t.bound.bound;
   117                 else
   118                     return visit(t.type);
   119             }
   121             @Override
   122             public Type visitCapturedType(CapturedType t, Void ignored) {
   123                 return visit(t.bound);
   124             }
   125         };
   126     // </editor-fold>
   128     // <editor-fold defaultstate="collapsed" desc="lowerBound">
   129     /**
   130      * The "lvalue conversion".<br>
   131      * The lower bound of most types is the type
   132      * itself.  Wildcards, on the other hand have upper
   133      * and lower bounds.
   134      * @param t a type
   135      * @return the lower bound of the given type
   136      */
   137     public Type lowerBound(Type t) {
   138         return lowerBound.visit(t);
   139     }
   140     // where
   141         private final MapVisitor<Void> lowerBound = new MapVisitor<Void>() {
   143             @Override
   144             public Type visitWildcardType(WildcardType t, Void ignored) {
   145                 return t.isExtendsBound() ? syms.botType : visit(t.type);
   146             }
   148             @Override
   149             public Type visitCapturedType(CapturedType t, Void ignored) {
   150                 return visit(t.getLowerBound());
   151             }
   152         };
   153     // </editor-fold>
   155     // <editor-fold defaultstate="collapsed" desc="isUnbounded">
   156     /**
   157      * Checks that all the arguments to a class are unbounded
   158      * wildcards or something else that doesn't make any restrictions
   159      * on the arguments. If a class isUnbounded, a raw super- or
   160      * subclass can be cast to it without a warning.
   161      * @param t a type
   162      * @return true iff the given type is unbounded or raw
   163      */
   164     public boolean isUnbounded(Type t) {
   165         return isUnbounded.visit(t);
   166     }
   167     // where
   168         private final UnaryVisitor<Boolean> isUnbounded = new UnaryVisitor<Boolean>() {
   170             public Boolean visitType(Type t, Void ignored) {
   171                 return true;
   172             }
   174             @Override
   175             public Boolean visitClassType(ClassType t, Void ignored) {
   176                 List<Type> parms = t.tsym.type.allparams();
   177                 List<Type> args = t.allparams();
   178                 while (parms.nonEmpty()) {
   179                     WildcardType unb = new WildcardType(syms.objectType,
   180                                                         BoundKind.UNBOUND,
   181                                                         syms.boundClass,
   182                                                         (TypeVar)parms.head);
   183                     if (!containsType(args.head, unb))
   184                         return false;
   185                     parms = parms.tail;
   186                     args = args.tail;
   187                 }
   188                 return true;
   189             }
   190         };
   191     // </editor-fold>
   193     // <editor-fold defaultstate="collapsed" desc="asSub">
   194     /**
   195      * Return the least specific subtype of t that starts with symbol
   196      * sym.  If none exists, return null.  The least specific subtype
   197      * is determined as follows:
   198      *
   199      * <p>If there is exactly one parameterized instance of sym that is a
   200      * subtype of t, that parameterized instance is returned.<br>
   201      * Otherwise, if the plain type or raw type `sym' is a subtype of
   202      * type t, the type `sym' itself is returned.  Otherwise, null is
   203      * returned.
   204      */
   205     public Type asSub(Type t, Symbol sym) {
   206         return asSub.visit(t, sym);
   207     }
   208     // where
   209         private final SimpleVisitor<Type,Symbol> asSub = new SimpleVisitor<Type,Symbol>() {
   211             public Type visitType(Type t, Symbol sym) {
   212                 return null;
   213             }
   215             @Override
   216             public Type visitClassType(ClassType t, Symbol sym) {
   217                 if (t.tsym == sym)
   218                     return t;
   219                 Type base = asSuper(sym.type, t.tsym);
   220                 if (base == null)
   221                     return null;
   222                 ListBuffer<Type> from = new ListBuffer<Type>();
   223                 ListBuffer<Type> to = new ListBuffer<Type>();
   224                 try {
   225                     adapt(base, t, from, to);
   226                 } catch (AdaptFailure ex) {
   227                     return null;
   228                 }
   229                 Type res = subst(sym.type, from.toList(), to.toList());
   230                 if (!isSubtype(res, t))
   231                     return null;
   232                 ListBuffer<Type> openVars = new ListBuffer<Type>();
   233                 for (List<Type> l = sym.type.allparams();
   234                      l.nonEmpty(); l = l.tail)
   235                     if (res.contains(l.head) && !t.contains(l.head))
   236                         openVars.append(l.head);
   237                 if (openVars.nonEmpty()) {
   238                     if (t.isRaw()) {
   239                         // The subtype of a raw type is raw
   240                         res = erasure(res);
   241                     } else {
   242                         // Unbound type arguments default to ?
   243                         List<Type> opens = openVars.toList();
   244                         ListBuffer<Type> qs = new ListBuffer<Type>();
   245                         for (List<Type> iter = opens; iter.nonEmpty(); iter = iter.tail) {
   246                             qs.append(new WildcardType(syms.objectType, BoundKind.UNBOUND, syms.boundClass, (TypeVar) iter.head));
   247                         }
   248                         res = subst(res, opens, qs.toList());
   249                     }
   250                 }
   251                 return res;
   252             }
   254             @Override
   255             public Type visitErrorType(ErrorType t, Symbol sym) {
   256                 return t;
   257             }
   258         };
   259     // </editor-fold>
   261     // <editor-fold defaultstate="collapsed" desc="isConvertible">
   262     /**
   263      * Is t a subtype of or convertiable via boxing/unboxing
   264      * convertions to s?
   265      */
   266     public boolean isConvertible(Type t, Type s, Warner warn) {
   267         boolean tPrimitive = t.isPrimitive();
   268         boolean sPrimitive = s.isPrimitive();
   269         if (tPrimitive == sPrimitive)
   270             return isSubtypeUnchecked(t, s, warn);
   271         if (!allowBoxing) return false;
   272         return tPrimitive
   273             ? isSubtype(boxedClass(t).type, s)
   274             : isSubtype(unboxedType(t), s);
   275     }
   277     /**
   278      * Is t a subtype of or convertiable via boxing/unboxing
   279      * convertions to s?
   280      */
   281     public boolean isConvertible(Type t, Type s) {
   282         return isConvertible(t, s, Warner.noWarnings);
   283     }
   284     // </editor-fold>
   286     // <editor-fold defaultstate="collapsed" desc="isSubtype">
   287     /**
   288      * Is t an unchecked subtype of s?
   289      */
   290     public boolean isSubtypeUnchecked(Type t, Type s) {
   291         return isSubtypeUnchecked(t, s, Warner.noWarnings);
   292     }
   293     /**
   294      * Is t an unchecked subtype of s?
   295      */
   296     public boolean isSubtypeUnchecked(Type t, Type s, Warner warn) {
   297         if (t.tag == ARRAY && s.tag == ARRAY) {
   298             return (((ArrayType)t).elemtype.tag <= lastBaseTag)
   299                 ? isSameType(elemtype(t), elemtype(s))
   300                 : isSubtypeUnchecked(elemtype(t), elemtype(s), warn);
   301         } else if (isSubtype(t, s)) {
   302             return true;
   303         }
   304         else if (t.tag == TYPEVAR) {
   305             return isSubtypeUnchecked(t.getUpperBound(), s, warn);
   306         }
   307         else if (s.tag == UNDETVAR) {
   308             UndetVar uv = (UndetVar)s;
   309             if (uv.inst != null)
   310                 return isSubtypeUnchecked(t, uv.inst, warn);
   311         }
   312         else if (!s.isRaw()) {
   313             Type t2 = asSuper(t, s.tsym);
   314             if (t2 != null && t2.isRaw()) {
   315                 if (isReifiable(s))
   316                     warn.silentUnchecked();
   317                 else
   318                     warn.warnUnchecked();
   319                 return true;
   320             }
   321         }
   322         return false;
   323     }
   325     /**
   326      * Is t a subtype of s?<br>
   327      * (not defined for Method and ForAll types)
   328      */
   329     final public boolean isSubtype(Type t, Type s) {
   330         return isSubtype(t, s, true);
   331     }
   332     final public boolean isSubtypeNoCapture(Type t, Type s) {
   333         return isSubtype(t, s, false);
   334     }
   335     public boolean isSubtype(Type t, Type s, boolean capture) {
   336         if (t == s)
   337             return true;
   339         if (s.tag >= firstPartialTag)
   340             return isSuperType(s, t);
   342         Type lower = lowerBound(s);
   343         if (s != lower)
   344             return isSubtype(capture ? capture(t) : t, lower, false);
   346         return isSubtype.visit(capture ? capture(t) : t, s);
   347     }
   348     // where
   349         private TypeRelation isSubtype = new TypeRelation()
   350         {
   351             public Boolean visitType(Type t, Type s) {
   352                 switch (t.tag) {
   353                 case BYTE: case CHAR:
   354                     return (t.tag == s.tag ||
   355                               t.tag + 2 <= s.tag && s.tag <= DOUBLE);
   356                 case SHORT: case INT: case LONG: case FLOAT: case DOUBLE:
   357                     return t.tag <= s.tag && s.tag <= DOUBLE;
   358                 case BOOLEAN: case VOID:
   359                     return t.tag == s.tag;
   360                 case TYPEVAR:
   361                     return isSubtypeNoCapture(t.getUpperBound(), s);
   362                 case BOT:
   363                     return
   364                         s.tag == BOT || s.tag == CLASS ||
   365                         s.tag == ARRAY || s.tag == TYPEVAR;
   366                 case NONE:
   367                     return false;
   368                 default:
   369                     throw new AssertionError("isSubtype " + t.tag);
   370                 }
   371             }
   373             private Set<TypePair> cache = new HashSet<TypePair>();
   375             private boolean containsTypeRecursive(Type t, Type s) {
   376                 TypePair pair = new TypePair(t, s);
   377                 if (cache.add(pair)) {
   378                     try {
   379                         return containsType(t.getTypeArguments(),
   380                                             s.getTypeArguments());
   381                     } finally {
   382                         cache.remove(pair);
   383                     }
   384                 } else {
   385                     return containsType(t.getTypeArguments(),
   386                                         rewriteSupers(s).getTypeArguments());
   387                 }
   388             }
   390             private Type rewriteSupers(Type t) {
   391                 if (!t.isParameterized())
   392                     return t;
   393                 ListBuffer<Type> from = lb();
   394                 ListBuffer<Type> to = lb();
   395                 adaptSelf(t, from, to);
   396                 if (from.isEmpty())
   397                     return t;
   398                 ListBuffer<Type> rewrite = lb();
   399                 boolean changed = false;
   400                 for (Type orig : to.toList()) {
   401                     Type s = rewriteSupers(orig);
   402                     if (s.isSuperBound() && !s.isExtendsBound()) {
   403                         s = new WildcardType(syms.objectType,
   404                                              BoundKind.UNBOUND,
   405                                              syms.boundClass);
   406                         changed = true;
   407                     } else if (s != orig) {
   408                         s = new WildcardType(upperBound(s),
   409                                              BoundKind.EXTENDS,
   410                                              syms.boundClass);
   411                         changed = true;
   412                     }
   413                     rewrite.append(s);
   414                 }
   415                 if (changed)
   416                     return subst(t.tsym.type, from.toList(), rewrite.toList());
   417                 else
   418                     return t;
   419             }
   421             @Override
   422             public Boolean visitClassType(ClassType t, Type s) {
   423                 Type sup = asSuper(t, s.tsym);
   424                 return sup != null
   425                     && sup.tsym == s.tsym
   426                     // You're not allowed to write
   427                     //     Vector<Object> vec = new Vector<String>();
   428                     // But with wildcards you can write
   429                     //     Vector<? extends Object> vec = new Vector<String>();
   430                     // which means that subtype checking must be done
   431                     // here instead of same-type checking (via containsType).
   432                     && (!s.isParameterized() || containsTypeRecursive(s, sup))
   433                     && isSubtypeNoCapture(sup.getEnclosingType(),
   434                                           s.getEnclosingType());
   435             }
   437             @Override
   438             public Boolean visitArrayType(ArrayType t, Type s) {
   439                 if (s.tag == ARRAY) {
   440                     if (t.elemtype.tag <= lastBaseTag)
   441                         return isSameType(t.elemtype, elemtype(s));
   442                     else
   443                         return isSubtypeNoCapture(t.elemtype, elemtype(s));
   444                 }
   446                 if (s.tag == CLASS) {
   447                     Name sname = s.tsym.getQualifiedName();
   448                     return sname == names.java_lang_Object
   449                         || sname == names.java_lang_Cloneable
   450                         || sname == names.java_io_Serializable;
   451                 }
   453                 return false;
   454             }
   456             @Override
   457             public Boolean visitUndetVar(UndetVar t, Type s) {
   458                 //todo: test against origin needed? or replace with substitution?
   459                 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN)
   460                     return true;
   462                 if (t.inst != null)
   463                     return isSubtypeNoCapture(t.inst, s); // TODO: ", warn"?
   465                 t.hibounds = t.hibounds.prepend(s);
   466                 return true;
   467             }
   469             @Override
   470             public Boolean visitErrorType(ErrorType t, Type s) {
   471                 return true;
   472             }
   473         };
   475     /**
   476      * Is t a subtype of every type in given list `ts'?<br>
   477      * (not defined for Method and ForAll types)<br>
   478      * Allows unchecked conversions.
   479      */
   480     public boolean isSubtypeUnchecked(Type t, List<Type> ts, Warner warn) {
   481         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
   482             if (!isSubtypeUnchecked(t, l.head, warn))
   483                 return false;
   484         return true;
   485     }
   487     /**
   488      * Are corresponding elements of ts subtypes of ss?  If lists are
   489      * of different length, return false.
   490      */
   491     public boolean isSubtypes(List<Type> ts, List<Type> ss) {
   492         while (ts.tail != null && ss.tail != null
   493                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   494                isSubtype(ts.head, ss.head)) {
   495             ts = ts.tail;
   496             ss = ss.tail;
   497         }
   498         return ts.tail == null && ss.tail == null;
   499         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   500     }
   502     /**
   503      * Are corresponding elements of ts subtypes of ss, allowing
   504      * unchecked conversions?  If lists are of different length,
   505      * return false.
   506      **/
   507     public boolean isSubtypesUnchecked(List<Type> ts, List<Type> ss, Warner warn) {
   508         while (ts.tail != null && ss.tail != null
   509                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   510                isSubtypeUnchecked(ts.head, ss.head, warn)) {
   511             ts = ts.tail;
   512             ss = ss.tail;
   513         }
   514         return ts.tail == null && ss.tail == null;
   515         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   516     }
   517     // </editor-fold>
   519     // <editor-fold defaultstate="collapsed" desc="isSuperType">
   520     /**
   521      * Is t a supertype of s?
   522      */
   523     public boolean isSuperType(Type t, Type s) {
   524         switch (t.tag) {
   525         case ERROR:
   526             return true;
   527         case UNDETVAR: {
   528             UndetVar undet = (UndetVar)t;
   529             if (t == s ||
   530                 undet.qtype == s ||
   531                 s.tag == ERROR ||
   532                 s.tag == BOT) return true;
   533             if (undet.inst != null)
   534                 return isSubtype(s, undet.inst);
   535             undet.lobounds = undet.lobounds.prepend(s);
   536             return true;
   537         }
   538         default:
   539             return isSubtype(s, t);
   540         }
   541     }
   542     // </editor-fold>
   544     // <editor-fold defaultstate="collapsed" desc="isSameType">
   545     /**
   546      * Are corresponding elements of the lists the same type?  If
   547      * lists are of different length, return false.
   548      */
   549     public boolean isSameTypes(List<Type> ts, List<Type> ss) {
   550         while (ts.tail != null && ss.tail != null
   551                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   552                isSameType(ts.head, ss.head)) {
   553             ts = ts.tail;
   554             ss = ss.tail;
   555         }
   556         return ts.tail == null && ss.tail == null;
   557         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   558     }
   560     /**
   561      * Is t the same type as s?
   562      */
   563     public boolean isSameType(Type t, Type s) {
   564         return isSameType.visit(t, s);
   565     }
   566     // where
   567         private TypeRelation isSameType = new TypeRelation() {
   569             public Boolean visitType(Type t, Type s) {
   570                 if (t == s)
   571                     return true;
   573                 if (s.tag >= firstPartialTag)
   574                     return visit(s, t);
   576                 switch (t.tag) {
   577                 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
   578                 case DOUBLE: case BOOLEAN: case VOID: case BOT: case NONE:
   579                     return t.tag == s.tag;
   580                 case TYPEVAR:
   581                     return s.isSuperBound()
   582                         && !s.isExtendsBound()
   583                         && visit(t, upperBound(s));
   584                 default:
   585                     throw new AssertionError("isSameType " + t.tag);
   586                 }
   587             }
   589             @Override
   590             public Boolean visitWildcardType(WildcardType t, Type s) {
   591                 if (s.tag >= firstPartialTag)
   592                     return visit(s, t);
   593                 else
   594                     return false;
   595             }
   597             @Override
   598             public Boolean visitClassType(ClassType t, Type s) {
   599                 if (t == s)
   600                     return true;
   602                 if (s.tag >= firstPartialTag)
   603                     return visit(s, t);
   605                 if (s.isSuperBound() && !s.isExtendsBound())
   606                     return visit(t, upperBound(s)) && visit(t, lowerBound(s));
   608                 if (t.isCompound() && s.isCompound()) {
   609                     if (!visit(supertype(t), supertype(s)))
   610                         return false;
   612                     HashSet<SingletonType> set = new HashSet<SingletonType>();
   613                     for (Type x : interfaces(t))
   614                         set.add(new SingletonType(x));
   615                     for (Type x : interfaces(s)) {
   616                         if (!set.remove(new SingletonType(x)))
   617                             return false;
   618                     }
   619                     return (set.size() == 0);
   620                 }
   621                 return t.tsym == s.tsym
   622                     && visit(t.getEnclosingType(), s.getEnclosingType())
   623                     && containsTypeEquivalent(t.getTypeArguments(), s.getTypeArguments());
   624             }
   626             @Override
   627             public Boolean visitArrayType(ArrayType t, Type s) {
   628                 if (t == s)
   629                     return true;
   631                 if (s.tag >= firstPartialTag)
   632                     return visit(s, t);
   634                 return s.tag == ARRAY
   635                     && containsTypeEquivalent(t.elemtype, elemtype(s));
   636             }
   638             @Override
   639             public Boolean visitMethodType(MethodType t, Type s) {
   640                 // isSameType for methods does not take thrown
   641                 // exceptions into account!
   642                 return hasSameArgs(t, s) && visit(t.getReturnType(), s.getReturnType());
   643             }
   645             @Override
   646             public Boolean visitPackageType(PackageType t, Type s) {
   647                 return t == s;
   648             }
   650             @Override
   651             public Boolean visitForAll(ForAll t, Type s) {
   652                 if (s.tag != FORALL)
   653                     return false;
   655                 ForAll forAll = (ForAll)s;
   656                 return hasSameBounds(t, forAll)
   657                     && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
   658             }
   660             @Override
   661             public Boolean visitUndetVar(UndetVar t, Type s) {
   662                 if (s.tag == WILDCARD)
   663                     // FIXME, this might be leftovers from before capture conversion
   664                     return false;
   666                 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN)
   667                     return true;
   669                 if (t.inst != null)
   670                     return visit(t.inst, s);
   672                 t.inst = fromUnknownFun.apply(s);
   673                 for (List<Type> l = t.lobounds; l.nonEmpty(); l = l.tail) {
   674                     if (!isSubtype(l.head, t.inst))
   675                         return false;
   676                 }
   677                 for (List<Type> l = t.hibounds; l.nonEmpty(); l = l.tail) {
   678                     if (!isSubtype(t.inst, l.head))
   679                         return false;
   680                 }
   681                 return true;
   682             }
   684             @Override
   685             public Boolean visitErrorType(ErrorType t, Type s) {
   686                 return true;
   687             }
   688         };
   689     // </editor-fold>
   691     // <editor-fold defaultstate="collapsed" desc="fromUnknownFun">
   692     /**
   693      * A mapping that turns all unknown types in this type to fresh
   694      * unknown variables.
   695      */
   696     public Mapping fromUnknownFun = new Mapping("fromUnknownFun") {
   697             public Type apply(Type t) {
   698                 if (t.tag == UNKNOWN) return new UndetVar(t);
   699                 else return t.map(this);
   700             }
   701         };
   702     // </editor-fold>
   704     // <editor-fold defaultstate="collapsed" desc="Contains Type">
   705     public boolean containedBy(Type t, Type s) {
   706         switch (t.tag) {
   707         case UNDETVAR:
   708             if (s.tag == WILDCARD) {
   709                 UndetVar undetvar = (UndetVar)t;
   711                 // Because of wildcard capture, s must be on the left
   712                 // hand side of an assignment.  Furthermore, t is an
   713                 // underconstrained type variable, for example, one
   714                 // that is only used in the return type of a method.
   715                 // If the type variable is truly underconstrained, it
   716                 // cannot have any low bounds:
   717                 assert undetvar.lobounds.isEmpty() : undetvar;
   719                 undetvar.inst = glb(upperBound(s), undetvar.inst);
   720                 return true;
   721             } else {
   722                 return isSameType(t, s);
   723             }
   724         case ERROR:
   725             return true;
   726         default:
   727             return containsType(s, t);
   728         }
   729     }
   731     boolean containsType(List<Type> ts, List<Type> ss) {
   732         while (ts.nonEmpty() && ss.nonEmpty()
   733                && containsType(ts.head, ss.head)) {
   734             ts = ts.tail;
   735             ss = ss.tail;
   736         }
   737         return ts.isEmpty() && ss.isEmpty();
   738     }
   740     /**
   741      * Check if t contains s.
   742      *
   743      * <p>T contains S if:
   744      *
   745      * <p>{@code L(T) <: L(S) && U(S) <: U(T)}
   746      *
   747      * <p>This relation is only used by ClassType.isSubtype(), that
   748      * is,
   749      *
   750      * <p>{@code C<S> <: C<T> if T contains S.}
   751      *
   752      * <p>Because of F-bounds, this relation can lead to infinite
   753      * recursion.  Thus we must somehow break that recursion.  Notice
   754      * that containsType() is only called from ClassType.isSubtype().
   755      * Since the arguments have already been checked against their
   756      * bounds, we know:
   757      *
   758      * <p>{@code U(S) <: U(T) if T is "super" bound (U(T) *is* the bound)}
   759      *
   760      * <p>{@code L(T) <: L(S) if T is "extends" bound (L(T) is bottom)}
   761      *
   762      * @param t a type
   763      * @param s a type
   764      */
   765     public boolean containsType(Type t, Type s) {
   766         return containsType.visit(t, s);
   767     }
   768     // where
   769         private TypeRelation containsType = new TypeRelation() {
   771             private Type U(Type t) {
   772                 while (t.tag == WILDCARD) {
   773                     WildcardType w = (WildcardType)t;
   774                     if (w.isSuperBound())
   775                         return w.bound == null ? syms.objectType : w.bound.bound;
   776                     else
   777                         t = w.type;
   778                 }
   779                 return t;
   780             }
   782             private Type L(Type t) {
   783                 while (t.tag == WILDCARD) {
   784                     WildcardType w = (WildcardType)t;
   785                     if (w.isExtendsBound())
   786                         return syms.botType;
   787                     else
   788                         t = w.type;
   789                 }
   790                 return t;
   791             }
   793             public Boolean visitType(Type t, Type s) {
   794                 if (s.tag >= firstPartialTag)
   795                     return containedBy(s, t);
   796                 else
   797                     return isSameType(t, s);
   798             }
   800             void debugContainsType(WildcardType t, Type s) {
   801                 System.err.println();
   802                 System.err.format(" does %s contain %s?%n", t, s);
   803                 System.err.format(" %s U(%s) <: U(%s) %s = %s%n",
   804                                   upperBound(s), s, t, U(t),
   805                                   t.isSuperBound()
   806                                   || isSubtypeNoCapture(upperBound(s), U(t)));
   807                 System.err.format(" %s L(%s) <: L(%s) %s = %s%n",
   808                                   L(t), t, s, lowerBound(s),
   809                                   t.isExtendsBound()
   810                                   || isSubtypeNoCapture(L(t), lowerBound(s)));
   811                 System.err.println();
   812             }
   814             @Override
   815             public Boolean visitWildcardType(WildcardType t, Type s) {
   816                 if (s.tag >= firstPartialTag)
   817                     return containedBy(s, t);
   818                 else {
   819                     // debugContainsType(t, s);
   820                     return isSameWildcard(t, s)
   821                         || isCaptureOf(s, t)
   822                         || ((t.isExtendsBound() || isSubtypeNoCapture(L(t), lowerBound(s))) &&
   823                             (t.isSuperBound() || isSubtypeNoCapture(upperBound(s), U(t))));
   824                 }
   825             }
   827             @Override
   828             public Boolean visitUndetVar(UndetVar t, Type s) {
   829                 if (s.tag != WILDCARD)
   830                     return isSameType(t, s);
   831                 else
   832                     return false;
   833             }
   835             @Override
   836             public Boolean visitErrorType(ErrorType t, Type s) {
   837                 return true;
   838             }
   839         };
   841     public boolean isCaptureOf(Type s, WildcardType t) {
   842         if (s.tag != TYPEVAR || !((TypeVar)s).isCaptured())
   843             return false;
   844         return isSameWildcard(t, ((CapturedType)s).wildcard);
   845     }
   847     public boolean isSameWildcard(WildcardType t, Type s) {
   848         if (s.tag != WILDCARD)
   849             return false;
   850         WildcardType w = (WildcardType)s;
   851         return w.kind == t.kind && w.type == t.type;
   852     }
   854     public boolean containsTypeEquivalent(List<Type> ts, List<Type> ss) {
   855         while (ts.nonEmpty() && ss.nonEmpty()
   856                && containsTypeEquivalent(ts.head, ss.head)) {
   857             ts = ts.tail;
   858             ss = ss.tail;
   859         }
   860         return ts.isEmpty() && ss.isEmpty();
   861     }
   862     // </editor-fold>
   864     // <editor-fold defaultstate="collapsed" desc="isCastable">
   865     public boolean isCastable(Type t, Type s) {
   866         return isCastable(t, s, Warner.noWarnings);
   867     }
   869     /**
   870      * Is t is castable to s?<br>
   871      * s is assumed to be an erased type.<br>
   872      * (not defined for Method and ForAll types).
   873      */
   874     public boolean isCastable(Type t, Type s, Warner warn) {
   875         if (t == s)
   876             return true;
   878         if (t.isPrimitive() != s.isPrimitive())
   879             return allowBoxing && isConvertible(t, s, warn);
   881         if (warn != warnStack.head) {
   882             try {
   883                 warnStack = warnStack.prepend(warn);
   884                 return isCastable.visit(t, s);
   885             } finally {
   886                 warnStack = warnStack.tail;
   887             }
   888         } else {
   889             return isCastable.visit(t, s);
   890         }
   891     }
   892     // where
   893         private TypeRelation isCastable = new TypeRelation() {
   895             public Boolean visitType(Type t, Type s) {
   896                 if (s.tag == ERROR)
   897                     return true;
   899                 switch (t.tag) {
   900                 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
   901                 case DOUBLE:
   902                     return s.tag <= DOUBLE;
   903                 case BOOLEAN:
   904                     return s.tag == BOOLEAN;
   905                 case VOID:
   906                     return false;
   907                 case BOT:
   908                     return isSubtype(t, s);
   909                 default:
   910                     throw new AssertionError();
   911                 }
   912             }
   914             @Override
   915             public Boolean visitWildcardType(WildcardType t, Type s) {
   916                 return isCastable(upperBound(t), s, warnStack.head);
   917             }
   919             @Override
   920             public Boolean visitClassType(ClassType t, Type s) {
   921                 if (s.tag == ERROR || s.tag == BOT)
   922                     return true;
   924                 if (s.tag == TYPEVAR) {
   925                     if (isCastable(s.getUpperBound(), t, Warner.noWarnings)) {
   926                         warnStack.head.warnUnchecked();
   927                         return true;
   928                     } else {
   929                         return false;
   930                     }
   931                 }
   933                 if (t.isCompound()) {
   934                     if (!visit(supertype(t), s))
   935                         return false;
   936                     for (Type intf : interfaces(t)) {
   937                         if (!visit(intf, s))
   938                             return false;
   939                     }
   940                     return true;
   941                 }
   943                 if (s.isCompound()) {
   944                     // call recursively to reuse the above code
   945                     return visitClassType((ClassType)s, t);
   946                 }
   948                 if (s.tag == CLASS || s.tag == ARRAY) {
   949                     boolean upcast;
   950                     if ((upcast = isSubtype(erasure(t), erasure(s)))
   951                         || isSubtype(erasure(s), erasure(t))) {
   952                         if (!upcast && s.tag == ARRAY) {
   953                             if (!isReifiable(s))
   954                                 warnStack.head.warnUnchecked();
   955                             return true;
   956                         } else if (s.isRaw()) {
   957                             return true;
   958                         } else if (t.isRaw()) {
   959                             if (!isUnbounded(s))
   960                                 warnStack.head.warnUnchecked();
   961                             return true;
   962                         }
   963                         // Assume |a| <: |b|
   964                         final Type a = upcast ? t : s;
   965                         final Type b = upcast ? s : t;
   966                         final boolean HIGH = true;
   967                         final boolean LOW = false;
   968                         final boolean DONT_REWRITE_TYPEVARS = false;
   969                         Type aHigh = rewriteQuantifiers(a, HIGH, DONT_REWRITE_TYPEVARS);
   970                         Type aLow  = rewriteQuantifiers(a, LOW,  DONT_REWRITE_TYPEVARS);
   971                         Type bHigh = rewriteQuantifiers(b, HIGH, DONT_REWRITE_TYPEVARS);
   972                         Type bLow  = rewriteQuantifiers(b, LOW,  DONT_REWRITE_TYPEVARS);
   973                         Type lowSub = asSub(bLow, aLow.tsym);
   974                         Type highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
   975                         if (highSub == null) {
   976                             final boolean REWRITE_TYPEVARS = true;
   977                             aHigh = rewriteQuantifiers(a, HIGH, REWRITE_TYPEVARS);
   978                             aLow  = rewriteQuantifiers(a, LOW,  REWRITE_TYPEVARS);
   979                             bHigh = rewriteQuantifiers(b, HIGH, REWRITE_TYPEVARS);
   980                             bLow  = rewriteQuantifiers(b, LOW,  REWRITE_TYPEVARS);
   981                             lowSub = asSub(bLow, aLow.tsym);
   982                             highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
   983                         }
   984                         if (highSub != null) {
   985                             assert a.tsym == highSub.tsym && a.tsym == lowSub.tsym
   986                                 : a.tsym + " != " + highSub.tsym + " != " + lowSub.tsym;
   987                             if (!disjointTypes(aHigh.getTypeArguments(), highSub.getTypeArguments())
   988                                 && !disjointTypes(aHigh.getTypeArguments(), lowSub.getTypeArguments())
   989                                 && !disjointTypes(aLow.getTypeArguments(), highSub.getTypeArguments())
   990                                 && !disjointTypes(aLow.getTypeArguments(), lowSub.getTypeArguments())) {
   991                                 if (upcast ? giveWarning(a, highSub) || giveWarning(a, lowSub)
   992                                            : giveWarning(highSub, a) || giveWarning(lowSub, a))
   993                                     warnStack.head.warnUnchecked();
   994                                 return true;
   995                             }
   996                         }
   997                         if (isReifiable(s))
   998                             return isSubtypeUnchecked(a, b);
   999                         else
  1000                             return isSubtypeUnchecked(a, b, warnStack.head);
  1003                     // Sidecast
  1004                     if (s.tag == CLASS) {
  1005                         if ((s.tsym.flags() & INTERFACE) != 0) {
  1006                             return ((t.tsym.flags() & FINAL) == 0)
  1007                                 ? sideCast(t, s, warnStack.head)
  1008                                 : sideCastFinal(t, s, warnStack.head);
  1009                         } else if ((t.tsym.flags() & INTERFACE) != 0) {
  1010                             return ((s.tsym.flags() & FINAL) == 0)
  1011                                 ? sideCast(t, s, warnStack.head)
  1012                                 : sideCastFinal(t, s, warnStack.head);
  1013                         } else {
  1014                             // unrelated class types
  1015                             return false;
  1019                 return false;
  1022             @Override
  1023             public Boolean visitArrayType(ArrayType t, Type s) {
  1024                 switch (s.tag) {
  1025                 case ERROR:
  1026                 case BOT:
  1027                     return true;
  1028                 case TYPEVAR:
  1029                     if (isCastable(s, t, Warner.noWarnings)) {
  1030                         warnStack.head.warnUnchecked();
  1031                         return true;
  1032                     } else {
  1033                         return false;
  1035                 case CLASS:
  1036                     return isSubtype(t, s);
  1037                 case ARRAY:
  1038                     if (elemtype(t).tag <= lastBaseTag) {
  1039                         return elemtype(t).tag == elemtype(s).tag;
  1040                     } else {
  1041                         return visit(elemtype(t), elemtype(s));
  1043                 default:
  1044                     return false;
  1048             @Override
  1049             public Boolean visitTypeVar(TypeVar t, Type s) {
  1050                 switch (s.tag) {
  1051                 case ERROR:
  1052                 case BOT:
  1053                     return true;
  1054                 case TYPEVAR:
  1055                     if (isSubtype(t, s)) {
  1056                         return true;
  1057                     } else if (isCastable(t.bound, s, Warner.noWarnings)) {
  1058                         warnStack.head.warnUnchecked();
  1059                         return true;
  1060                     } else {
  1061                         return false;
  1063                 default:
  1064                     return isCastable(t.bound, s, warnStack.head);
  1068             @Override
  1069             public Boolean visitErrorType(ErrorType t, Type s) {
  1070                 return true;
  1072         };
  1073     // </editor-fold>
  1075     // <editor-fold defaultstate="collapsed" desc="disjointTypes">
  1076     public boolean disjointTypes(List<Type> ts, List<Type> ss) {
  1077         while (ts.tail != null && ss.tail != null) {
  1078             if (disjointType(ts.head, ss.head)) return true;
  1079             ts = ts.tail;
  1080             ss = ss.tail;
  1082         return false;
  1085     /**
  1086      * Two types or wildcards are considered disjoint if it can be
  1087      * proven that no type can be contained in both. It is
  1088      * conservative in that it is allowed to say that two types are
  1089      * not disjoint, even though they actually are.
  1091      * The type C<X> is castable to C<Y> exactly if X and Y are not
  1092      * disjoint.
  1093      */
  1094     public boolean disjointType(Type t, Type s) {
  1095         return disjointType.visit(t, s);
  1097     // where
  1098         private TypeRelation disjointType = new TypeRelation() {
  1100             private Set<TypePair> cache = new HashSet<TypePair>();
  1102             public Boolean visitType(Type t, Type s) {
  1103                 if (s.tag == WILDCARD)
  1104                     return visit(s, t);
  1105                 else
  1106                     return notSoftSubtypeRecursive(t, s) || notSoftSubtypeRecursive(s, t);
  1109             private boolean isCastableRecursive(Type t, Type s) {
  1110                 TypePair pair = new TypePair(t, s);
  1111                 if (cache.add(pair)) {
  1112                     try {
  1113                         return Types.this.isCastable(t, s);
  1114                     } finally {
  1115                         cache.remove(pair);
  1117                 } else {
  1118                     return true;
  1122             private boolean notSoftSubtypeRecursive(Type t, Type s) {
  1123                 TypePair pair = new TypePair(t, s);
  1124                 if (cache.add(pair)) {
  1125                     try {
  1126                         return Types.this.notSoftSubtype(t, s);
  1127                     } finally {
  1128                         cache.remove(pair);
  1130                 } else {
  1131                     return false;
  1135             @Override
  1136             public Boolean visitWildcardType(WildcardType t, Type s) {
  1137                 if (t.isUnbound())
  1138                     return false;
  1140                 if (s.tag != WILDCARD) {
  1141                     if (t.isExtendsBound())
  1142                         return notSoftSubtypeRecursive(s, t.type);
  1143                     else // isSuperBound()
  1144                         return notSoftSubtypeRecursive(t.type, s);
  1147                 if (s.isUnbound())
  1148                     return false;
  1150                 if (t.isExtendsBound()) {
  1151                     if (s.isExtendsBound())
  1152                         return !isCastableRecursive(t.type, upperBound(s));
  1153                     else if (s.isSuperBound())
  1154                         return notSoftSubtypeRecursive(lowerBound(s), t.type);
  1155                 } else if (t.isSuperBound()) {
  1156                     if (s.isExtendsBound())
  1157                         return notSoftSubtypeRecursive(t.type, upperBound(s));
  1159                 return false;
  1161         };
  1162     // </editor-fold>
  1164     // <editor-fold defaultstate="collapsed" desc="lowerBoundArgtypes">
  1165     /**
  1166      * Returns the lower bounds of the formals of a method.
  1167      */
  1168     public List<Type> lowerBoundArgtypes(Type t) {
  1169         return map(t.getParameterTypes(), lowerBoundMapping);
  1171     private final Mapping lowerBoundMapping = new Mapping("lowerBound") {
  1172             public Type apply(Type t) {
  1173                 return lowerBound(t);
  1175         };
  1176     // </editor-fold>
  1178     // <editor-fold defaultstate="collapsed" desc="notSoftSubtype">
  1179     /**
  1180      * This relation answers the question: is impossible that
  1181      * something of type `t' can be a subtype of `s'? This is
  1182      * different from the question "is `t' not a subtype of `s'?"
  1183      * when type variables are involved: Integer is not a subtype of T
  1184      * where <T extends Number> but it is not true that Integer cannot
  1185      * possibly be a subtype of T.
  1186      */
  1187     public boolean notSoftSubtype(Type t, Type s) {
  1188         if (t == s) return false;
  1189         if (t.tag == TYPEVAR) {
  1190             TypeVar tv = (TypeVar) t;
  1191             if (s.tag == TYPEVAR)
  1192                 s = s.getUpperBound();
  1193             return !isCastable(tv.bound,
  1194                                s,
  1195                                Warner.noWarnings);
  1197         if (s.tag != WILDCARD)
  1198             s = upperBound(s);
  1199         if (s.tag == TYPEVAR)
  1200             s = s.getUpperBound();
  1201         return !isSubtype(t, s);
  1203     // </editor-fold>
  1205     // <editor-fold defaultstate="collapsed" desc="isReifiable">
  1206     public boolean isReifiable(Type t) {
  1207         return isReifiable.visit(t);
  1209     // where
  1210         private UnaryVisitor<Boolean> isReifiable = new UnaryVisitor<Boolean>() {
  1212             public Boolean visitType(Type t, Void ignored) {
  1213                 return true;
  1216             @Override
  1217             public Boolean visitClassType(ClassType t, Void ignored) {
  1218                 if (!t.isParameterized())
  1219                     return true;
  1221                 for (Type param : t.allparams()) {
  1222                     if (!param.isUnbound())
  1223                         return false;
  1225                 return true;
  1228             @Override
  1229             public Boolean visitArrayType(ArrayType t, Void ignored) {
  1230                 return visit(t.elemtype);
  1233             @Override
  1234             public Boolean visitTypeVar(TypeVar t, Void ignored) {
  1235                 return false;
  1237         };
  1238     // </editor-fold>
  1240     // <editor-fold defaultstate="collapsed" desc="Array Utils">
  1241     public boolean isArray(Type t) {
  1242         while (t.tag == WILDCARD)
  1243             t = upperBound(t);
  1244         return t.tag == ARRAY;
  1247     /**
  1248      * The element type of an array.
  1249      */
  1250     public Type elemtype(Type t) {
  1251         switch (t.tag) {
  1252         case WILDCARD:
  1253             return elemtype(upperBound(t));
  1254         case ARRAY:
  1255             return ((ArrayType)t).elemtype;
  1256         case FORALL:
  1257             return elemtype(((ForAll)t).qtype);
  1258         case ERROR:
  1259             return t;
  1260         default:
  1261             return null;
  1265     /**
  1266      * Mapping to take element type of an arraytype
  1267      */
  1268     private Mapping elemTypeFun = new Mapping ("elemTypeFun") {
  1269         public Type apply(Type t) { return elemtype(t); }
  1270     };
  1272     /**
  1273      * The number of dimensions of an array type.
  1274      */
  1275     public int dimensions(Type t) {
  1276         int result = 0;
  1277         while (t.tag == ARRAY) {
  1278             result++;
  1279             t = elemtype(t);
  1281         return result;
  1283     // </editor-fold>
  1285     // <editor-fold defaultstate="collapsed" desc="asSuper">
  1286     /**
  1287      * Return the (most specific) base type of t that starts with the
  1288      * given symbol.  If none exists, return null.
  1290      * @param t a type
  1291      * @param sym a symbol
  1292      */
  1293     public Type asSuper(Type t, Symbol sym) {
  1294         return asSuper.visit(t, sym);
  1296     // where
  1297         private SimpleVisitor<Type,Symbol> asSuper = new SimpleVisitor<Type,Symbol>() {
  1299             public Type visitType(Type t, Symbol sym) {
  1300                 return null;
  1303             @Override
  1304             public Type visitClassType(ClassType t, Symbol sym) {
  1305                 if (t.tsym == sym)
  1306                     return t;
  1308                 Type st = supertype(t);
  1309                 if (st.tag == CLASS || st.tag == TYPEVAR || st.tag == ERROR) {
  1310                     Type x = asSuper(st, sym);
  1311                     if (x != null)
  1312                         return x;
  1314                 if ((sym.flags() & INTERFACE) != 0) {
  1315                     for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
  1316                         Type x = asSuper(l.head, sym);
  1317                         if (x != null)
  1318                             return x;
  1321                 return null;
  1324             @Override
  1325             public Type visitArrayType(ArrayType t, Symbol sym) {
  1326                 return isSubtype(t, sym.type) ? sym.type : null;
  1329             @Override
  1330             public Type visitTypeVar(TypeVar t, Symbol sym) {
  1331                 if (t.tsym == sym)
  1332                     return t;
  1333                 else
  1334                     return asSuper(t.bound, sym);
  1337             @Override
  1338             public Type visitErrorType(ErrorType t, Symbol sym) {
  1339                 return t;
  1341         };
  1343     /**
  1344      * Return the base type of t or any of its outer types that starts
  1345      * with the given symbol.  If none exists, return null.
  1347      * @param t a type
  1348      * @param sym a symbol
  1349      */
  1350     public Type asOuterSuper(Type t, Symbol sym) {
  1351         switch (t.tag) {
  1352         case CLASS:
  1353             do {
  1354                 Type s = asSuper(t, sym);
  1355                 if (s != null) return s;
  1356                 t = t.getEnclosingType();
  1357             } while (t.tag == CLASS);
  1358             return null;
  1359         case ARRAY:
  1360             return isSubtype(t, sym.type) ? sym.type : null;
  1361         case TYPEVAR:
  1362             return asSuper(t, sym);
  1363         case ERROR:
  1364             return t;
  1365         default:
  1366             return null;
  1370     /**
  1371      * Return the base type of t or any of its enclosing types that
  1372      * starts with the given symbol.  If none exists, return null.
  1374      * @param t a type
  1375      * @param sym a symbol
  1376      */
  1377     public Type asEnclosingSuper(Type t, Symbol sym) {
  1378         switch (t.tag) {
  1379         case CLASS:
  1380             do {
  1381                 Type s = asSuper(t, sym);
  1382                 if (s != null) return s;
  1383                 Type outer = t.getEnclosingType();
  1384                 t = (outer.tag == CLASS) ? outer :
  1385                     (t.tsym.owner.enclClass() != null) ? t.tsym.owner.enclClass().type :
  1386                     Type.noType;
  1387             } while (t.tag == CLASS);
  1388             return null;
  1389         case ARRAY:
  1390             return isSubtype(t, sym.type) ? sym.type : null;
  1391         case TYPEVAR:
  1392             return asSuper(t, sym);
  1393         case ERROR:
  1394             return t;
  1395         default:
  1396             return null;
  1399     // </editor-fold>
  1401     // <editor-fold defaultstate="collapsed" desc="memberType">
  1402     /**
  1403      * The type of given symbol, seen as a member of t.
  1405      * @param t a type
  1406      * @param sym a symbol
  1407      */
  1408     public Type memberType(Type t, Symbol sym) {
  1409         return (sym.flags() & STATIC) != 0
  1410             ? sym.type
  1411             : memberType.visit(t, sym);
  1413     // where
  1414         private SimpleVisitor<Type,Symbol> memberType = new SimpleVisitor<Type,Symbol>() {
  1416             public Type visitType(Type t, Symbol sym) {
  1417                 return sym.type;
  1420             @Override
  1421             public Type visitWildcardType(WildcardType t, Symbol sym) {
  1422                 return memberType(upperBound(t), sym);
  1425             @Override
  1426             public Type visitClassType(ClassType t, Symbol sym) {
  1427                 Symbol owner = sym.owner;
  1428                 long flags = sym.flags();
  1429                 if (((flags & STATIC) == 0) && owner.type.isParameterized()) {
  1430                     Type base = asOuterSuper(t, owner);
  1431                     if (base != null) {
  1432                         List<Type> ownerParams = owner.type.allparams();
  1433                         List<Type> baseParams = base.allparams();
  1434                         if (ownerParams.nonEmpty()) {
  1435                             if (baseParams.isEmpty()) {
  1436                                 // then base is a raw type
  1437                                 return erasure(sym.type);
  1438                             } else {
  1439                                 return subst(sym.type, ownerParams, baseParams);
  1444                 return sym.type;
  1447             @Override
  1448             public Type visitTypeVar(TypeVar t, Symbol sym) {
  1449                 return memberType(t.bound, sym);
  1452             @Override
  1453             public Type visitErrorType(ErrorType t, Symbol sym) {
  1454                 return t;
  1456         };
  1457     // </editor-fold>
  1459     // <editor-fold defaultstate="collapsed" desc="isAssignable">
  1460     public boolean isAssignable(Type t, Type s) {
  1461         return isAssignable(t, s, Warner.noWarnings);
  1464     /**
  1465      * Is t assignable to s?<br>
  1466      * Equivalent to subtype except for constant values and raw
  1467      * types.<br>
  1468      * (not defined for Method and ForAll types)
  1469      */
  1470     public boolean isAssignable(Type t, Type s, Warner warn) {
  1471         if (t.tag == ERROR)
  1472             return true;
  1473         if (t.tag <= INT && t.constValue() != null) {
  1474             int value = ((Number)t.constValue()).intValue();
  1475             switch (s.tag) {
  1476             case BYTE:
  1477                 if (Byte.MIN_VALUE <= value && value <= Byte.MAX_VALUE)
  1478                     return true;
  1479                 break;
  1480             case CHAR:
  1481                 if (Character.MIN_VALUE <= value && value <= Character.MAX_VALUE)
  1482                     return true;
  1483                 break;
  1484             case SHORT:
  1485                 if (Short.MIN_VALUE <= value && value <= Short.MAX_VALUE)
  1486                     return true;
  1487                 break;
  1488             case INT:
  1489                 return true;
  1490             case CLASS:
  1491                 switch (unboxedType(s).tag) {
  1492                 case BYTE:
  1493                 case CHAR:
  1494                 case SHORT:
  1495                     return isAssignable(t, unboxedType(s), warn);
  1497                 break;
  1500         return isConvertible(t, s, warn);
  1502     // </editor-fold>
  1504     // <editor-fold defaultstate="collapsed" desc="erasure">
  1505     /**
  1506      * The erasure of t {@code |t|} -- the type that results when all
  1507      * type parameters in t are deleted.
  1508      */
  1509     public Type erasure(Type t) {
  1510         return erasure(t, false);
  1512     //where
  1513     private Type erasure(Type t, boolean recurse) {
  1514         if (t.tag <= lastBaseTag)
  1515             return t; /* fast special case */
  1516         else
  1517             return erasure.visit(t, recurse);
  1519     // where
  1520         private SimpleVisitor<Type, Boolean> erasure = new SimpleVisitor<Type, Boolean>() {
  1521             public Type visitType(Type t, Boolean recurse) {
  1522                 if (t.tag <= lastBaseTag)
  1523                     return t; /*fast special case*/
  1524                 else
  1525                     return t.map(recurse ? erasureRecFun : erasureFun);
  1528             @Override
  1529             public Type visitWildcardType(WildcardType t, Boolean recurse) {
  1530                 return erasure(upperBound(t), recurse);
  1533             @Override
  1534             public Type visitClassType(ClassType t, Boolean recurse) {
  1535                 Type erased = t.tsym.erasure(Types.this);
  1536                 if (recurse) {
  1537                     erased = new ErasedClassType(erased.getEnclosingType(),erased.tsym);
  1539                 return erased;
  1542             @Override
  1543             public Type visitTypeVar(TypeVar t, Boolean recurse) {
  1544                 return erasure(t.bound, recurse);
  1547             @Override
  1548             public Type visitErrorType(ErrorType t, Boolean recurse) {
  1549                 return t;
  1551         };
  1553     private Mapping erasureFun = new Mapping ("erasure") {
  1554             public Type apply(Type t) { return erasure(t); }
  1555         };
  1557     private Mapping erasureRecFun = new Mapping ("erasureRecursive") {
  1558         public Type apply(Type t) { return erasureRecursive(t); }
  1559     };
  1561     public List<Type> erasure(List<Type> ts) {
  1562         return Type.map(ts, erasureFun);
  1565     public Type erasureRecursive(Type t) {
  1566         return erasure(t, true);
  1569     public List<Type> erasureRecursive(List<Type> ts) {
  1570         return Type.map(ts, erasureRecFun);
  1572     // </editor-fold>
  1574     // <editor-fold defaultstate="collapsed" desc="makeCompoundType">
  1575     /**
  1576      * Make a compound type from non-empty list of types
  1578      * @param bounds            the types from which the compound type is formed
  1579      * @param supertype         is objectType if all bounds are interfaces,
  1580      *                          null otherwise.
  1581      */
  1582     public Type makeCompoundType(List<Type> bounds,
  1583                                  Type supertype) {
  1584         ClassSymbol bc =
  1585             new ClassSymbol(ABSTRACT|PUBLIC|SYNTHETIC|COMPOUND|ACYCLIC,
  1586                             Type.moreInfo
  1587                                 ? names.fromString(bounds.toString())
  1588                                 : names.empty,
  1589                             syms.noSymbol);
  1590         if (bounds.head.tag == TYPEVAR)
  1591             // error condition, recover
  1592             bc.erasure_field = syms.objectType;
  1593         else
  1594             bc.erasure_field = erasure(bounds.head);
  1595         bc.members_field = new Scope(bc);
  1596         ClassType bt = (ClassType)bc.type;
  1597         bt.allparams_field = List.nil();
  1598         if (supertype != null) {
  1599             bt.supertype_field = supertype;
  1600             bt.interfaces_field = bounds;
  1601         } else {
  1602             bt.supertype_field = bounds.head;
  1603             bt.interfaces_field = bounds.tail;
  1605         assert bt.supertype_field.tsym.completer != null
  1606             || !bt.supertype_field.isInterface()
  1607             : bt.supertype_field;
  1608         return bt;
  1611     /**
  1612      * Same as {@link #makeCompoundType(List,Type)}, except that the
  1613      * second parameter is computed directly. Note that this might
  1614      * cause a symbol completion.  Hence, this version of
  1615      * makeCompoundType may not be called during a classfile read.
  1616      */
  1617     public Type makeCompoundType(List<Type> bounds) {
  1618         Type supertype = (bounds.head.tsym.flags() & INTERFACE) != 0 ?
  1619             supertype(bounds.head) : null;
  1620         return makeCompoundType(bounds, supertype);
  1623     /**
  1624      * A convenience wrapper for {@link #makeCompoundType(List)}; the
  1625      * arguments are converted to a list and passed to the other
  1626      * method.  Note that this might cause a symbol completion.
  1627      * Hence, this version of makeCompoundType may not be called
  1628      * during a classfile read.
  1629      */
  1630     public Type makeCompoundType(Type bound1, Type bound2) {
  1631         return makeCompoundType(List.of(bound1, bound2));
  1633     // </editor-fold>
  1635     // <editor-fold defaultstate="collapsed" desc="supertype">
  1636     public Type supertype(Type t) {
  1637         return supertype.visit(t);
  1639     // where
  1640         private UnaryVisitor<Type> supertype = new UnaryVisitor<Type>() {
  1642             public Type visitType(Type t, Void ignored) {
  1643                 // A note on wildcards: there is no good way to
  1644                 // determine a supertype for a super bounded wildcard.
  1645                 return null;
  1648             @Override
  1649             public Type visitClassType(ClassType t, Void ignored) {
  1650                 if (t.supertype_field == null) {
  1651                     Type supertype = ((ClassSymbol)t.tsym).getSuperclass();
  1652                     // An interface has no superclass; its supertype is Object.
  1653                     if (t.isInterface())
  1654                         supertype = ((ClassType)t.tsym.type).supertype_field;
  1655                     if (t.supertype_field == null) {
  1656                         List<Type> actuals = classBound(t).allparams();
  1657                         List<Type> formals = t.tsym.type.allparams();
  1658                         if (t.hasErasedSupertypes()) {
  1659                             t.supertype_field = erasureRecursive(supertype);
  1660                         } else if (formals.nonEmpty()) {
  1661                             t.supertype_field = subst(supertype, formals, actuals);
  1663                         else {
  1664                             t.supertype_field = supertype;
  1668                 return t.supertype_field;
  1671             /**
  1672              * The supertype is always a class type. If the type
  1673              * variable's bounds start with a class type, this is also
  1674              * the supertype.  Otherwise, the supertype is
  1675              * java.lang.Object.
  1676              */
  1677             @Override
  1678             public Type visitTypeVar(TypeVar t, Void ignored) {
  1679                 if (t.bound.tag == TYPEVAR ||
  1680                     (!t.bound.isCompound() && !t.bound.isInterface())) {
  1681                     return t.bound;
  1682                 } else {
  1683                     return supertype(t.bound);
  1687             @Override
  1688             public Type visitArrayType(ArrayType t, Void ignored) {
  1689                 if (t.elemtype.isPrimitive() || isSameType(t.elemtype, syms.objectType))
  1690                     return arraySuperType();
  1691                 else
  1692                     return new ArrayType(supertype(t.elemtype), t.tsym);
  1695             @Override
  1696             public Type visitErrorType(ErrorType t, Void ignored) {
  1697                 return t;
  1699         };
  1700     // </editor-fold>
  1702     // <editor-fold defaultstate="collapsed" desc="interfaces">
  1703     /**
  1704      * Return the interfaces implemented by this class.
  1705      */
  1706     public List<Type> interfaces(Type t) {
  1707         return interfaces.visit(t);
  1709     // where
  1710         private UnaryVisitor<List<Type>> interfaces = new UnaryVisitor<List<Type>>() {
  1712             public List<Type> visitType(Type t, Void ignored) {
  1713                 return List.nil();
  1716             @Override
  1717             public List<Type> visitClassType(ClassType t, Void ignored) {
  1718                 if (t.interfaces_field == null) {
  1719                     List<Type> interfaces = ((ClassSymbol)t.tsym).getInterfaces();
  1720                     if (t.interfaces_field == null) {
  1721                         // If t.interfaces_field is null, then t must
  1722                         // be a parameterized type (not to be confused
  1723                         // with a generic type declaration).
  1724                         // Terminology:
  1725                         //    Parameterized type: List<String>
  1726                         //    Generic type declaration: class List<E> { ... }
  1727                         // So t corresponds to List<String> and
  1728                         // t.tsym.type corresponds to List<E>.
  1729                         // The reason t must be parameterized type is
  1730                         // that completion will happen as a side
  1731                         // effect of calling
  1732                         // ClassSymbol.getInterfaces.  Since
  1733                         // t.interfaces_field is null after
  1734                         // completion, we can assume that t is not the
  1735                         // type of a class/interface declaration.
  1736                         assert t != t.tsym.type : t.toString();
  1737                         List<Type> actuals = t.allparams();
  1738                         List<Type> formals = t.tsym.type.allparams();
  1739                         if (t.hasErasedSupertypes()) {
  1740                             t.interfaces_field = erasureRecursive(interfaces);
  1741                         } else if (formals.nonEmpty()) {
  1742                             t.interfaces_field =
  1743                                 upperBounds(subst(interfaces, formals, actuals));
  1745                         else {
  1746                             t.interfaces_field = interfaces;
  1750                 return t.interfaces_field;
  1753             @Override
  1754             public List<Type> visitTypeVar(TypeVar t, Void ignored) {
  1755                 if (t.bound.isCompound())
  1756                     return interfaces(t.bound);
  1758                 if (t.bound.isInterface())
  1759                     return List.of(t.bound);
  1761                 return List.nil();
  1763         };
  1764     // </editor-fold>
  1766     // <editor-fold defaultstate="collapsed" desc="isDerivedRaw">
  1767     Map<Type,Boolean> isDerivedRawCache = new HashMap<Type,Boolean>();
  1769     public boolean isDerivedRaw(Type t) {
  1770         Boolean result = isDerivedRawCache.get(t);
  1771         if (result == null) {
  1772             result = isDerivedRawInternal(t);
  1773             isDerivedRawCache.put(t, result);
  1775         return result;
  1778     public boolean isDerivedRawInternal(Type t) {
  1779         if (t.isErroneous())
  1780             return false;
  1781         return
  1782             t.isRaw() ||
  1783             supertype(t) != null && isDerivedRaw(supertype(t)) ||
  1784             isDerivedRaw(interfaces(t));
  1787     public boolean isDerivedRaw(List<Type> ts) {
  1788         List<Type> l = ts;
  1789         while (l.nonEmpty() && !isDerivedRaw(l.head)) l = l.tail;
  1790         return l.nonEmpty();
  1792     // </editor-fold>
  1794     // <editor-fold defaultstate="collapsed" desc="setBounds">
  1795     /**
  1796      * Set the bounds field of the given type variable to reflect a
  1797      * (possibly multiple) list of bounds.
  1798      * @param t                 a type variable
  1799      * @param bounds            the bounds, must be nonempty
  1800      * @param supertype         is objectType if all bounds are interfaces,
  1801      *                          null otherwise.
  1802      */
  1803     public void setBounds(TypeVar t, List<Type> bounds, Type supertype) {
  1804         if (bounds.tail.isEmpty())
  1805             t.bound = bounds.head;
  1806         else
  1807             t.bound = makeCompoundType(bounds, supertype);
  1808         t.rank_field = -1;
  1811     /**
  1812      * Same as {@link #setBounds(Type.TypeVar,List,Type)}, except that
  1813      * third parameter is computed directly.  Note that this test
  1814      * might cause a symbol completion.  Hence, this version of
  1815      * setBounds may not be called during a classfile read.
  1816      */
  1817     public void setBounds(TypeVar t, List<Type> bounds) {
  1818         Type supertype = (bounds.head.tsym.flags() & INTERFACE) != 0 ?
  1819             supertype(bounds.head) : null;
  1820         setBounds(t, bounds, supertype);
  1821         t.rank_field = -1;
  1823     // </editor-fold>
  1825     // <editor-fold defaultstate="collapsed" desc="getBounds">
  1826     /**
  1827      * Return list of bounds of the given type variable.
  1828      */
  1829     public List<Type> getBounds(TypeVar t) {
  1830         if (t.bound.isErroneous() || !t.bound.isCompound())
  1831             return List.of(t.bound);
  1832         else if ((erasure(t).tsym.flags() & INTERFACE) == 0)
  1833             return interfaces(t).prepend(supertype(t));
  1834         else
  1835             // No superclass was given in bounds.
  1836             // In this case, supertype is Object, erasure is first interface.
  1837             return interfaces(t);
  1839     // </editor-fold>
  1841     // <editor-fold defaultstate="collapsed" desc="classBound">
  1842     /**
  1843      * If the given type is a (possibly selected) type variable,
  1844      * return the bounding class of this type, otherwise return the
  1845      * type itself.
  1846      */
  1847     public Type classBound(Type t) {
  1848         return classBound.visit(t);
  1850     // where
  1851         private UnaryVisitor<Type> classBound = new UnaryVisitor<Type>() {
  1853             public Type visitType(Type t, Void ignored) {
  1854                 return t;
  1857             @Override
  1858             public Type visitClassType(ClassType t, Void ignored) {
  1859                 Type outer1 = classBound(t.getEnclosingType());
  1860                 if (outer1 != t.getEnclosingType())
  1861                     return new ClassType(outer1, t.getTypeArguments(), t.tsym);
  1862                 else
  1863                     return t;
  1866             @Override
  1867             public Type visitTypeVar(TypeVar t, Void ignored) {
  1868                 return classBound(supertype(t));
  1871             @Override
  1872             public Type visitErrorType(ErrorType t, Void ignored) {
  1873                 return t;
  1875         };
  1876     // </editor-fold>
  1878     // <editor-fold defaultstate="collapsed" desc="sub signature / override equivalence">
  1879     /**
  1880      * Returns true iff the first signature is a <em>sub
  1881      * signature</em> of the other.  This is <b>not</b> an equivalence
  1882      * relation.
  1884      * @see "The Java Language Specification, Third Ed. (8.4.2)."
  1885      * @see #overrideEquivalent(Type t, Type s)
  1886      * @param t first signature (possibly raw).
  1887      * @param s second signature (could be subjected to erasure).
  1888      * @return true if t is a sub signature of s.
  1889      */
  1890     public boolean isSubSignature(Type t, Type s) {
  1891         return hasSameArgs(t, s) || hasSameArgs(t, erasure(s));
  1894     /**
  1895      * Returns true iff these signatures are related by <em>override
  1896      * equivalence</em>.  This is the natural extension of
  1897      * isSubSignature to an equivalence relation.
  1899      * @see "The Java Language Specification, Third Ed. (8.4.2)."
  1900      * @see #isSubSignature(Type t, Type s)
  1901      * @param t a signature (possible raw, could be subjected to
  1902      * erasure).
  1903      * @param s a signature (possible raw, could be subjected to
  1904      * erasure).
  1905      * @return true if either argument is a sub signature of the other.
  1906      */
  1907     public boolean overrideEquivalent(Type t, Type s) {
  1908         return hasSameArgs(t, s) ||
  1909             hasSameArgs(t, erasure(s)) || hasSameArgs(erasure(t), s);
  1912     /**
  1913      * Does t have the same arguments as s?  It is assumed that both
  1914      * types are (possibly polymorphic) method types.  Monomorphic
  1915      * method types "have the same arguments", if their argument lists
  1916      * are equal.  Polymorphic method types "have the same arguments",
  1917      * if they have the same arguments after renaming all type
  1918      * variables of one to corresponding type variables in the other,
  1919      * where correspondence is by position in the type parameter list.
  1920      */
  1921     public boolean hasSameArgs(Type t, Type s) {
  1922         return hasSameArgs.visit(t, s);
  1924     // where
  1925         private TypeRelation hasSameArgs = new TypeRelation() {
  1927             public Boolean visitType(Type t, Type s) {
  1928                 throw new AssertionError();
  1931             @Override
  1932             public Boolean visitMethodType(MethodType t, Type s) {
  1933                 return s.tag == METHOD
  1934                     && containsTypeEquivalent(t.argtypes, s.getParameterTypes());
  1937             @Override
  1938             public Boolean visitForAll(ForAll t, Type s) {
  1939                 if (s.tag != FORALL)
  1940                     return false;
  1942                 ForAll forAll = (ForAll)s;
  1943                 return hasSameBounds(t, forAll)
  1944                     && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
  1947             @Override
  1948             public Boolean visitErrorType(ErrorType t, Type s) {
  1949                 return false;
  1951         };
  1952     // </editor-fold>
  1954     // <editor-fold defaultstate="collapsed" desc="subst">
  1955     public List<Type> subst(List<Type> ts,
  1956                             List<Type> from,
  1957                             List<Type> to) {
  1958         return new Subst(from, to).subst(ts);
  1961     /**
  1962      * Substitute all occurrences of a type in `from' with the
  1963      * corresponding type in `to' in 't'. Match lists `from' and `to'
  1964      * from the right: If lists have different length, discard leading
  1965      * elements of the longer list.
  1966      */
  1967     public Type subst(Type t, List<Type> from, List<Type> to) {
  1968         return new Subst(from, to).subst(t);
  1971     private class Subst extends UnaryVisitor<Type> {
  1972         List<Type> from;
  1973         List<Type> to;
  1975         public Subst(List<Type> from, List<Type> to) {
  1976             int fromLength = from.length();
  1977             int toLength = to.length();
  1978             while (fromLength > toLength) {
  1979                 fromLength--;
  1980                 from = from.tail;
  1982             while (fromLength < toLength) {
  1983                 toLength--;
  1984                 to = to.tail;
  1986             this.from = from;
  1987             this.to = to;
  1990         Type subst(Type t) {
  1991             if (from.tail == null)
  1992                 return t;
  1993             else
  1994                 return visit(t);
  1997         List<Type> subst(List<Type> ts) {
  1998             if (from.tail == null)
  1999                 return ts;
  2000             boolean wild = false;
  2001             if (ts.nonEmpty() && from.nonEmpty()) {
  2002                 Type head1 = subst(ts.head);
  2003                 List<Type> tail1 = subst(ts.tail);
  2004                 if (head1 != ts.head || tail1 != ts.tail)
  2005                     return tail1.prepend(head1);
  2007             return ts;
  2010         public Type visitType(Type t, Void ignored) {
  2011             return t;
  2014         @Override
  2015         public Type visitMethodType(MethodType t, Void ignored) {
  2016             List<Type> argtypes = subst(t.argtypes);
  2017             Type restype = subst(t.restype);
  2018             List<Type> thrown = subst(t.thrown);
  2019             if (argtypes == t.argtypes &&
  2020                 restype == t.restype &&
  2021                 thrown == t.thrown)
  2022                 return t;
  2023             else
  2024                 return new MethodType(argtypes, restype, thrown, t.tsym);
  2027         @Override
  2028         public Type visitTypeVar(TypeVar t, Void ignored) {
  2029             for (List<Type> from = this.from, to = this.to;
  2030                  from.nonEmpty();
  2031                  from = from.tail, to = to.tail) {
  2032                 if (t == from.head) {
  2033                     return to.head.withTypeVar(t);
  2036             return t;
  2039         @Override
  2040         public Type visitClassType(ClassType t, Void ignored) {
  2041             if (!t.isCompound()) {
  2042                 List<Type> typarams = t.getTypeArguments();
  2043                 List<Type> typarams1 = subst(typarams);
  2044                 Type outer = t.getEnclosingType();
  2045                 Type outer1 = subst(outer);
  2046                 if (typarams1 == typarams && outer1 == outer)
  2047                     return t;
  2048                 else
  2049                     return new ClassType(outer1, typarams1, t.tsym);
  2050             } else {
  2051                 Type st = subst(supertype(t));
  2052                 List<Type> is = upperBounds(subst(interfaces(t)));
  2053                 if (st == supertype(t) && is == interfaces(t))
  2054                     return t;
  2055                 else
  2056                     return makeCompoundType(is.prepend(st));
  2060         @Override
  2061         public Type visitWildcardType(WildcardType t, Void ignored) {
  2062             Type bound = t.type;
  2063             if (t.kind != BoundKind.UNBOUND)
  2064                 bound = subst(bound);
  2065             if (bound == t.type) {
  2066                 return t;
  2067             } else {
  2068                 if (t.isExtendsBound() && bound.isExtendsBound())
  2069                     bound = upperBound(bound);
  2070                 return new WildcardType(bound, t.kind, syms.boundClass, t.bound);
  2074         @Override
  2075         public Type visitArrayType(ArrayType t, Void ignored) {
  2076             Type elemtype = subst(t.elemtype);
  2077             if (elemtype == t.elemtype)
  2078                 return t;
  2079             else
  2080                 return new ArrayType(upperBound(elemtype), t.tsym);
  2083         @Override
  2084         public Type visitForAll(ForAll t, Void ignored) {
  2085             List<Type> tvars1 = substBounds(t.tvars, from, to);
  2086             Type qtype1 = subst(t.qtype);
  2087             if (tvars1 == t.tvars && qtype1 == t.qtype) {
  2088                 return t;
  2089             } else if (tvars1 == t.tvars) {
  2090                 return new ForAll(tvars1, qtype1);
  2091             } else {
  2092                 return new ForAll(tvars1, Types.this.subst(qtype1, t.tvars, tvars1));
  2096         @Override
  2097         public Type visitErrorType(ErrorType t, Void ignored) {
  2098             return t;
  2102     public List<Type> substBounds(List<Type> tvars,
  2103                                   List<Type> from,
  2104                                   List<Type> to) {
  2105         if (tvars.isEmpty())
  2106             return tvars;
  2107         if (tvars.tail.isEmpty())
  2108             // fast common case
  2109             return List.<Type>of(substBound((TypeVar)tvars.head, from, to));
  2110         ListBuffer<Type> newBoundsBuf = lb();
  2111         boolean changed = false;
  2112         // calculate new bounds
  2113         for (Type t : tvars) {
  2114             TypeVar tv = (TypeVar) t;
  2115             Type bound = subst(tv.bound, from, to);
  2116             if (bound != tv.bound)
  2117                 changed = true;
  2118             newBoundsBuf.append(bound);
  2120         if (!changed)
  2121             return tvars;
  2122         ListBuffer<Type> newTvars = lb();
  2123         // create new type variables without bounds
  2124         for (Type t : tvars) {
  2125             newTvars.append(new TypeVar(t.tsym, null, syms.botType));
  2127         // the new bounds should use the new type variables in place
  2128         // of the old
  2129         List<Type> newBounds = newBoundsBuf.toList();
  2130         from = tvars;
  2131         to = newTvars.toList();
  2132         for (; !newBounds.isEmpty(); newBounds = newBounds.tail) {
  2133             newBounds.head = subst(newBounds.head, from, to);
  2135         newBounds = newBoundsBuf.toList();
  2136         // set the bounds of new type variables to the new bounds
  2137         for (Type t : newTvars.toList()) {
  2138             TypeVar tv = (TypeVar) t;
  2139             tv.bound = newBounds.head;
  2140             newBounds = newBounds.tail;
  2142         return newTvars.toList();
  2145     public TypeVar substBound(TypeVar t, List<Type> from, List<Type> to) {
  2146         Type bound1 = subst(t.bound, from, to);
  2147         if (bound1 == t.bound)
  2148             return t;
  2149         else
  2150             return new TypeVar(t.tsym, bound1, syms.botType);
  2152     // </editor-fold>
  2154     // <editor-fold defaultstate="collapsed" desc="hasSameBounds">
  2155     /**
  2156      * Does t have the same bounds for quantified variables as s?
  2157      */
  2158     boolean hasSameBounds(ForAll t, ForAll s) {
  2159         List<Type> l1 = t.tvars;
  2160         List<Type> l2 = s.tvars;
  2161         while (l1.nonEmpty() && l2.nonEmpty() &&
  2162                isSameType(l1.head.getUpperBound(),
  2163                           subst(l2.head.getUpperBound(),
  2164                                 s.tvars,
  2165                                 t.tvars))) {
  2166             l1 = l1.tail;
  2167             l2 = l2.tail;
  2169         return l1.isEmpty() && l2.isEmpty();
  2171     // </editor-fold>
  2173     // <editor-fold defaultstate="collapsed" desc="newInstances">
  2174     /** Create new vector of type variables from list of variables
  2175      *  changing all recursive bounds from old to new list.
  2176      */
  2177     public List<Type> newInstances(List<Type> tvars) {
  2178         List<Type> tvars1 = Type.map(tvars, newInstanceFun);
  2179         for (List<Type> l = tvars1; l.nonEmpty(); l = l.tail) {
  2180             TypeVar tv = (TypeVar) l.head;
  2181             tv.bound = subst(tv.bound, tvars, tvars1);
  2183         return tvars1;
  2185     static private Mapping newInstanceFun = new Mapping("newInstanceFun") {
  2186             public Type apply(Type t) { return new TypeVar(t.tsym, t.getUpperBound(), t.getLowerBound()); }
  2187         };
  2188     // </editor-fold>
  2190     // <editor-fold defaultstate="collapsed" desc="createErrorType">
  2191     public Type createErrorType(Type originalType) {
  2192         return new ErrorType(originalType, syms.errSymbol);
  2195     public Type createErrorType(ClassSymbol c, Type originalType) {
  2196         return new ErrorType(c, originalType);
  2199     public Type createErrorType(Name name, TypeSymbol container, Type originalType) {
  2200         return new ErrorType(name, container, originalType);
  2202     // </editor-fold>
  2204     // <editor-fold defaultstate="collapsed" desc="rank">
  2205     /**
  2206      * The rank of a class is the length of the longest path between
  2207      * the class and java.lang.Object in the class inheritance
  2208      * graph. Undefined for all but reference types.
  2209      */
  2210     public int rank(Type t) {
  2211         switch(t.tag) {
  2212         case CLASS: {
  2213             ClassType cls = (ClassType)t;
  2214             if (cls.rank_field < 0) {
  2215                 Name fullname = cls.tsym.getQualifiedName();
  2216                 if (fullname == names.java_lang_Object)
  2217                     cls.rank_field = 0;
  2218                 else {
  2219                     int r = rank(supertype(cls));
  2220                     for (List<Type> l = interfaces(cls);
  2221                          l.nonEmpty();
  2222                          l = l.tail) {
  2223                         if (rank(l.head) > r)
  2224                             r = rank(l.head);
  2226                     cls.rank_field = r + 1;
  2229             return cls.rank_field;
  2231         case TYPEVAR: {
  2232             TypeVar tvar = (TypeVar)t;
  2233             if (tvar.rank_field < 0) {
  2234                 int r = rank(supertype(tvar));
  2235                 for (List<Type> l = interfaces(tvar);
  2236                      l.nonEmpty();
  2237                      l = l.tail) {
  2238                     if (rank(l.head) > r) r = rank(l.head);
  2240                 tvar.rank_field = r + 1;
  2242             return tvar.rank_field;
  2244         case ERROR:
  2245             return 0;
  2246         default:
  2247             throw new AssertionError();
  2250     // </editor-fold>
  2252     // <editor-fold defaultstate="collapsed" desc="toString">
  2253     /**
  2254      * This toString is slightly more descriptive than the one on Type.
  2255      */
  2256     public String toString(Type t) {
  2257         if (t.tag == FORALL) {
  2258             ForAll forAll = (ForAll)t;
  2259             return typaramsString(forAll.tvars) + forAll.qtype;
  2261         return "" + t;
  2263     // where
  2264         private String typaramsString(List<Type> tvars) {
  2265             StringBuffer s = new StringBuffer();
  2266             s.append('<');
  2267             boolean first = true;
  2268             for (Type t : tvars) {
  2269                 if (!first) s.append(", ");
  2270                 first = false;
  2271                 appendTyparamString(((TypeVar)t), s);
  2273             s.append('>');
  2274             return s.toString();
  2276         private void appendTyparamString(TypeVar t, StringBuffer buf) {
  2277             buf.append(t);
  2278             if (t.bound == null ||
  2279                 t.bound.tsym.getQualifiedName() == names.java_lang_Object)
  2280                 return;
  2281             buf.append(" extends "); // Java syntax; no need for i18n
  2282             Type bound = t.bound;
  2283             if (!bound.isCompound()) {
  2284                 buf.append(bound);
  2285             } else if ((erasure(t).tsym.flags() & INTERFACE) == 0) {
  2286                 buf.append(supertype(t));
  2287                 for (Type intf : interfaces(t)) {
  2288                     buf.append('&');
  2289                     buf.append(intf);
  2291             } else {
  2292                 // No superclass was given in bounds.
  2293                 // In this case, supertype is Object, erasure is first interface.
  2294                 boolean first = true;
  2295                 for (Type intf : interfaces(t)) {
  2296                     if (!first) buf.append('&');
  2297                     first = false;
  2298                     buf.append(intf);
  2302     // </editor-fold>
  2304     // <editor-fold defaultstate="collapsed" desc="Determining least upper bounds of types">
  2305     /**
  2306      * A cache for closures.
  2308      * <p>A closure is a list of all the supertypes and interfaces of
  2309      * a class or interface type, ordered by ClassSymbol.precedes
  2310      * (that is, subclasses come first, arbitrary but fixed
  2311      * otherwise).
  2312      */
  2313     private Map<Type,List<Type>> closureCache = new HashMap<Type,List<Type>>();
  2315     /**
  2316      * Returns the closure of a class or interface type.
  2317      */
  2318     public List<Type> closure(Type t) {
  2319         List<Type> cl = closureCache.get(t);
  2320         if (cl == null) {
  2321             Type st = supertype(t);
  2322             if (!t.isCompound()) {
  2323                 if (st.tag == CLASS) {
  2324                     cl = insert(closure(st), t);
  2325                 } else if (st.tag == TYPEVAR) {
  2326                     cl = closure(st).prepend(t);
  2327                 } else {
  2328                     cl = List.of(t);
  2330             } else {
  2331                 cl = closure(supertype(t));
  2333             for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail)
  2334                 cl = union(cl, closure(l.head));
  2335             closureCache.put(t, cl);
  2337         return cl;
  2340     /**
  2341      * Insert a type in a closure
  2342      */
  2343     public List<Type> insert(List<Type> cl, Type t) {
  2344         if (cl.isEmpty() || t.tsym.precedes(cl.head.tsym, this)) {
  2345             return cl.prepend(t);
  2346         } else if (cl.head.tsym.precedes(t.tsym, this)) {
  2347             return insert(cl.tail, t).prepend(cl.head);
  2348         } else {
  2349             return cl;
  2353     /**
  2354      * Form the union of two closures
  2355      */
  2356     public List<Type> union(List<Type> cl1, List<Type> cl2) {
  2357         if (cl1.isEmpty()) {
  2358             return cl2;
  2359         } else if (cl2.isEmpty()) {
  2360             return cl1;
  2361         } else if (cl1.head.tsym.precedes(cl2.head.tsym, this)) {
  2362             return union(cl1.tail, cl2).prepend(cl1.head);
  2363         } else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) {
  2364             return union(cl1, cl2.tail).prepend(cl2.head);
  2365         } else {
  2366             return union(cl1.tail, cl2.tail).prepend(cl1.head);
  2370     /**
  2371      * Intersect two closures
  2372      */
  2373     public List<Type> intersect(List<Type> cl1, List<Type> cl2) {
  2374         if (cl1 == cl2)
  2375             return cl1;
  2376         if (cl1.isEmpty() || cl2.isEmpty())
  2377             return List.nil();
  2378         if (cl1.head.tsym.precedes(cl2.head.tsym, this))
  2379             return intersect(cl1.tail, cl2);
  2380         if (cl2.head.tsym.precedes(cl1.head.tsym, this))
  2381             return intersect(cl1, cl2.tail);
  2382         if (isSameType(cl1.head, cl2.head))
  2383             return intersect(cl1.tail, cl2.tail).prepend(cl1.head);
  2384         if (cl1.head.tsym == cl2.head.tsym &&
  2385             cl1.head.tag == CLASS && cl2.head.tag == CLASS) {
  2386             if (cl1.head.isParameterized() && cl2.head.isParameterized()) {
  2387                 Type merge = merge(cl1.head,cl2.head);
  2388                 return intersect(cl1.tail, cl2.tail).prepend(merge);
  2390             if (cl1.head.isRaw() || cl2.head.isRaw())
  2391                 return intersect(cl1.tail, cl2.tail).prepend(erasure(cl1.head));
  2393         return intersect(cl1.tail, cl2.tail);
  2395     // where
  2396         class TypePair {
  2397             final Type t1;
  2398             final Type t2;
  2399             TypePair(Type t1, Type t2) {
  2400                 this.t1 = t1;
  2401                 this.t2 = t2;
  2403             @Override
  2404             public int hashCode() {
  2405                 return 127 * Types.this.hashCode(t1) + Types.this.hashCode(t2);
  2407             @Override
  2408             public boolean equals(Object obj) {
  2409                 if (!(obj instanceof TypePair))
  2410                     return false;
  2411                 TypePair typePair = (TypePair)obj;
  2412                 return isSameType(t1, typePair.t1)
  2413                     && isSameType(t2, typePair.t2);
  2416         Set<TypePair> mergeCache = new HashSet<TypePair>();
  2417         private Type merge(Type c1, Type c2) {
  2418             ClassType class1 = (ClassType) c1;
  2419             List<Type> act1 = class1.getTypeArguments();
  2420             ClassType class2 = (ClassType) c2;
  2421             List<Type> act2 = class2.getTypeArguments();
  2422             ListBuffer<Type> merged = new ListBuffer<Type>();
  2423             List<Type> typarams = class1.tsym.type.getTypeArguments();
  2425             while (act1.nonEmpty() && act2.nonEmpty() && typarams.nonEmpty()) {
  2426                 if (containsType(act1.head, act2.head)) {
  2427                     merged.append(act1.head);
  2428                 } else if (containsType(act2.head, act1.head)) {
  2429                     merged.append(act2.head);
  2430                 } else {
  2431                     TypePair pair = new TypePair(c1, c2);
  2432                     Type m;
  2433                     if (mergeCache.add(pair)) {
  2434                         m = new WildcardType(lub(upperBound(act1.head),
  2435                                                  upperBound(act2.head)),
  2436                                              BoundKind.EXTENDS,
  2437                                              syms.boundClass);
  2438                         mergeCache.remove(pair);
  2439                     } else {
  2440                         m = new WildcardType(syms.objectType,
  2441                                              BoundKind.UNBOUND,
  2442                                              syms.boundClass);
  2444                     merged.append(m.withTypeVar(typarams.head));
  2446                 act1 = act1.tail;
  2447                 act2 = act2.tail;
  2448                 typarams = typarams.tail;
  2450             assert(act1.isEmpty() && act2.isEmpty() && typarams.isEmpty());
  2451             return new ClassType(class1.getEnclosingType(), merged.toList(), class1.tsym);
  2454     /**
  2455      * Return the minimum type of a closure, a compound type if no
  2456      * unique minimum exists.
  2457      */
  2458     private Type compoundMin(List<Type> cl) {
  2459         if (cl.isEmpty()) return syms.objectType;
  2460         List<Type> compound = closureMin(cl);
  2461         if (compound.isEmpty())
  2462             return null;
  2463         else if (compound.tail.isEmpty())
  2464             return compound.head;
  2465         else
  2466             return makeCompoundType(compound);
  2469     /**
  2470      * Return the minimum types of a closure, suitable for computing
  2471      * compoundMin or glb.
  2472      */
  2473     private List<Type> closureMin(List<Type> cl) {
  2474         ListBuffer<Type> classes = lb();
  2475         ListBuffer<Type> interfaces = lb();
  2476         while (!cl.isEmpty()) {
  2477             Type current = cl.head;
  2478             if (current.isInterface())
  2479                 interfaces.append(current);
  2480             else
  2481                 classes.append(current);
  2482             ListBuffer<Type> candidates = lb();
  2483             for (Type t : cl.tail) {
  2484                 if (!isSubtypeNoCapture(current, t))
  2485                     candidates.append(t);
  2487             cl = candidates.toList();
  2489         return classes.appendList(interfaces).toList();
  2492     /**
  2493      * Return the least upper bound of pair of types.  if the lub does
  2494      * not exist return null.
  2495      */
  2496     public Type lub(Type t1, Type t2) {
  2497         return lub(List.of(t1, t2));
  2500     /**
  2501      * Return the least upper bound (lub) of set of types.  If the lub
  2502      * does not exist return the type of null (bottom).
  2503      */
  2504     public Type lub(List<Type> ts) {
  2505         final int ARRAY_BOUND = 1;
  2506         final int CLASS_BOUND = 2;
  2507         int boundkind = 0;
  2508         for (Type t : ts) {
  2509             switch (t.tag) {
  2510             case CLASS:
  2511                 boundkind |= CLASS_BOUND;
  2512                 break;
  2513             case ARRAY:
  2514                 boundkind |= ARRAY_BOUND;
  2515                 break;
  2516             case  TYPEVAR:
  2517                 do {
  2518                     t = t.getUpperBound();
  2519                 } while (t.tag == TYPEVAR);
  2520                 if (t.tag == ARRAY) {
  2521                     boundkind |= ARRAY_BOUND;
  2522                 } else {
  2523                     boundkind |= CLASS_BOUND;
  2525                 break;
  2526             default:
  2527                 if (t.isPrimitive())
  2528                     return syms.errType;
  2531         switch (boundkind) {
  2532         case 0:
  2533             return syms.botType;
  2535         case ARRAY_BOUND:
  2536             // calculate lub(A[], B[])
  2537             List<Type> elements = Type.map(ts, elemTypeFun);
  2538             for (Type t : elements) {
  2539                 if (t.isPrimitive()) {
  2540                     // if a primitive type is found, then return
  2541                     // arraySuperType unless all the types are the
  2542                     // same
  2543                     Type first = ts.head;
  2544                     for (Type s : ts.tail) {
  2545                         if (!isSameType(first, s)) {
  2546                              // lub(int[], B[]) is Cloneable & Serializable
  2547                             return arraySuperType();
  2550                     // all the array types are the same, return one
  2551                     // lub(int[], int[]) is int[]
  2552                     return first;
  2555             // lub(A[], B[]) is lub(A, B)[]
  2556             return new ArrayType(lub(elements), syms.arrayClass);
  2558         case CLASS_BOUND:
  2559             // calculate lub(A, B)
  2560             while (ts.head.tag != CLASS && ts.head.tag != TYPEVAR)
  2561                 ts = ts.tail;
  2562             assert !ts.isEmpty();
  2563             List<Type> cl = closure(ts.head);
  2564             for (Type t : ts.tail) {
  2565                 if (t.tag == CLASS || t.tag == TYPEVAR)
  2566                     cl = intersect(cl, closure(t));
  2568             return compoundMin(cl);
  2570         default:
  2571             // calculate lub(A, B[])
  2572             List<Type> classes = List.of(arraySuperType());
  2573             for (Type t : ts) {
  2574                 if (t.tag != ARRAY) // Filter out any arrays
  2575                     classes = classes.prepend(t);
  2577             // lub(A, B[]) is lub(A, arraySuperType)
  2578             return lub(classes);
  2581     // where
  2582         private Type arraySuperType = null;
  2583         private Type arraySuperType() {
  2584             // initialized lazily to avoid problems during compiler startup
  2585             if (arraySuperType == null) {
  2586                 synchronized (this) {
  2587                     if (arraySuperType == null) {
  2588                         // JLS 10.8: all arrays implement Cloneable and Serializable.
  2589                         arraySuperType = makeCompoundType(List.of(syms.serializableType,
  2590                                                                   syms.cloneableType),
  2591                                                           syms.objectType);
  2595             return arraySuperType;
  2597     // </editor-fold>
  2599     // <editor-fold defaultstate="collapsed" desc="Greatest lower bound">
  2600     public Type glb(Type t, Type s) {
  2601         if (s == null)
  2602             return t;
  2603         else if (isSubtypeNoCapture(t, s))
  2604             return t;
  2605         else if (isSubtypeNoCapture(s, t))
  2606             return s;
  2608         List<Type> closure = union(closure(t), closure(s));
  2609         List<Type> bounds = closureMin(closure);
  2611         if (bounds.isEmpty()) {             // length == 0
  2612             return syms.objectType;
  2613         } else if (bounds.tail.isEmpty()) { // length == 1
  2614             return bounds.head;
  2615         } else {                            // length > 1
  2616             int classCount = 0;
  2617             for (Type bound : bounds)
  2618                 if (!bound.isInterface())
  2619                     classCount++;
  2620             if (classCount > 1)
  2621                 return createErrorType(t);
  2623         return makeCompoundType(bounds);
  2625     // </editor-fold>
  2627     // <editor-fold defaultstate="collapsed" desc="hashCode">
  2628     /**
  2629      * Compute a hash code on a type.
  2630      */
  2631     public static int hashCode(Type t) {
  2632         return hashCode.visit(t);
  2634     // where
  2635         private static final UnaryVisitor<Integer> hashCode = new UnaryVisitor<Integer>() {
  2637             public Integer visitType(Type t, Void ignored) {
  2638                 return t.tag;
  2641             @Override
  2642             public Integer visitClassType(ClassType t, Void ignored) {
  2643                 int result = visit(t.getEnclosingType());
  2644                 result *= 127;
  2645                 result += t.tsym.flatName().hashCode();
  2646                 for (Type s : t.getTypeArguments()) {
  2647                     result *= 127;
  2648                     result += visit(s);
  2650                 return result;
  2653             @Override
  2654             public Integer visitWildcardType(WildcardType t, Void ignored) {
  2655                 int result = t.kind.hashCode();
  2656                 if (t.type != null) {
  2657                     result *= 127;
  2658                     result += visit(t.type);
  2660                 return result;
  2663             @Override
  2664             public Integer visitArrayType(ArrayType t, Void ignored) {
  2665                 return visit(t.elemtype) + 12;
  2668             @Override
  2669             public Integer visitTypeVar(TypeVar t, Void ignored) {
  2670                 return System.identityHashCode(t.tsym);
  2673             @Override
  2674             public Integer visitUndetVar(UndetVar t, Void ignored) {
  2675                 return System.identityHashCode(t);
  2678             @Override
  2679             public Integer visitErrorType(ErrorType t, Void ignored) {
  2680                 return 0;
  2682         };
  2683     // </editor-fold>
  2685     // <editor-fold defaultstate="collapsed" desc="Return-Type-Substitutable">
  2686     /**
  2687      * Does t have a result that is a subtype of the result type of s,
  2688      * suitable for covariant returns?  It is assumed that both types
  2689      * are (possibly polymorphic) method types.  Monomorphic method
  2690      * types are handled in the obvious way.  Polymorphic method types
  2691      * require renaming all type variables of one to corresponding
  2692      * type variables in the other, where correspondence is by
  2693      * position in the type parameter list. */
  2694     public boolean resultSubtype(Type t, Type s, Warner warner) {
  2695         List<Type> tvars = t.getTypeArguments();
  2696         List<Type> svars = s.getTypeArguments();
  2697         Type tres = t.getReturnType();
  2698         Type sres = subst(s.getReturnType(), svars, tvars);
  2699         return covariantReturnType(tres, sres, warner);
  2702     /**
  2703      * Return-Type-Substitutable.
  2704      * @see <a href="http://java.sun.com/docs/books/jls/">The Java
  2705      * Language Specification, Third Ed. (8.4.5)</a>
  2706      */
  2707     public boolean returnTypeSubstitutable(Type r1, Type r2) {
  2708         if (hasSameArgs(r1, r2))
  2709             return resultSubtype(r1, r2, Warner.noWarnings);
  2710         else
  2711             return covariantReturnType(r1.getReturnType(),
  2712                                        erasure(r2.getReturnType()),
  2713                                        Warner.noWarnings);
  2716     public boolean returnTypeSubstitutable(Type r1,
  2717                                            Type r2, Type r2res,
  2718                                            Warner warner) {
  2719         if (isSameType(r1.getReturnType(), r2res))
  2720             return true;
  2721         if (r1.getReturnType().isPrimitive() || r2res.isPrimitive())
  2722             return false;
  2724         if (hasSameArgs(r1, r2))
  2725             return covariantReturnType(r1.getReturnType(), r2res, warner);
  2726         if (!source.allowCovariantReturns())
  2727             return false;
  2728         if (isSubtypeUnchecked(r1.getReturnType(), r2res, warner))
  2729             return true;
  2730         if (!isSubtype(r1.getReturnType(), erasure(r2res)))
  2731             return false;
  2732         warner.warnUnchecked();
  2733         return true;
  2736     /**
  2737      * Is t an appropriate return type in an overrider for a
  2738      * method that returns s?
  2739      */
  2740     public boolean covariantReturnType(Type t, Type s, Warner warner) {
  2741         return
  2742             isSameType(t, s) ||
  2743             source.allowCovariantReturns() &&
  2744             !t.isPrimitive() &&
  2745             !s.isPrimitive() &&
  2746             isAssignable(t, s, warner);
  2748     // </editor-fold>
  2750     // <editor-fold defaultstate="collapsed" desc="Box/unbox support">
  2751     /**
  2752      * Return the class that boxes the given primitive.
  2753      */
  2754     public ClassSymbol boxedClass(Type t) {
  2755         return reader.enterClass(syms.boxedName[t.tag]);
  2758     /**
  2759      * Return the primitive type corresponding to a boxed type.
  2760      */
  2761     public Type unboxedType(Type t) {
  2762         if (allowBoxing) {
  2763             for (int i=0; i<syms.boxedName.length; i++) {
  2764                 Name box = syms.boxedName[i];
  2765                 if (box != null &&
  2766                     asSuper(t, reader.enterClass(box)) != null)
  2767                     return syms.typeOfTag[i];
  2770         return Type.noType;
  2772     // </editor-fold>
  2774     // <editor-fold defaultstate="collapsed" desc="Capture conversion">
  2775     /*
  2776      * JLS 3rd Ed. 5.1.10 Capture Conversion:
  2778      * Let G name a generic type declaration with n formal type
  2779      * parameters A1 ... An with corresponding bounds U1 ... Un. There
  2780      * exists a capture conversion from G<T1 ... Tn> to G<S1 ... Sn>,
  2781      * where, for 1 <= i <= n:
  2783      * + If Ti is a wildcard type argument (4.5.1) of the form ? then
  2784      *   Si is a fresh type variable whose upper bound is
  2785      *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is the null
  2786      *   type.
  2788      * + If Ti is a wildcard type argument of the form ? extends Bi,
  2789      *   then Si is a fresh type variable whose upper bound is
  2790      *   glb(Bi, Ui[A1 := S1, ..., An := Sn]) and whose lower bound is
  2791      *   the null type, where glb(V1,... ,Vm) is V1 & ... & Vm. It is
  2792      *   a compile-time error if for any two classes (not interfaces)
  2793      *   Vi and Vj,Vi is not a subclass of Vj or vice versa.
  2795      * + If Ti is a wildcard type argument of the form ? super Bi,
  2796      *   then Si is a fresh type variable whose upper bound is
  2797      *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is Bi.
  2799      * + Otherwise, Si = Ti.
  2801      * Capture conversion on any type other than a parameterized type
  2802      * (4.5) acts as an identity conversion (5.1.1). Capture
  2803      * conversions never require a special action at run time and
  2804      * therefore never throw an exception at run time.
  2806      * Capture conversion is not applied recursively.
  2807      */
  2808     /**
  2809      * Capture conversion as specified by JLS 3rd Ed.
  2810      */
  2811     public Type capture(Type t) {
  2812         if (t.tag != CLASS)
  2813             return t;
  2814         ClassType cls = (ClassType)t;
  2815         if (cls.isRaw() || !cls.isParameterized())
  2816             return cls;
  2818         ClassType G = (ClassType)cls.asElement().asType();
  2819         List<Type> A = G.getTypeArguments();
  2820         List<Type> T = cls.getTypeArguments();
  2821         List<Type> S = freshTypeVariables(T);
  2823         List<Type> currentA = A;
  2824         List<Type> currentT = T;
  2825         List<Type> currentS = S;
  2826         boolean captured = false;
  2827         while (!currentA.isEmpty() &&
  2828                !currentT.isEmpty() &&
  2829                !currentS.isEmpty()) {
  2830             if (currentS.head != currentT.head) {
  2831                 captured = true;
  2832                 WildcardType Ti = (WildcardType)currentT.head;
  2833                 Type Ui = currentA.head.getUpperBound();
  2834                 CapturedType Si = (CapturedType)currentS.head;
  2835                 if (Ui == null)
  2836                     Ui = syms.objectType;
  2837                 switch (Ti.kind) {
  2838                 case UNBOUND:
  2839                     Si.bound = subst(Ui, A, S);
  2840                     Si.lower = syms.botType;
  2841                     break;
  2842                 case EXTENDS:
  2843                     Si.bound = glb(Ti.getExtendsBound(), subst(Ui, A, S));
  2844                     Si.lower = syms.botType;
  2845                     break;
  2846                 case SUPER:
  2847                     Si.bound = subst(Ui, A, S);
  2848                     Si.lower = Ti.getSuperBound();
  2849                     break;
  2851                 if (Si.bound == Si.lower)
  2852                     currentS.head = Si.bound;
  2854             currentA = currentA.tail;
  2855             currentT = currentT.tail;
  2856             currentS = currentS.tail;
  2858         if (!currentA.isEmpty() || !currentT.isEmpty() || !currentS.isEmpty())
  2859             return erasure(t); // some "rare" type involved
  2861         if (captured)
  2862             return new ClassType(cls.getEnclosingType(), S, cls.tsym);
  2863         else
  2864             return t;
  2866     // where
  2867         private List<Type> freshTypeVariables(List<Type> types) {
  2868             ListBuffer<Type> result = lb();
  2869             for (Type t : types) {
  2870                 if (t.tag == WILDCARD) {
  2871                     Type bound = ((WildcardType)t).getExtendsBound();
  2872                     if (bound == null)
  2873                         bound = syms.objectType;
  2874                     result.append(new CapturedType(capturedName,
  2875                                                    syms.noSymbol,
  2876                                                    bound,
  2877                                                    syms.botType,
  2878                                                    (WildcardType)t));
  2879                 } else {
  2880                     result.append(t);
  2883             return result.toList();
  2885     // </editor-fold>
  2887     // <editor-fold defaultstate="collapsed" desc="Internal utility methods">
  2888     private List<Type> upperBounds(List<Type> ss) {
  2889         if (ss.isEmpty()) return ss;
  2890         Type head = upperBound(ss.head);
  2891         List<Type> tail = upperBounds(ss.tail);
  2892         if (head != ss.head || tail != ss.tail)
  2893             return tail.prepend(head);
  2894         else
  2895             return ss;
  2898     private boolean sideCast(Type from, Type to, Warner warn) {
  2899         // We are casting from type $from$ to type $to$, which are
  2900         // non-final unrelated types.  This method
  2901         // tries to reject a cast by transferring type parameters
  2902         // from $to$ to $from$ by common superinterfaces.
  2903         boolean reverse = false;
  2904         Type target = to;
  2905         if ((to.tsym.flags() & INTERFACE) == 0) {
  2906             assert (from.tsym.flags() & INTERFACE) != 0;
  2907             reverse = true;
  2908             to = from;
  2909             from = target;
  2911         List<Type> commonSupers = superClosure(to, erasure(from));
  2912         boolean giveWarning = commonSupers.isEmpty();
  2913         // The arguments to the supers could be unified here to
  2914         // get a more accurate analysis
  2915         while (commonSupers.nonEmpty()) {
  2916             Type t1 = asSuper(from, commonSupers.head.tsym);
  2917             Type t2 = commonSupers.head; // same as asSuper(to, commonSupers.head.tsym);
  2918             if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
  2919                 return false;
  2920             giveWarning = giveWarning || (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2));
  2921             commonSupers = commonSupers.tail;
  2923         if (giveWarning && !isReifiable(to))
  2924             warn.warnUnchecked();
  2925         if (!source.allowCovariantReturns())
  2926             // reject if there is a common method signature with
  2927             // incompatible return types.
  2928             chk.checkCompatibleAbstracts(warn.pos(), from, to);
  2929         return true;
  2932     private boolean sideCastFinal(Type from, Type to, Warner warn) {
  2933         // We are casting from type $from$ to type $to$, which are
  2934         // unrelated types one of which is final and the other of
  2935         // which is an interface.  This method
  2936         // tries to reject a cast by transferring type parameters
  2937         // from the final class to the interface.
  2938         boolean reverse = false;
  2939         Type target = to;
  2940         if ((to.tsym.flags() & INTERFACE) == 0) {
  2941             assert (from.tsym.flags() & INTERFACE) != 0;
  2942             reverse = true;
  2943             to = from;
  2944             from = target;
  2946         assert (from.tsym.flags() & FINAL) != 0;
  2947         Type t1 = asSuper(from, to.tsym);
  2948         if (t1 == null) return false;
  2949         Type t2 = to;
  2950         if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
  2951             return false;
  2952         if (!source.allowCovariantReturns())
  2953             // reject if there is a common method signature with
  2954             // incompatible return types.
  2955             chk.checkCompatibleAbstracts(warn.pos(), from, to);
  2956         if (!isReifiable(target) &&
  2957             (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2)))
  2958             warn.warnUnchecked();
  2959         return true;
  2962     private boolean giveWarning(Type from, Type to) {
  2963         // To and from are (possibly different) parameterizations
  2964         // of the same class or interface
  2965         return to.isParameterized() && !containsType(to.getTypeArguments(), from.getTypeArguments());
  2968     private List<Type> superClosure(Type t, Type s) {
  2969         List<Type> cl = List.nil();
  2970         for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
  2971             if (isSubtype(s, erasure(l.head))) {
  2972                 cl = insert(cl, l.head);
  2973             } else {
  2974                 cl = union(cl, superClosure(l.head, s));
  2977         return cl;
  2980     private boolean containsTypeEquivalent(Type t, Type s) {
  2981         return
  2982             isSameType(t, s) || // shortcut
  2983             containsType(t, s) && containsType(s, t);
  2986     /**
  2987      * Adapt a type by computing a substitution which maps a source
  2988      * type to a target type.
  2990      * @param source    the source type
  2991      * @param target    the target type
  2992      * @param from      the type variables of the computed substitution
  2993      * @param to        the types of the computed substitution.
  2994      */
  2995     public void adapt(Type source,
  2996                        Type target,
  2997                        ListBuffer<Type> from,
  2998                        ListBuffer<Type> to) throws AdaptFailure {
  2999         Map<Symbol,Type> mapping = new HashMap<Symbol,Type>();
  3000         adaptRecursive(source, target, from, to, mapping);
  3001         List<Type> fromList = from.toList();
  3002         List<Type> toList = to.toList();
  3003         while (!fromList.isEmpty()) {
  3004             Type val = mapping.get(fromList.head.tsym);
  3005             if (toList.head != val)
  3006                 toList.head = val;
  3007             fromList = fromList.tail;
  3008             toList = toList.tail;
  3011     // where
  3012         private void adaptRecursive(Type source,
  3013                                     Type target,
  3014                                     ListBuffer<Type> from,
  3015                                     ListBuffer<Type> to,
  3016                                     Map<Symbol,Type> mapping) throws AdaptFailure {
  3017             if (source.tag == TYPEVAR) {
  3018                 // Check to see if there is
  3019                 // already a mapping for $source$, in which case
  3020                 // the old mapping will be merged with the new
  3021                 Type val = mapping.get(source.tsym);
  3022                 if (val != null) {
  3023                     if (val.isSuperBound() && target.isSuperBound()) {
  3024                         val = isSubtype(lowerBound(val), lowerBound(target))
  3025                             ? target : val;
  3026                     } else if (val.isExtendsBound() && target.isExtendsBound()) {
  3027                         val = isSubtype(upperBound(val), upperBound(target))
  3028                             ? val : target;
  3029                     } else if (!isSameType(val, target)) {
  3030                         throw new AdaptFailure();
  3032                 } else {
  3033                     val = target;
  3034                     from.append(source);
  3035                     to.append(target);
  3037                 mapping.put(source.tsym, val);
  3038             } else if (source.tag == target.tag) {
  3039                 switch (source.tag) {
  3040                     case CLASS:
  3041                         adapt(source.allparams(), target.allparams(),
  3042                               from, to, mapping);
  3043                         break;
  3044                     case ARRAY:
  3045                         adaptRecursive(elemtype(source), elemtype(target),
  3046                                        from, to, mapping);
  3047                         break;
  3048                     case WILDCARD:
  3049                         if (source.isExtendsBound()) {
  3050                             adaptRecursive(upperBound(source), upperBound(target),
  3051                                            from, to, mapping);
  3052                         } else if (source.isSuperBound()) {
  3053                             adaptRecursive(lowerBound(source), lowerBound(target),
  3054                                            from, to, mapping);
  3056                         break;
  3060         public static class AdaptFailure extends Exception {
  3061             static final long serialVersionUID = -7490231548272701566L;
  3064     /**
  3065      * Adapt a type by computing a substitution which maps a list of
  3066      * source types to a list of target types.
  3068      * @param source    the source type
  3069      * @param target    the target type
  3070      * @param from      the type variables of the computed substitution
  3071      * @param to        the types of the computed substitution.
  3072      */
  3073     private void adapt(List<Type> source,
  3074                        List<Type> target,
  3075                        ListBuffer<Type> from,
  3076                        ListBuffer<Type> to,
  3077                        Map<Symbol,Type> mapping) throws AdaptFailure {
  3078         if (source.length() == target.length()) {
  3079             while (source.nonEmpty()) {
  3080                 adaptRecursive(source.head, target.head, from, to, mapping);
  3081                 source = source.tail;
  3082                 target = target.tail;
  3087     private void adaptSelf(Type t,
  3088                            ListBuffer<Type> from,
  3089                            ListBuffer<Type> to) {
  3090         try {
  3091             //if (t.tsym.type != t)
  3092                 adapt(t.tsym.type, t, from, to);
  3093         } catch (AdaptFailure ex) {
  3094             // Adapt should never fail calculating a mapping from
  3095             // t.tsym.type to t as there can be no merge problem.
  3096             throw new AssertionError(ex);
  3100     /**
  3101      * Rewrite all type variables (universal quantifiers) in the given
  3102      * type to wildcards (existential quantifiers).  This is used to
  3103      * determine if a cast is allowed.  For example, if high is true
  3104      * and {@code T <: Number}, then {@code List<T>} is rewritten to
  3105      * {@code List<?  extends Number>}.  Since {@code List<Integer> <:
  3106      * List<? extends Number>} a {@code List<T>} can be cast to {@code
  3107      * List<Integer>} with a warning.
  3108      * @param t a type
  3109      * @param high if true return an upper bound; otherwise a lower
  3110      * bound
  3111      * @param rewriteTypeVars only rewrite captured wildcards if false;
  3112      * otherwise rewrite all type variables
  3113      * @return the type rewritten with wildcards (existential
  3114      * quantifiers) only
  3115      */
  3116     private Type rewriteQuantifiers(Type t, boolean high, boolean rewriteTypeVars) {
  3117         ListBuffer<Type> from = new ListBuffer<Type>();
  3118         ListBuffer<Type> to = new ListBuffer<Type>();
  3119         adaptSelf(t, from, to);
  3120         ListBuffer<Type> rewritten = new ListBuffer<Type>();
  3121         List<Type> formals = from.toList();
  3122         boolean changed = false;
  3123         for (Type arg : to.toList()) {
  3124             Type bound;
  3125             if (rewriteTypeVars && arg.tag == TYPEVAR) {
  3126                 TypeVar tv = (TypeVar)arg;
  3127                 bound = high ? tv.bound : syms.botType;
  3128             } else {
  3129                 bound = high ? upperBound(arg) : lowerBound(arg);
  3131             Type newarg = bound;
  3132             if (arg != bound) {
  3133                 changed = true;
  3134                 newarg = high ? makeExtendsWildcard(bound, (TypeVar)formals.head)
  3135                               : makeSuperWildcard(bound, (TypeVar)formals.head);
  3137             rewritten.append(newarg);
  3138             formals = formals.tail;
  3140         if (changed)
  3141             return subst(t.tsym.type, from.toList(), rewritten.toList());
  3142         else
  3143             return t;
  3146     /**
  3147      * Create a wildcard with the given upper (extends) bound; create
  3148      * an unbounded wildcard if bound is Object.
  3150      * @param bound the upper bound
  3151      * @param formal the formal type parameter that will be
  3152      * substituted by the wildcard
  3153      */
  3154     private WildcardType makeExtendsWildcard(Type bound, TypeVar formal) {
  3155         if (bound == syms.objectType) {
  3156             return new WildcardType(syms.objectType,
  3157                                     BoundKind.UNBOUND,
  3158                                     syms.boundClass,
  3159                                     formal);
  3160         } else {
  3161             return new WildcardType(bound,
  3162                                     BoundKind.EXTENDS,
  3163                                     syms.boundClass,
  3164                                     formal);
  3168     /**
  3169      * Create a wildcard with the given lower (super) bound; create an
  3170      * unbounded wildcard if bound is bottom (type of {@code null}).
  3172      * @param bound the lower bound
  3173      * @param formal the formal type parameter that will be
  3174      * substituted by the wildcard
  3175      */
  3176     private WildcardType makeSuperWildcard(Type bound, TypeVar formal) {
  3177         if (bound.tag == BOT) {
  3178             return new WildcardType(syms.objectType,
  3179                                     BoundKind.UNBOUND,
  3180                                     syms.boundClass,
  3181                                     formal);
  3182         } else {
  3183             return new WildcardType(bound,
  3184                                     BoundKind.SUPER,
  3185                                     syms.boundClass,
  3186                                     formal);
  3190     /**
  3191      * A wrapper for a type that allows use in sets.
  3192      */
  3193     class SingletonType {
  3194         final Type t;
  3195         SingletonType(Type t) {
  3196             this.t = t;
  3198         public int hashCode() {
  3199             return Types.this.hashCode(t);
  3201         public boolean equals(Object obj) {
  3202             return (obj instanceof SingletonType) &&
  3203                 isSameType(t, ((SingletonType)obj).t);
  3205         public String toString() {
  3206             return t.toString();
  3209     // </editor-fold>
  3211     // <editor-fold defaultstate="collapsed" desc="Visitors">
  3212     /**
  3213      * A default visitor for types.  All visitor methods except
  3214      * visitType are implemented by delegating to visitType.  Concrete
  3215      * subclasses must provide an implementation of visitType and can
  3216      * override other methods as needed.
  3218      * @param <R> the return type of the operation implemented by this
  3219      * visitor; use Void if no return type is needed.
  3220      * @param <S> the type of the second argument (the first being the
  3221      * type itself) of the operation implemented by this visitor; use
  3222      * Void if a second argument is not needed.
  3223      */
  3224     public static abstract class DefaultTypeVisitor<R,S> implements Type.Visitor<R,S> {
  3225         final public R visit(Type t, S s)               { return t.accept(this, s); }
  3226         public R visitClassType(ClassType t, S s)       { return visitType(t, s); }
  3227         public R visitWildcardType(WildcardType t, S s) { return visitType(t, s); }
  3228         public R visitArrayType(ArrayType t, S s)       { return visitType(t, s); }
  3229         public R visitMethodType(MethodType t, S s)     { return visitType(t, s); }
  3230         public R visitPackageType(PackageType t, S s)   { return visitType(t, s); }
  3231         public R visitTypeVar(TypeVar t, S s)           { return visitType(t, s); }
  3232         public R visitCapturedType(CapturedType t, S s) { return visitType(t, s); }
  3233         public R visitForAll(ForAll t, S s)             { return visitType(t, s); }
  3234         public R visitUndetVar(UndetVar t, S s)         { return visitType(t, s); }
  3235         public R visitErrorType(ErrorType t, S s)       { return visitType(t, s); }
  3238     /**
  3239      * A <em>simple</em> visitor for types.  This visitor is simple as
  3240      * captured wildcards, for-all types (generic methods), and
  3241      * undetermined type variables (part of inference) are hidden.
  3242      * Captured wildcards are hidden by treating them as type
  3243      * variables and the rest are hidden by visiting their qtypes.
  3245      * @param <R> the return type of the operation implemented by this
  3246      * visitor; use Void if no return type is needed.
  3247      * @param <S> the type of the second argument (the first being the
  3248      * type itself) of the operation implemented by this visitor; use
  3249      * Void if a second argument is not needed.
  3250      */
  3251     public static abstract class SimpleVisitor<R,S> extends DefaultTypeVisitor<R,S> {
  3252         @Override
  3253         public R visitCapturedType(CapturedType t, S s) {
  3254             return visitTypeVar(t, s);
  3256         @Override
  3257         public R visitForAll(ForAll t, S s) {
  3258             return visit(t.qtype, s);
  3260         @Override
  3261         public R visitUndetVar(UndetVar t, S s) {
  3262             return visit(t.qtype, s);
  3266     /**
  3267      * A plain relation on types.  That is a 2-ary function on the
  3268      * form Type&nbsp;&times;&nbsp;Type&nbsp;&rarr;&nbsp;Boolean.
  3269      * <!-- In plain text: Type x Type -> Boolean -->
  3270      */
  3271     public static abstract class TypeRelation extends SimpleVisitor<Boolean,Type> {}
  3273     /**
  3274      * A convenience visitor for implementing operations that only
  3275      * require one argument (the type itself), that is, unary
  3276      * operations.
  3278      * @param <R> the return type of the operation implemented by this
  3279      * visitor; use Void if no return type is needed.
  3280      */
  3281     public static abstract class UnaryVisitor<R> extends SimpleVisitor<R,Void> {
  3282         final public R visit(Type t) { return t.accept(this, null); }
  3285     /**
  3286      * A visitor for implementing a mapping from types to types.  The
  3287      * default behavior of this class is to implement the identity
  3288      * mapping (mapping a type to itself).  This can be overridden in
  3289      * subclasses.
  3291      * @param <S> the type of the second argument (the first being the
  3292      * type itself) of this mapping; use Void if a second argument is
  3293      * not needed.
  3294      */
  3295     public static class MapVisitor<S> extends DefaultTypeVisitor<Type,S> {
  3296         final public Type visit(Type t) { return t.accept(this, null); }
  3297         public Type visitType(Type t, S s) { return t; }
  3299     // </editor-fold>

mercurial