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

Mon, 23 Aug 2010 16:59:30 +0100

author
mcimadamore
date
Mon, 23 Aug 2010 16:59:30 +0100
changeset 640
995bcdb9a41d
parent 637
c655e0280bdc
child 657
70ebdef189c9
permissions
-rw-r--r--

6932571: Compiling Generics causing Inconvertible types
Summary: Types.rewriteQuantifiers() does not work well with recursive type-variable bounds
Reviewed-by: jjg

     1 /*
     2  * Copyright (c) 2003, 2009, Oracle and/or its affiliates. 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.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    26 package com.sun.tools.javac.code;
    28 import java.lang.ref.SoftReference;
    29 import java.util.*;
    31 import com.sun.tools.javac.util.*;
    32 import com.sun.tools.javac.util.List;
    34 import com.sun.tools.javac.jvm.ClassReader;
    35 import com.sun.tools.javac.comp.Check;
    37 import static com.sun.tools.javac.code.Type.*;
    38 import static com.sun.tools.javac.code.TypeTags.*;
    39 import static com.sun.tools.javac.code.Symbol.*;
    40 import static com.sun.tools.javac.code.Flags.*;
    41 import static com.sun.tools.javac.code.BoundKind.*;
    42 import static com.sun.tools.javac.util.ListBuffer.lb;
    44 /**
    45  * Utility class containing various operations on types.
    46  *
    47  * <p>Unless other names are more illustrative, the following naming
    48  * conventions should be observed in this file:
    49  *
    50  * <dl>
    51  * <dt>t</dt>
    52  * <dd>If the first argument to an operation is a type, it should be named t.</dd>
    53  * <dt>s</dt>
    54  * <dd>Similarly, if the second argument to an operation is a type, it should be named s.</dd>
    55  * <dt>ts</dt>
    56  * <dd>If an operations takes a list of types, the first should be named ts.</dd>
    57  * <dt>ss</dt>
    58  * <dd>A second list of types should be named ss.</dd>
    59  * </dl>
    60  *
    61  * <p><b>This is NOT part of any supported API.
    62  * If you write code that depends on this, you do so at your own risk.
    63  * This code and its internal interfaces are subject to change or
    64  * deletion without notice.</b>
    65  */
    66 public class Types {
    67     protected static final Context.Key<Types> typesKey =
    68         new Context.Key<Types>();
    70     final Symtab syms;
    71     final JavacMessages messages;
    72     final Names names;
    73     final boolean allowBoxing;
    74     final ClassReader reader;
    75     final Source source;
    76     final Check chk;
    77     List<Warner> warnStack = List.nil();
    78     final Name capturedName;
    80     // <editor-fold defaultstate="collapsed" desc="Instantiating">
    81     public static Types instance(Context context) {
    82         Types instance = context.get(typesKey);
    83         if (instance == null)
    84             instance = new Types(context);
    85         return instance;
    86     }
    88     protected Types(Context context) {
    89         context.put(typesKey, this);
    90         syms = Symtab.instance(context);
    91         names = Names.instance(context);
    92         allowBoxing = Source.instance(context).allowBoxing();
    93         reader = ClassReader.instance(context);
    94         source = Source.instance(context);
    95         chk = Check.instance(context);
    96         capturedName = names.fromString("<captured wildcard>");
    97         messages = JavacMessages.instance(context);
    98     }
    99     // </editor-fold>
   101     // <editor-fold defaultstate="collapsed" desc="upperBound">
   102     /**
   103      * The "rvalue conversion".<br>
   104      * The upper bound of most types is the type
   105      * itself.  Wildcards, on the other hand have upper
   106      * and lower bounds.
   107      * @param t a type
   108      * @return the upper bound of the given type
   109      */
   110     public Type upperBound(Type t) {
   111         return upperBound.visit(t);
   112     }
   113     // where
   114         private final MapVisitor<Void> upperBound = new MapVisitor<Void>() {
   116             @Override
   117             public Type visitWildcardType(WildcardType t, Void ignored) {
   118                 if (t.isSuperBound())
   119                     return t.bound == null ? syms.objectType : t.bound.bound;
   120                 else
   121                     return visit(t.type);
   122             }
   124             @Override
   125             public Type visitCapturedType(CapturedType t, Void ignored) {
   126                 return visit(t.bound);
   127             }
   128         };
   129     // </editor-fold>
   131     // <editor-fold defaultstate="collapsed" desc="lowerBound">
   132     /**
   133      * The "lvalue conversion".<br>
   134      * The lower bound of most types is the type
   135      * itself.  Wildcards, on the other hand have upper
   136      * and lower bounds.
   137      * @param t a type
   138      * @return the lower bound of the given type
   139      */
   140     public Type lowerBound(Type t) {
   141         return lowerBound.visit(t);
   142     }
   143     // where
   144         private final MapVisitor<Void> lowerBound = new MapVisitor<Void>() {
   146             @Override
   147             public Type visitWildcardType(WildcardType t, Void ignored) {
   148                 return t.isExtendsBound() ? syms.botType : visit(t.type);
   149             }
   151             @Override
   152             public Type visitCapturedType(CapturedType t, Void ignored) {
   153                 return visit(t.getLowerBound());
   154             }
   155         };
   156     // </editor-fold>
   158     // <editor-fold defaultstate="collapsed" desc="isUnbounded">
   159     /**
   160      * Checks that all the arguments to a class are unbounded
   161      * wildcards or something else that doesn't make any restrictions
   162      * on the arguments. If a class isUnbounded, a raw super- or
   163      * subclass can be cast to it without a warning.
   164      * @param t a type
   165      * @return true iff the given type is unbounded or raw
   166      */
   167     public boolean isUnbounded(Type t) {
   168         return isUnbounded.visit(t);
   169     }
   170     // where
   171         private final UnaryVisitor<Boolean> isUnbounded = new UnaryVisitor<Boolean>() {
   173             public Boolean visitType(Type t, Void ignored) {
   174                 return true;
   175             }
   177             @Override
   178             public Boolean visitClassType(ClassType t, Void ignored) {
   179                 List<Type> parms = t.tsym.type.allparams();
   180                 List<Type> args = t.allparams();
   181                 while (parms.nonEmpty()) {
   182                     WildcardType unb = new WildcardType(syms.objectType,
   183                                                         BoundKind.UNBOUND,
   184                                                         syms.boundClass,
   185                                                         (TypeVar)parms.head);
   186                     if (!containsType(args.head, unb))
   187                         return false;
   188                     parms = parms.tail;
   189                     args = args.tail;
   190                 }
   191                 return true;
   192             }
   193         };
   194     // </editor-fold>
   196     // <editor-fold defaultstate="collapsed" desc="asSub">
   197     /**
   198      * Return the least specific subtype of t that starts with symbol
   199      * sym.  If none exists, return null.  The least specific subtype
   200      * is determined as follows:
   201      *
   202      * <p>If there is exactly one parameterized instance of sym that is a
   203      * subtype of t, that parameterized instance is returned.<br>
   204      * Otherwise, if the plain type or raw type `sym' is a subtype of
   205      * type t, the type `sym' itself is returned.  Otherwise, null is
   206      * returned.
   207      */
   208     public Type asSub(Type t, Symbol sym) {
   209         return asSub.visit(t, sym);
   210     }
   211     // where
   212         private final SimpleVisitor<Type,Symbol> asSub = new SimpleVisitor<Type,Symbol>() {
   214             public Type visitType(Type t, Symbol sym) {
   215                 return null;
   216             }
   218             @Override
   219             public Type visitClassType(ClassType t, Symbol sym) {
   220                 if (t.tsym == sym)
   221                     return t;
   222                 Type base = asSuper(sym.type, t.tsym);
   223                 if (base == null)
   224                     return null;
   225                 ListBuffer<Type> from = new ListBuffer<Type>();
   226                 ListBuffer<Type> to = new ListBuffer<Type>();
   227                 try {
   228                     adapt(base, t, from, to);
   229                 } catch (AdaptFailure ex) {
   230                     return null;
   231                 }
   232                 Type res = subst(sym.type, from.toList(), to.toList());
   233                 if (!isSubtype(res, t))
   234                     return null;
   235                 ListBuffer<Type> openVars = new ListBuffer<Type>();
   236                 for (List<Type> l = sym.type.allparams();
   237                      l.nonEmpty(); l = l.tail)
   238                     if (res.contains(l.head) && !t.contains(l.head))
   239                         openVars.append(l.head);
   240                 if (openVars.nonEmpty()) {
   241                     if (t.isRaw()) {
   242                         // The subtype of a raw type is raw
   243                         res = erasure(res);
   244                     } else {
   245                         // Unbound type arguments default to ?
   246                         List<Type> opens = openVars.toList();
   247                         ListBuffer<Type> qs = new ListBuffer<Type>();
   248                         for (List<Type> iter = opens; iter.nonEmpty(); iter = iter.tail) {
   249                             qs.append(new WildcardType(syms.objectType, BoundKind.UNBOUND, syms.boundClass, (TypeVar) iter.head));
   250                         }
   251                         res = subst(res, opens, qs.toList());
   252                     }
   253                 }
   254                 return res;
   255             }
   257             @Override
   258             public Type visitErrorType(ErrorType t, Symbol sym) {
   259                 return t;
   260             }
   261         };
   262     // </editor-fold>
   264     // <editor-fold defaultstate="collapsed" desc="isConvertible">
   265     /**
   266      * Is t a subtype of or convertiable via boxing/unboxing
   267      * convertions to s?
   268      */
   269     public boolean isConvertible(Type t, Type s, Warner warn) {
   270         boolean tPrimitive = t.isPrimitive();
   271         boolean sPrimitive = s.isPrimitive();
   272         if (tPrimitive == sPrimitive)
   273             return isSubtypeUnchecked(t, s, warn);
   274         if (!allowBoxing) return false;
   275         return tPrimitive
   276             ? isSubtype(boxedClass(t).type, s)
   277             : isSubtype(unboxedType(t), s);
   278     }
   280     /**
   281      * Is t a subtype of or convertiable via boxing/unboxing
   282      * convertions to s?
   283      */
   284     public boolean isConvertible(Type t, Type s) {
   285         return isConvertible(t, s, Warner.noWarnings);
   286     }
   287     // </editor-fold>
   289     // <editor-fold defaultstate="collapsed" desc="isSubtype">
   290     /**
   291      * Is t an unchecked subtype of s?
   292      */
   293     public boolean isSubtypeUnchecked(Type t, Type s) {
   294         return isSubtypeUnchecked(t, s, Warner.noWarnings);
   295     }
   296     /**
   297      * Is t an unchecked subtype of s?
   298      */
   299     public boolean isSubtypeUnchecked(Type t, Type s, Warner warn) {
   300         if (t.tag == ARRAY && s.tag == ARRAY) {
   301             return (((ArrayType)t).elemtype.tag <= lastBaseTag)
   302                 ? isSameType(elemtype(t), elemtype(s))
   303                 : isSubtypeUnchecked(elemtype(t), elemtype(s), warn);
   304         } else if (isSubtype(t, s)) {
   305             return true;
   306         }
   307         else if (t.tag == TYPEVAR) {
   308             return isSubtypeUnchecked(t.getUpperBound(), s, warn);
   309         }
   310         else if (s.tag == UNDETVAR) {
   311             UndetVar uv = (UndetVar)s;
   312             if (uv.inst != null)
   313                 return isSubtypeUnchecked(t, uv.inst, warn);
   314         }
   315         else if (!s.isRaw()) {
   316             Type t2 = asSuper(t, s.tsym);
   317             if (t2 != null && t2.isRaw()) {
   318                 if (isReifiable(s))
   319                     warn.silentUnchecked();
   320                 else
   321                     warn.warnUnchecked();
   322                 return true;
   323             }
   324         }
   325         return false;
   326     }
   328     /**
   329      * Is t a subtype of s?<br>
   330      * (not defined for Method and ForAll types)
   331      */
   332     final public boolean isSubtype(Type t, Type s) {
   333         return isSubtype(t, s, true);
   334     }
   335     final public boolean isSubtypeNoCapture(Type t, Type s) {
   336         return isSubtype(t, s, false);
   337     }
   338     public boolean isSubtype(Type t, Type s, boolean capture) {
   339         if (t == s)
   340             return true;
   342         if (s.tag >= firstPartialTag)
   343             return isSuperType(s, t);
   345         if (s.isCompound()) {
   346             for (Type s2 : interfaces(s).prepend(supertype(s))) {
   347                 if (!isSubtype(t, s2, capture))
   348                     return false;
   349             }
   350             return true;
   351         }
   353         Type lower = lowerBound(s);
   354         if (s != lower)
   355             return isSubtype(capture ? capture(t) : t, lower, false);
   357         return isSubtype.visit(capture ? capture(t) : t, s);
   358     }
   359     // where
   360         private TypeRelation isSubtype = new TypeRelation()
   361         {
   362             public Boolean visitType(Type t, Type s) {
   363                 switch (t.tag) {
   364                 case BYTE: case CHAR:
   365                     return (t.tag == s.tag ||
   366                               t.tag + 2 <= s.tag && s.tag <= DOUBLE);
   367                 case SHORT: case INT: case LONG: case FLOAT: case DOUBLE:
   368                     return t.tag <= s.tag && s.tag <= DOUBLE;
   369                 case BOOLEAN: case VOID:
   370                     return t.tag == s.tag;
   371                 case TYPEVAR:
   372                     return isSubtypeNoCapture(t.getUpperBound(), s);
   373                 case BOT:
   374                     return
   375                         s.tag == BOT || s.tag == CLASS ||
   376                         s.tag == ARRAY || s.tag == TYPEVAR;
   377                 case NONE:
   378                     return false;
   379                 default:
   380                     throw new AssertionError("isSubtype " + t.tag);
   381                 }
   382             }
   384             private Set<TypePair> cache = new HashSet<TypePair>();
   386             private boolean containsTypeRecursive(Type t, Type s) {
   387                 TypePair pair = new TypePair(t, s);
   388                 if (cache.add(pair)) {
   389                     try {
   390                         return containsType(t.getTypeArguments(),
   391                                             s.getTypeArguments());
   392                     } finally {
   393                         cache.remove(pair);
   394                     }
   395                 } else {
   396                     return containsType(t.getTypeArguments(),
   397                                         rewriteSupers(s).getTypeArguments());
   398                 }
   399             }
   401             private Type rewriteSupers(Type t) {
   402                 if (!t.isParameterized())
   403                     return t;
   404                 ListBuffer<Type> from = lb();
   405                 ListBuffer<Type> to = lb();
   406                 adaptSelf(t, from, to);
   407                 if (from.isEmpty())
   408                     return t;
   409                 ListBuffer<Type> rewrite = lb();
   410                 boolean changed = false;
   411                 for (Type orig : to.toList()) {
   412                     Type s = rewriteSupers(orig);
   413                     if (s.isSuperBound() && !s.isExtendsBound()) {
   414                         s = new WildcardType(syms.objectType,
   415                                              BoundKind.UNBOUND,
   416                                              syms.boundClass);
   417                         changed = true;
   418                     } else if (s != orig) {
   419                         s = new WildcardType(upperBound(s),
   420                                              BoundKind.EXTENDS,
   421                                              syms.boundClass);
   422                         changed = true;
   423                     }
   424                     rewrite.append(s);
   425                 }
   426                 if (changed)
   427                     return subst(t.tsym.type, from.toList(), rewrite.toList());
   428                 else
   429                     return t;
   430             }
   432             @Override
   433             public Boolean visitClassType(ClassType t, Type s) {
   434                 Type sup = asSuper(t, s.tsym);
   435                 return sup != null
   436                     && sup.tsym == s.tsym
   437                     // You're not allowed to write
   438                     //     Vector<Object> vec = new Vector<String>();
   439                     // But with wildcards you can write
   440                     //     Vector<? extends Object> vec = new Vector<String>();
   441                     // which means that subtype checking must be done
   442                     // here instead of same-type checking (via containsType).
   443                     && (!s.isParameterized() || containsTypeRecursive(s, sup))
   444                     && isSubtypeNoCapture(sup.getEnclosingType(),
   445                                           s.getEnclosingType());
   446             }
   448             @Override
   449             public Boolean visitArrayType(ArrayType t, Type s) {
   450                 if (s.tag == ARRAY) {
   451                     if (t.elemtype.tag <= lastBaseTag)
   452                         return isSameType(t.elemtype, elemtype(s));
   453                     else
   454                         return isSubtypeNoCapture(t.elemtype, elemtype(s));
   455                 }
   457                 if (s.tag == CLASS) {
   458                     Name sname = s.tsym.getQualifiedName();
   459                     return sname == names.java_lang_Object
   460                         || sname == names.java_lang_Cloneable
   461                         || sname == names.java_io_Serializable;
   462                 }
   464                 return false;
   465             }
   467             @Override
   468             public Boolean visitUndetVar(UndetVar t, Type s) {
   469                 //todo: test against origin needed? or replace with substitution?
   470                 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN)
   471                     return true;
   473                 if (t.inst != null)
   474                     return isSubtypeNoCapture(t.inst, s); // TODO: ", warn"?
   476                 t.hibounds = t.hibounds.prepend(s);
   477                 return true;
   478             }
   480             @Override
   481             public Boolean visitErrorType(ErrorType t, Type s) {
   482                 return true;
   483             }
   484         };
   486     /**
   487      * Is t a subtype of every type in given list `ts'?<br>
   488      * (not defined for Method and ForAll types)<br>
   489      * Allows unchecked conversions.
   490      */
   491     public boolean isSubtypeUnchecked(Type t, List<Type> ts, Warner warn) {
   492         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
   493             if (!isSubtypeUnchecked(t, l.head, warn))
   494                 return false;
   495         return true;
   496     }
   498     /**
   499      * Are corresponding elements of ts subtypes of ss?  If lists are
   500      * of different length, return false.
   501      */
   502     public boolean isSubtypes(List<Type> ts, List<Type> ss) {
   503         while (ts.tail != null && ss.tail != null
   504                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   505                isSubtype(ts.head, ss.head)) {
   506             ts = ts.tail;
   507             ss = ss.tail;
   508         }
   509         return ts.tail == null && ss.tail == null;
   510         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   511     }
   513     /**
   514      * Are corresponding elements of ts subtypes of ss, allowing
   515      * unchecked conversions?  If lists are of different length,
   516      * return false.
   517      **/
   518     public boolean isSubtypesUnchecked(List<Type> ts, List<Type> ss, Warner warn) {
   519         while (ts.tail != null && ss.tail != null
   520                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   521                isSubtypeUnchecked(ts.head, ss.head, warn)) {
   522             ts = ts.tail;
   523             ss = ss.tail;
   524         }
   525         return ts.tail == null && ss.tail == null;
   526         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   527     }
   528     // </editor-fold>
   530     // <editor-fold defaultstate="collapsed" desc="isSuperType">
   531     /**
   532      * Is t a supertype of s?
   533      */
   534     public boolean isSuperType(Type t, Type s) {
   535         switch (t.tag) {
   536         case ERROR:
   537             return true;
   538         case UNDETVAR: {
   539             UndetVar undet = (UndetVar)t;
   540             if (t == s ||
   541                 undet.qtype == s ||
   542                 s.tag == ERROR ||
   543                 s.tag == BOT) return true;
   544             if (undet.inst != null)
   545                 return isSubtype(s, undet.inst);
   546             undet.lobounds = undet.lobounds.prepend(s);
   547             return true;
   548         }
   549         default:
   550             return isSubtype(s, t);
   551         }
   552     }
   553     // </editor-fold>
   555     // <editor-fold defaultstate="collapsed" desc="isSameType">
   556     /**
   557      * Are corresponding elements of the lists the same type?  If
   558      * lists are of different length, return false.
   559      */
   560     public boolean isSameTypes(List<Type> ts, List<Type> ss) {
   561         while (ts.tail != null && ss.tail != null
   562                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   563                isSameType(ts.head, ss.head)) {
   564             ts = ts.tail;
   565             ss = ss.tail;
   566         }
   567         return ts.tail == null && ss.tail == null;
   568         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   569     }
   571     /**
   572      * Is t the same type as s?
   573      */
   574     public boolean isSameType(Type t, Type s) {
   575         return isSameType.visit(t, s);
   576     }
   577     // where
   578         private TypeRelation isSameType = new TypeRelation() {
   580             public Boolean visitType(Type t, Type s) {
   581                 if (t == s)
   582                     return true;
   584                 if (s.tag >= firstPartialTag)
   585                     return visit(s, t);
   587                 switch (t.tag) {
   588                 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
   589                 case DOUBLE: case BOOLEAN: case VOID: case BOT: case NONE:
   590                     return t.tag == s.tag;
   591                 case TYPEVAR: {
   592                     if (s.tag == TYPEVAR) {
   593                         //type-substitution does not preserve type-var types
   594                         //check that type var symbols and bounds are indeed the same
   595                         return t.tsym == s.tsym &&
   596                                 visit(t.getUpperBound(), s.getUpperBound());
   597                     }
   598                     else {
   599                         //special case for s == ? super X, where upper(s) = u
   600                         //check that u == t, where u has been set by Type.withTypeVar
   601                         return s.isSuperBound() &&
   602                                 !s.isExtendsBound() &&
   603                                 visit(t, upperBound(s));
   604                     }
   605                 }
   606                 default:
   607                     throw new AssertionError("isSameType " + t.tag);
   608                 }
   609             }
   611             @Override
   612             public Boolean visitWildcardType(WildcardType t, Type s) {
   613                 if (s.tag >= firstPartialTag)
   614                     return visit(s, t);
   615                 else
   616                     return false;
   617             }
   619             @Override
   620             public Boolean visitClassType(ClassType t, Type s) {
   621                 if (t == s)
   622                     return true;
   624                 if (s.tag >= firstPartialTag)
   625                     return visit(s, t);
   627                 if (s.isSuperBound() && !s.isExtendsBound())
   628                     return visit(t, upperBound(s)) && visit(t, lowerBound(s));
   630                 if (t.isCompound() && s.isCompound()) {
   631                     if (!visit(supertype(t), supertype(s)))
   632                         return false;
   634                     HashSet<SingletonType> set = new HashSet<SingletonType>();
   635                     for (Type x : interfaces(t))
   636                         set.add(new SingletonType(x));
   637                     for (Type x : interfaces(s)) {
   638                         if (!set.remove(new SingletonType(x)))
   639                             return false;
   640                     }
   641                     return (set.size() == 0);
   642                 }
   643                 return t.tsym == s.tsym
   644                     && visit(t.getEnclosingType(), s.getEnclosingType())
   645                     && containsTypeEquivalent(t.getTypeArguments(), s.getTypeArguments());
   646             }
   648             @Override
   649             public Boolean visitArrayType(ArrayType t, Type s) {
   650                 if (t == s)
   651                     return true;
   653                 if (s.tag >= firstPartialTag)
   654                     return visit(s, t);
   656                 return s.tag == ARRAY
   657                     && containsTypeEquivalent(t.elemtype, elemtype(s));
   658             }
   660             @Override
   661             public Boolean visitMethodType(MethodType t, Type s) {
   662                 // isSameType for methods does not take thrown
   663                 // exceptions into account!
   664                 return hasSameArgs(t, s) && visit(t.getReturnType(), s.getReturnType());
   665             }
   667             @Override
   668             public Boolean visitPackageType(PackageType t, Type s) {
   669                 return t == s;
   670             }
   672             @Override
   673             public Boolean visitForAll(ForAll t, Type s) {
   674                 if (s.tag != FORALL)
   675                     return false;
   677                 ForAll forAll = (ForAll)s;
   678                 return hasSameBounds(t, forAll)
   679                     && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
   680             }
   682             @Override
   683             public Boolean visitUndetVar(UndetVar t, Type s) {
   684                 if (s.tag == WILDCARD)
   685                     // FIXME, this might be leftovers from before capture conversion
   686                     return false;
   688                 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN)
   689                     return true;
   691                 if (t.inst != null)
   692                     return visit(t.inst, s);
   694                 t.inst = fromUnknownFun.apply(s);
   695                 for (List<Type> l = t.lobounds; l.nonEmpty(); l = l.tail) {
   696                     if (!isSubtype(l.head, t.inst))
   697                         return false;
   698                 }
   699                 for (List<Type> l = t.hibounds; l.nonEmpty(); l = l.tail) {
   700                     if (!isSubtype(t.inst, l.head))
   701                         return false;
   702                 }
   703                 return true;
   704             }
   706             @Override
   707             public Boolean visitErrorType(ErrorType t, Type s) {
   708                 return true;
   709             }
   710         };
   711     // </editor-fold>
   713     // <editor-fold defaultstate="collapsed" desc="fromUnknownFun">
   714     /**
   715      * A mapping that turns all unknown types in this type to fresh
   716      * unknown variables.
   717      */
   718     public Mapping fromUnknownFun = new Mapping("fromUnknownFun") {
   719             public Type apply(Type t) {
   720                 if (t.tag == UNKNOWN) return new UndetVar(t);
   721                 else return t.map(this);
   722             }
   723         };
   724     // </editor-fold>
   726     // <editor-fold defaultstate="collapsed" desc="Contains Type">
   727     public boolean containedBy(Type t, Type s) {
   728         switch (t.tag) {
   729         case UNDETVAR:
   730             if (s.tag == WILDCARD) {
   731                 UndetVar undetvar = (UndetVar)t;
   732                 WildcardType wt = (WildcardType)s;
   733                 switch(wt.kind) {
   734                     case UNBOUND: //similar to ? extends Object
   735                     case EXTENDS: {
   736                         Type bound = upperBound(s);
   737                         // We should check the new upper bound against any of the
   738                         // undetvar's lower bounds.
   739                         for (Type t2 : undetvar.lobounds) {
   740                             if (!isSubtype(t2, bound))
   741                                 return false;
   742                         }
   743                         undetvar.hibounds = undetvar.hibounds.prepend(bound);
   744                         break;
   745                     }
   746                     case SUPER: {
   747                         Type bound = lowerBound(s);
   748                         // We should check the new lower bound against any of the
   749                         // undetvar's lower bounds.
   750                         for (Type t2 : undetvar.hibounds) {
   751                             if (!isSubtype(bound, t2))
   752                                 return false;
   753                         }
   754                         undetvar.lobounds = undetvar.lobounds.prepend(bound);
   755                         break;
   756                     }
   757                 }
   758                 return true;
   759             } else {
   760                 return isSameType(t, s);
   761             }
   762         case ERROR:
   763             return true;
   764         default:
   765             return containsType(s, t);
   766         }
   767     }
   769     boolean containsType(List<Type> ts, List<Type> ss) {
   770         while (ts.nonEmpty() && ss.nonEmpty()
   771                && containsType(ts.head, ss.head)) {
   772             ts = ts.tail;
   773             ss = ss.tail;
   774         }
   775         return ts.isEmpty() && ss.isEmpty();
   776     }
   778     /**
   779      * Check if t contains s.
   780      *
   781      * <p>T contains S if:
   782      *
   783      * <p>{@code L(T) <: L(S) && U(S) <: U(T)}
   784      *
   785      * <p>This relation is only used by ClassType.isSubtype(), that
   786      * is,
   787      *
   788      * <p>{@code C<S> <: C<T> if T contains S.}
   789      *
   790      * <p>Because of F-bounds, this relation can lead to infinite
   791      * recursion.  Thus we must somehow break that recursion.  Notice
   792      * that containsType() is only called from ClassType.isSubtype().
   793      * Since the arguments have already been checked against their
   794      * bounds, we know:
   795      *
   796      * <p>{@code U(S) <: U(T) if T is "super" bound (U(T) *is* the bound)}
   797      *
   798      * <p>{@code L(T) <: L(S) if T is "extends" bound (L(T) is bottom)}
   799      *
   800      * @param t a type
   801      * @param s a type
   802      */
   803     public boolean containsType(Type t, Type s) {
   804         return containsType.visit(t, s);
   805     }
   806     // where
   807         private TypeRelation containsType = new TypeRelation() {
   809             private Type U(Type t) {
   810                 while (t.tag == WILDCARD) {
   811                     WildcardType w = (WildcardType)t;
   812                     if (w.isSuperBound())
   813                         return w.bound == null ? syms.objectType : w.bound.bound;
   814                     else
   815                         t = w.type;
   816                 }
   817                 return t;
   818             }
   820             private Type L(Type t) {
   821                 while (t.tag == WILDCARD) {
   822                     WildcardType w = (WildcardType)t;
   823                     if (w.isExtendsBound())
   824                         return syms.botType;
   825                     else
   826                         t = w.type;
   827                 }
   828                 return t;
   829             }
   831             public Boolean visitType(Type t, Type s) {
   832                 if (s.tag >= firstPartialTag)
   833                     return containedBy(s, t);
   834                 else
   835                     return isSameType(t, s);
   836             }
   838             void debugContainsType(WildcardType t, Type s) {
   839                 System.err.println();
   840                 System.err.format(" does %s contain %s?%n", t, s);
   841                 System.err.format(" %s U(%s) <: U(%s) %s = %s%n",
   842                                   upperBound(s), s, t, U(t),
   843                                   t.isSuperBound()
   844                                   || isSubtypeNoCapture(upperBound(s), U(t)));
   845                 System.err.format(" %s L(%s) <: L(%s) %s = %s%n",
   846                                   L(t), t, s, lowerBound(s),
   847                                   t.isExtendsBound()
   848                                   || isSubtypeNoCapture(L(t), lowerBound(s)));
   849                 System.err.println();
   850             }
   852             @Override
   853             public Boolean visitWildcardType(WildcardType t, Type s) {
   854                 if (s.tag >= firstPartialTag)
   855                     return containedBy(s, t);
   856                 else {
   857                     // debugContainsType(t, s);
   858                     return isSameWildcard(t, s)
   859                         || isCaptureOf(s, t)
   860                         || ((t.isExtendsBound() || isSubtypeNoCapture(L(t), lowerBound(s))) &&
   861                             (t.isSuperBound() || isSubtypeNoCapture(upperBound(s), U(t))));
   862                 }
   863             }
   865             @Override
   866             public Boolean visitUndetVar(UndetVar t, Type s) {
   867                 if (s.tag != WILDCARD)
   868                     return isSameType(t, s);
   869                 else
   870                     return false;
   871             }
   873             @Override
   874             public Boolean visitErrorType(ErrorType t, Type s) {
   875                 return true;
   876             }
   877         };
   879     public boolean isCaptureOf(Type s, WildcardType t) {
   880         if (s.tag != TYPEVAR || !((TypeVar)s).isCaptured())
   881             return false;
   882         return isSameWildcard(t, ((CapturedType)s).wildcard);
   883     }
   885     public boolean isSameWildcard(WildcardType t, Type s) {
   886         if (s.tag != WILDCARD)
   887             return false;
   888         WildcardType w = (WildcardType)s;
   889         return w.kind == t.kind && w.type == t.type;
   890     }
   892     public boolean containsTypeEquivalent(List<Type> ts, List<Type> ss) {
   893         while (ts.nonEmpty() && ss.nonEmpty()
   894                && containsTypeEquivalent(ts.head, ss.head)) {
   895             ts = ts.tail;
   896             ss = ss.tail;
   897         }
   898         return ts.isEmpty() && ss.isEmpty();
   899     }
   900     // </editor-fold>
   902     // <editor-fold defaultstate="collapsed" desc="isCastable">
   903     public boolean isCastable(Type t, Type s) {
   904         return isCastable(t, s, Warner.noWarnings);
   905     }
   907     /**
   908      * Is t is castable to s?<br>
   909      * s is assumed to be an erased type.<br>
   910      * (not defined for Method and ForAll types).
   911      */
   912     public boolean isCastable(Type t, Type s, Warner warn) {
   913         if (t == s)
   914             return true;
   916         if (t.isPrimitive() != s.isPrimitive())
   917             return allowBoxing && isConvertible(t, s, warn);
   919         if (warn != warnStack.head) {
   920             try {
   921                 warnStack = warnStack.prepend(warn);
   922                 return isCastable.visit(t,s);
   923             } finally {
   924                 warnStack = warnStack.tail;
   925             }
   926         } else {
   927             return isCastable.visit(t,s);
   928         }
   929     }
   930     // where
   931         private TypeRelation isCastable = new TypeRelation() {
   933             public Boolean visitType(Type t, Type s) {
   934                 if (s.tag == ERROR)
   935                     return true;
   937                 switch (t.tag) {
   938                 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
   939                 case DOUBLE:
   940                     return s.tag <= DOUBLE;
   941                 case BOOLEAN:
   942                     return s.tag == BOOLEAN;
   943                 case VOID:
   944                     return false;
   945                 case BOT:
   946                     return isSubtype(t, s);
   947                 default:
   948                     throw new AssertionError();
   949                 }
   950             }
   952             @Override
   953             public Boolean visitWildcardType(WildcardType t, Type s) {
   954                 return isCastable(upperBound(t), s, warnStack.head);
   955             }
   957             @Override
   958             public Boolean visitClassType(ClassType t, Type s) {
   959                 if (s.tag == ERROR || s.tag == BOT)
   960                     return true;
   962                 if (s.tag == TYPEVAR) {
   963                     if (isCastable(t, s.getUpperBound(), Warner.noWarnings)) {
   964                         warnStack.head.warnUnchecked();
   965                         return true;
   966                     } else {
   967                         return false;
   968                     }
   969                 }
   971                 if (t.isCompound()) {
   972                     Warner oldWarner = warnStack.head;
   973                     warnStack.head = Warner.noWarnings;
   974                     if (!visit(supertype(t), s))
   975                         return false;
   976                     for (Type intf : interfaces(t)) {
   977                         if (!visit(intf, s))
   978                             return false;
   979                     }
   980                     if (warnStack.head.unchecked == true)
   981                         oldWarner.warnUnchecked();
   982                     return true;
   983                 }
   985                 if (s.isCompound()) {
   986                     // call recursively to reuse the above code
   987                     return visitClassType((ClassType)s, t);
   988                 }
   990                 if (s.tag == CLASS || s.tag == ARRAY) {
   991                     boolean upcast;
   992                     if ((upcast = isSubtype(erasure(t), erasure(s)))
   993                         || isSubtype(erasure(s), erasure(t))) {
   994                         if (!upcast && s.tag == ARRAY) {
   995                             if (!isReifiable(s))
   996                                 warnStack.head.warnUnchecked();
   997                             return true;
   998                         } else if (s.isRaw()) {
   999                             return true;
  1000                         } else if (t.isRaw()) {
  1001                             if (!isUnbounded(s))
  1002                                 warnStack.head.warnUnchecked();
  1003                             return true;
  1005                         // Assume |a| <: |b|
  1006                         final Type a = upcast ? t : s;
  1007                         final Type b = upcast ? s : t;
  1008                         final boolean HIGH = true;
  1009                         final boolean LOW = false;
  1010                         final boolean DONT_REWRITE_TYPEVARS = false;
  1011                         Type aHigh = rewriteQuantifiers(a, HIGH, DONT_REWRITE_TYPEVARS);
  1012                         Type aLow  = rewriteQuantifiers(a, LOW,  DONT_REWRITE_TYPEVARS);
  1013                         Type bHigh = rewriteQuantifiers(b, HIGH, DONT_REWRITE_TYPEVARS);
  1014                         Type bLow  = rewriteQuantifiers(b, LOW,  DONT_REWRITE_TYPEVARS);
  1015                         Type lowSub = asSub(bLow, aLow.tsym);
  1016                         Type highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
  1017                         if (highSub == null) {
  1018                             final boolean REWRITE_TYPEVARS = true;
  1019                             aHigh = rewriteQuantifiers(a, HIGH, REWRITE_TYPEVARS);
  1020                             aLow  = rewriteQuantifiers(a, LOW,  REWRITE_TYPEVARS);
  1021                             bHigh = rewriteQuantifiers(b, HIGH, REWRITE_TYPEVARS);
  1022                             bLow  = rewriteQuantifiers(b, LOW,  REWRITE_TYPEVARS);
  1023                             lowSub = asSub(bLow, aLow.tsym);
  1024                             highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
  1026                         if (highSub != null) {
  1027                             assert a.tsym == highSub.tsym && a.tsym == lowSub.tsym
  1028                                 : a.tsym + " != " + highSub.tsym + " != " + lowSub.tsym;
  1029                             if (!disjointTypes(aHigh.allparams(), highSub.allparams())
  1030                                 && !disjointTypes(aHigh.allparams(), lowSub.allparams())
  1031                                 && !disjointTypes(aLow.allparams(), highSub.allparams())
  1032                                 && !disjointTypes(aLow.allparams(), lowSub.allparams())) {
  1033                                 if (s.isInterface() &&
  1034                                         !t.isInterface() &&
  1035                                         t.isFinal() &&
  1036                                         !isSubtype(t, s)) {
  1037                                     return false;
  1038                                 } else if (upcast ? giveWarning(a, b) :
  1039                                     giveWarning(b, a))
  1040                                     warnStack.head.warnUnchecked();
  1041                                 return true;
  1044                         if (isReifiable(s))
  1045                             return isSubtypeUnchecked(a, b);
  1046                         else
  1047                             return isSubtypeUnchecked(a, b, warnStack.head);
  1050                     // Sidecast
  1051                     if (s.tag == CLASS) {
  1052                         if ((s.tsym.flags() & INTERFACE) != 0) {
  1053                             return ((t.tsym.flags() & FINAL) == 0)
  1054                                 ? sideCast(t, s, warnStack.head)
  1055                                 : sideCastFinal(t, s, warnStack.head);
  1056                         } else if ((t.tsym.flags() & INTERFACE) != 0) {
  1057                             return ((s.tsym.flags() & FINAL) == 0)
  1058                                 ? sideCast(t, s, warnStack.head)
  1059                                 : sideCastFinal(t, s, warnStack.head);
  1060                         } else {
  1061                             // unrelated class types
  1062                             return false;
  1066                 return false;
  1069             @Override
  1070             public Boolean visitArrayType(ArrayType t, Type s) {
  1071                 switch (s.tag) {
  1072                 case ERROR:
  1073                 case BOT:
  1074                     return true;
  1075                 case TYPEVAR:
  1076                     if (isCastable(s, t, Warner.noWarnings)) {
  1077                         warnStack.head.warnUnchecked();
  1078                         return true;
  1079                     } else {
  1080                         return false;
  1082                 case CLASS:
  1083                     return isSubtype(t, s);
  1084                 case ARRAY:
  1085                     if (elemtype(t).tag <= lastBaseTag) {
  1086                         return elemtype(t).tag == elemtype(s).tag;
  1087                     } else {
  1088                         return visit(elemtype(t), elemtype(s));
  1090                 default:
  1091                     return false;
  1095             @Override
  1096             public Boolean visitTypeVar(TypeVar t, Type s) {
  1097                 switch (s.tag) {
  1098                 case ERROR:
  1099                 case BOT:
  1100                     return true;
  1101                 case TYPEVAR:
  1102                     if (isSubtype(t, s)) {
  1103                         return true;
  1104                     } else if (isCastable(t.bound, s, Warner.noWarnings)) {
  1105                         warnStack.head.warnUnchecked();
  1106                         return true;
  1107                     } else {
  1108                         return false;
  1110                 default:
  1111                     return isCastable(t.bound, s, warnStack.head);
  1115             @Override
  1116             public Boolean visitErrorType(ErrorType t, Type s) {
  1117                 return true;
  1119         };
  1120     // </editor-fold>
  1122     // <editor-fold defaultstate="collapsed" desc="disjointTypes">
  1123     public boolean disjointTypes(List<Type> ts, List<Type> ss) {
  1124         while (ts.tail != null && ss.tail != null) {
  1125             if (disjointType(ts.head, ss.head)) return true;
  1126             ts = ts.tail;
  1127             ss = ss.tail;
  1129         return false;
  1132     /**
  1133      * Two types or wildcards are considered disjoint if it can be
  1134      * proven that no type can be contained in both. It is
  1135      * conservative in that it is allowed to say that two types are
  1136      * not disjoint, even though they actually are.
  1138      * The type C<X> is castable to C<Y> exactly if X and Y are not
  1139      * disjoint.
  1140      */
  1141     public boolean disjointType(Type t, Type s) {
  1142         return disjointType.visit(t, s);
  1144     // where
  1145         private TypeRelation disjointType = new TypeRelation() {
  1147             private Set<TypePair> cache = new HashSet<TypePair>();
  1149             public Boolean visitType(Type t, Type s) {
  1150                 if (s.tag == WILDCARD)
  1151                     return visit(s, t);
  1152                 else
  1153                     return notSoftSubtypeRecursive(t, s) || notSoftSubtypeRecursive(s, t);
  1156             private boolean isCastableRecursive(Type t, Type s) {
  1157                 TypePair pair = new TypePair(t, s);
  1158                 if (cache.add(pair)) {
  1159                     try {
  1160                         return Types.this.isCastable(t, s);
  1161                     } finally {
  1162                         cache.remove(pair);
  1164                 } else {
  1165                     return true;
  1169             private boolean notSoftSubtypeRecursive(Type t, Type s) {
  1170                 TypePair pair = new TypePair(t, s);
  1171                 if (cache.add(pair)) {
  1172                     try {
  1173                         return Types.this.notSoftSubtype(t, s);
  1174                     } finally {
  1175                         cache.remove(pair);
  1177                 } else {
  1178                     return false;
  1182             @Override
  1183             public Boolean visitWildcardType(WildcardType t, Type s) {
  1184                 if (t.isUnbound())
  1185                     return false;
  1187                 if (s.tag != WILDCARD) {
  1188                     if (t.isExtendsBound())
  1189                         return notSoftSubtypeRecursive(s, t.type);
  1190                     else // isSuperBound()
  1191                         return notSoftSubtypeRecursive(t.type, s);
  1194                 if (s.isUnbound())
  1195                     return false;
  1197                 if (t.isExtendsBound()) {
  1198                     if (s.isExtendsBound())
  1199                         return !isCastableRecursive(t.type, upperBound(s));
  1200                     else if (s.isSuperBound())
  1201                         return notSoftSubtypeRecursive(lowerBound(s), t.type);
  1202                 } else if (t.isSuperBound()) {
  1203                     if (s.isExtendsBound())
  1204                         return notSoftSubtypeRecursive(t.type, upperBound(s));
  1206                 return false;
  1208         };
  1209     // </editor-fold>
  1211     // <editor-fold defaultstate="collapsed" desc="lowerBoundArgtypes">
  1212     /**
  1213      * Returns the lower bounds of the formals of a method.
  1214      */
  1215     public List<Type> lowerBoundArgtypes(Type t) {
  1216         return map(t.getParameterTypes(), lowerBoundMapping);
  1218     private final Mapping lowerBoundMapping = new Mapping("lowerBound") {
  1219             public Type apply(Type t) {
  1220                 return lowerBound(t);
  1222         };
  1223     // </editor-fold>
  1225     // <editor-fold defaultstate="collapsed" desc="notSoftSubtype">
  1226     /**
  1227      * This relation answers the question: is impossible that
  1228      * something of type `t' can be a subtype of `s'? This is
  1229      * different from the question "is `t' not a subtype of `s'?"
  1230      * when type variables are involved: Integer is not a subtype of T
  1231      * where <T extends Number> but it is not true that Integer cannot
  1232      * possibly be a subtype of T.
  1233      */
  1234     public boolean notSoftSubtype(Type t, Type s) {
  1235         if (t == s) return false;
  1236         if (t.tag == TYPEVAR) {
  1237             TypeVar tv = (TypeVar) t;
  1238             return !isCastable(tv.bound,
  1239                                relaxBound(s),
  1240                                Warner.noWarnings);
  1242         if (s.tag != WILDCARD)
  1243             s = upperBound(s);
  1245         return !isSubtype(t, relaxBound(s));
  1248     private Type relaxBound(Type t) {
  1249         if (t.tag == TYPEVAR) {
  1250             while (t.tag == TYPEVAR)
  1251                 t = t.getUpperBound();
  1252             t = rewriteQuantifiers(t, true, true);
  1254         return t;
  1256     // </editor-fold>
  1258     // <editor-fold defaultstate="collapsed" desc="isReifiable">
  1259     public boolean isReifiable(Type t) {
  1260         return isReifiable.visit(t);
  1262     // where
  1263         private UnaryVisitor<Boolean> isReifiable = new UnaryVisitor<Boolean>() {
  1265             public Boolean visitType(Type t, Void ignored) {
  1266                 return true;
  1269             @Override
  1270             public Boolean visitClassType(ClassType t, Void ignored) {
  1271                 if (t.isCompound())
  1272                     return false;
  1273                 else {
  1274                     if (!t.isParameterized())
  1275                         return true;
  1277                     for (Type param : t.allparams()) {
  1278                         if (!param.isUnbound())
  1279                             return false;
  1281                     return true;
  1285             @Override
  1286             public Boolean visitArrayType(ArrayType t, Void ignored) {
  1287                 return visit(t.elemtype);
  1290             @Override
  1291             public Boolean visitTypeVar(TypeVar t, Void ignored) {
  1292                 return false;
  1294         };
  1295     // </editor-fold>
  1297     // <editor-fold defaultstate="collapsed" desc="Array Utils">
  1298     public boolean isArray(Type t) {
  1299         while (t.tag == WILDCARD)
  1300             t = upperBound(t);
  1301         return t.tag == ARRAY;
  1304     /**
  1305      * The element type of an array.
  1306      */
  1307     public Type elemtype(Type t) {
  1308         switch (t.tag) {
  1309         case WILDCARD:
  1310             return elemtype(upperBound(t));
  1311         case ARRAY:
  1312             return ((ArrayType)t).elemtype;
  1313         case FORALL:
  1314             return elemtype(((ForAll)t).qtype);
  1315         case ERROR:
  1316             return t;
  1317         default:
  1318             return null;
  1322     /**
  1323      * Mapping to take element type of an arraytype
  1324      */
  1325     private Mapping elemTypeFun = new Mapping ("elemTypeFun") {
  1326         public Type apply(Type t) { return elemtype(t); }
  1327     };
  1329     /**
  1330      * The number of dimensions of an array type.
  1331      */
  1332     public int dimensions(Type t) {
  1333         int result = 0;
  1334         while (t.tag == ARRAY) {
  1335             result++;
  1336             t = elemtype(t);
  1338         return result;
  1340     // </editor-fold>
  1342     // <editor-fold defaultstate="collapsed" desc="asSuper">
  1343     /**
  1344      * Return the (most specific) base type of t that starts with the
  1345      * given symbol.  If none exists, return null.
  1347      * @param t a type
  1348      * @param sym a symbol
  1349      */
  1350     public Type asSuper(Type t, Symbol sym) {
  1351         return asSuper.visit(t, sym);
  1353     // where
  1354         private SimpleVisitor<Type,Symbol> asSuper = new SimpleVisitor<Type,Symbol>() {
  1356             public Type visitType(Type t, Symbol sym) {
  1357                 return null;
  1360             @Override
  1361             public Type visitClassType(ClassType t, Symbol sym) {
  1362                 if (t.tsym == sym)
  1363                     return t;
  1365                 Type st = supertype(t);
  1366                 if (st.tag == CLASS || st.tag == TYPEVAR || st.tag == ERROR) {
  1367                     Type x = asSuper(st, sym);
  1368                     if (x != null)
  1369                         return x;
  1371                 if ((sym.flags() & INTERFACE) != 0) {
  1372                     for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
  1373                         Type x = asSuper(l.head, sym);
  1374                         if (x != null)
  1375                             return x;
  1378                 return null;
  1381             @Override
  1382             public Type visitArrayType(ArrayType t, Symbol sym) {
  1383                 return isSubtype(t, sym.type) ? sym.type : null;
  1386             @Override
  1387             public Type visitTypeVar(TypeVar t, Symbol sym) {
  1388                 if (t.tsym == sym)
  1389                     return t;
  1390                 else
  1391                     return asSuper(t.bound, sym);
  1394             @Override
  1395             public Type visitErrorType(ErrorType t, Symbol sym) {
  1396                 return t;
  1398         };
  1400     /**
  1401      * Return the base type of t or any of its outer types that starts
  1402      * with the given symbol.  If none exists, return null.
  1404      * @param t a type
  1405      * @param sym a symbol
  1406      */
  1407     public Type asOuterSuper(Type t, Symbol sym) {
  1408         switch (t.tag) {
  1409         case CLASS:
  1410             do {
  1411                 Type s = asSuper(t, sym);
  1412                 if (s != null) return s;
  1413                 t = t.getEnclosingType();
  1414             } while (t.tag == CLASS);
  1415             return null;
  1416         case ARRAY:
  1417             return isSubtype(t, sym.type) ? sym.type : null;
  1418         case TYPEVAR:
  1419             return asSuper(t, sym);
  1420         case ERROR:
  1421             return t;
  1422         default:
  1423             return null;
  1427     /**
  1428      * Return the base type of t or any of its enclosing types that
  1429      * starts with the given symbol.  If none exists, return null.
  1431      * @param t a type
  1432      * @param sym a symbol
  1433      */
  1434     public Type asEnclosingSuper(Type t, Symbol sym) {
  1435         switch (t.tag) {
  1436         case CLASS:
  1437             do {
  1438                 Type s = asSuper(t, sym);
  1439                 if (s != null) return s;
  1440                 Type outer = t.getEnclosingType();
  1441                 t = (outer.tag == CLASS) ? outer :
  1442                     (t.tsym.owner.enclClass() != null) ? t.tsym.owner.enclClass().type :
  1443                     Type.noType;
  1444             } while (t.tag == CLASS);
  1445             return null;
  1446         case ARRAY:
  1447             return isSubtype(t, sym.type) ? sym.type : null;
  1448         case TYPEVAR:
  1449             return asSuper(t, sym);
  1450         case ERROR:
  1451             return t;
  1452         default:
  1453             return null;
  1456     // </editor-fold>
  1458     // <editor-fold defaultstate="collapsed" desc="memberType">
  1459     /**
  1460      * The type of given symbol, seen as a member of t.
  1462      * @param t a type
  1463      * @param sym a symbol
  1464      */
  1465     public Type memberType(Type t, Symbol sym) {
  1466         return (sym.flags() & STATIC) != 0
  1467             ? sym.type
  1468             : memberType.visit(t, sym);
  1470     // where
  1471         private SimpleVisitor<Type,Symbol> memberType = new SimpleVisitor<Type,Symbol>() {
  1473             public Type visitType(Type t, Symbol sym) {
  1474                 return sym.type;
  1477             @Override
  1478             public Type visitWildcardType(WildcardType t, Symbol sym) {
  1479                 return memberType(upperBound(t), sym);
  1482             @Override
  1483             public Type visitClassType(ClassType t, Symbol sym) {
  1484                 Symbol owner = sym.owner;
  1485                 long flags = sym.flags();
  1486                 if (((flags & STATIC) == 0) && owner.type.isParameterized()) {
  1487                     Type base = asOuterSuper(t, owner);
  1488                     //if t is an intersection type T = CT & I1 & I2 ... & In
  1489                     //its supertypes CT, I1, ... In might contain wildcards
  1490                     //so we need to go through capture conversion
  1491                     base = t.isCompound() ? capture(base) : base;
  1492                     if (base != null) {
  1493                         List<Type> ownerParams = owner.type.allparams();
  1494                         List<Type> baseParams = base.allparams();
  1495                         if (ownerParams.nonEmpty()) {
  1496                             if (baseParams.isEmpty()) {
  1497                                 // then base is a raw type
  1498                                 return erasure(sym.type);
  1499                             } else {
  1500                                 return subst(sym.type, ownerParams, baseParams);
  1505                 return sym.type;
  1508             @Override
  1509             public Type visitTypeVar(TypeVar t, Symbol sym) {
  1510                 return memberType(t.bound, sym);
  1513             @Override
  1514             public Type visitErrorType(ErrorType t, Symbol sym) {
  1515                 return t;
  1517         };
  1518     // </editor-fold>
  1520     // <editor-fold defaultstate="collapsed" desc="isAssignable">
  1521     public boolean isAssignable(Type t, Type s) {
  1522         return isAssignable(t, s, Warner.noWarnings);
  1525     /**
  1526      * Is t assignable to s?<br>
  1527      * Equivalent to subtype except for constant values and raw
  1528      * types.<br>
  1529      * (not defined for Method and ForAll types)
  1530      */
  1531     public boolean isAssignable(Type t, Type s, Warner warn) {
  1532         if (t.tag == ERROR)
  1533             return true;
  1534         if (t.tag <= INT && t.constValue() != null) {
  1535             int value = ((Number)t.constValue()).intValue();
  1536             switch (s.tag) {
  1537             case BYTE:
  1538                 if (Byte.MIN_VALUE <= value && value <= Byte.MAX_VALUE)
  1539                     return true;
  1540                 break;
  1541             case CHAR:
  1542                 if (Character.MIN_VALUE <= value && value <= Character.MAX_VALUE)
  1543                     return true;
  1544                 break;
  1545             case SHORT:
  1546                 if (Short.MIN_VALUE <= value && value <= Short.MAX_VALUE)
  1547                     return true;
  1548                 break;
  1549             case INT:
  1550                 return true;
  1551             case CLASS:
  1552                 switch (unboxedType(s).tag) {
  1553                 case BYTE:
  1554                 case CHAR:
  1555                 case SHORT:
  1556                     return isAssignable(t, unboxedType(s), warn);
  1558                 break;
  1561         return isConvertible(t, s, warn);
  1563     // </editor-fold>
  1565     // <editor-fold defaultstate="collapsed" desc="erasure">
  1566     /**
  1567      * The erasure of t {@code |t|} -- the type that results when all
  1568      * type parameters in t are deleted.
  1569      */
  1570     public Type erasure(Type t) {
  1571         return erasure(t, false);
  1573     //where
  1574     private Type erasure(Type t, boolean recurse) {
  1575         if (t.tag <= lastBaseTag)
  1576             return t; /* fast special case */
  1577         else
  1578             return erasure.visit(t, recurse);
  1580     // where
  1581         private SimpleVisitor<Type, Boolean> erasure = new SimpleVisitor<Type, Boolean>() {
  1582             public Type visitType(Type t, Boolean recurse) {
  1583                 if (t.tag <= lastBaseTag)
  1584                     return t; /*fast special case*/
  1585                 else
  1586                     return t.map(recurse ? erasureRecFun : erasureFun);
  1589             @Override
  1590             public Type visitWildcardType(WildcardType t, Boolean recurse) {
  1591                 return erasure(upperBound(t), recurse);
  1594             @Override
  1595             public Type visitClassType(ClassType t, Boolean recurse) {
  1596                 Type erased = t.tsym.erasure(Types.this);
  1597                 if (recurse) {
  1598                     erased = new ErasedClassType(erased.getEnclosingType(),erased.tsym);
  1600                 return erased;
  1603             @Override
  1604             public Type visitTypeVar(TypeVar t, Boolean recurse) {
  1605                 return erasure(t.bound, recurse);
  1608             @Override
  1609             public Type visitErrorType(ErrorType t, Boolean recurse) {
  1610                 return t;
  1612         };
  1614     private Mapping erasureFun = new Mapping ("erasure") {
  1615             public Type apply(Type t) { return erasure(t); }
  1616         };
  1618     private Mapping erasureRecFun = new Mapping ("erasureRecursive") {
  1619         public Type apply(Type t) { return erasureRecursive(t); }
  1620     };
  1622     public List<Type> erasure(List<Type> ts) {
  1623         return Type.map(ts, erasureFun);
  1626     public Type erasureRecursive(Type t) {
  1627         return erasure(t, true);
  1630     public List<Type> erasureRecursive(List<Type> ts) {
  1631         return Type.map(ts, erasureRecFun);
  1633     // </editor-fold>
  1635     // <editor-fold defaultstate="collapsed" desc="makeCompoundType">
  1636     /**
  1637      * Make a compound type from non-empty list of types
  1639      * @param bounds            the types from which the compound type is formed
  1640      * @param supertype         is objectType if all bounds are interfaces,
  1641      *                          null otherwise.
  1642      */
  1643     public Type makeCompoundType(List<Type> bounds,
  1644                                  Type supertype) {
  1645         ClassSymbol bc =
  1646             new ClassSymbol(ABSTRACT|PUBLIC|SYNTHETIC|COMPOUND|ACYCLIC,
  1647                             Type.moreInfo
  1648                                 ? names.fromString(bounds.toString())
  1649                                 : names.empty,
  1650                             syms.noSymbol);
  1651         if (bounds.head.tag == TYPEVAR)
  1652             // error condition, recover
  1653                 bc.erasure_field = syms.objectType;
  1654             else
  1655                 bc.erasure_field = erasure(bounds.head);
  1656             bc.members_field = new Scope(bc);
  1657         ClassType bt = (ClassType)bc.type;
  1658         bt.allparams_field = List.nil();
  1659         if (supertype != null) {
  1660             bt.supertype_field = supertype;
  1661             bt.interfaces_field = bounds;
  1662         } else {
  1663             bt.supertype_field = bounds.head;
  1664             bt.interfaces_field = bounds.tail;
  1666         assert bt.supertype_field.tsym.completer != null
  1667             || !bt.supertype_field.isInterface()
  1668             : bt.supertype_field;
  1669         return bt;
  1672     /**
  1673      * Same as {@link #makeCompoundType(List,Type)}, except that the
  1674      * second parameter is computed directly. Note that this might
  1675      * cause a symbol completion.  Hence, this version of
  1676      * makeCompoundType may not be called during a classfile read.
  1677      */
  1678     public Type makeCompoundType(List<Type> bounds) {
  1679         Type supertype = (bounds.head.tsym.flags() & INTERFACE) != 0 ?
  1680             supertype(bounds.head) : null;
  1681         return makeCompoundType(bounds, supertype);
  1684     /**
  1685      * A convenience wrapper for {@link #makeCompoundType(List)}; the
  1686      * arguments are converted to a list and passed to the other
  1687      * method.  Note that this might cause a symbol completion.
  1688      * Hence, this version of makeCompoundType may not be called
  1689      * during a classfile read.
  1690      */
  1691     public Type makeCompoundType(Type bound1, Type bound2) {
  1692         return makeCompoundType(List.of(bound1, bound2));
  1694     // </editor-fold>
  1696     // <editor-fold defaultstate="collapsed" desc="supertype">
  1697     public Type supertype(Type t) {
  1698         return supertype.visit(t);
  1700     // where
  1701         private UnaryVisitor<Type> supertype = new UnaryVisitor<Type>() {
  1703             public Type visitType(Type t, Void ignored) {
  1704                 // A note on wildcards: there is no good way to
  1705                 // determine a supertype for a super bounded wildcard.
  1706                 return null;
  1709             @Override
  1710             public Type visitClassType(ClassType t, Void ignored) {
  1711                 if (t.supertype_field == null) {
  1712                     Type supertype = ((ClassSymbol)t.tsym).getSuperclass();
  1713                     // An interface has no superclass; its supertype is Object.
  1714                     if (t.isInterface())
  1715                         supertype = ((ClassType)t.tsym.type).supertype_field;
  1716                     if (t.supertype_field == null) {
  1717                         List<Type> actuals = classBound(t).allparams();
  1718                         List<Type> formals = t.tsym.type.allparams();
  1719                         if (t.hasErasedSupertypes()) {
  1720                             t.supertype_field = erasureRecursive(supertype);
  1721                         } else if (formals.nonEmpty()) {
  1722                             t.supertype_field = subst(supertype, formals, actuals);
  1724                         else {
  1725                             t.supertype_field = supertype;
  1729                 return t.supertype_field;
  1732             /**
  1733              * The supertype is always a class type. If the type
  1734              * variable's bounds start with a class type, this is also
  1735              * the supertype.  Otherwise, the supertype is
  1736              * java.lang.Object.
  1737              */
  1738             @Override
  1739             public Type visitTypeVar(TypeVar t, Void ignored) {
  1740                 if (t.bound.tag == TYPEVAR ||
  1741                     (!t.bound.isCompound() && !t.bound.isInterface())) {
  1742                     return t.bound;
  1743                 } else {
  1744                     return supertype(t.bound);
  1748             @Override
  1749             public Type visitArrayType(ArrayType t, Void ignored) {
  1750                 if (t.elemtype.isPrimitive() || isSameType(t.elemtype, syms.objectType))
  1751                     return arraySuperType();
  1752                 else
  1753                     return new ArrayType(supertype(t.elemtype), t.tsym);
  1756             @Override
  1757             public Type visitErrorType(ErrorType t, Void ignored) {
  1758                 return t;
  1760         };
  1761     // </editor-fold>
  1763     // <editor-fold defaultstate="collapsed" desc="interfaces">
  1764     /**
  1765      * Return the interfaces implemented by this class.
  1766      */
  1767     public List<Type> interfaces(Type t) {
  1768         return interfaces.visit(t);
  1770     // where
  1771         private UnaryVisitor<List<Type>> interfaces = new UnaryVisitor<List<Type>>() {
  1773             public List<Type> visitType(Type t, Void ignored) {
  1774                 return List.nil();
  1777             @Override
  1778             public List<Type> visitClassType(ClassType t, Void ignored) {
  1779                 if (t.interfaces_field == null) {
  1780                     List<Type> interfaces = ((ClassSymbol)t.tsym).getInterfaces();
  1781                     if (t.interfaces_field == null) {
  1782                         // If t.interfaces_field is null, then t must
  1783                         // be a parameterized type (not to be confused
  1784                         // with a generic type declaration).
  1785                         // Terminology:
  1786                         //    Parameterized type: List<String>
  1787                         //    Generic type declaration: class List<E> { ... }
  1788                         // So t corresponds to List<String> and
  1789                         // t.tsym.type corresponds to List<E>.
  1790                         // The reason t must be parameterized type is
  1791                         // that completion will happen as a side
  1792                         // effect of calling
  1793                         // ClassSymbol.getInterfaces.  Since
  1794                         // t.interfaces_field is null after
  1795                         // completion, we can assume that t is not the
  1796                         // type of a class/interface declaration.
  1797                         assert t != t.tsym.type : t.toString();
  1798                         List<Type> actuals = t.allparams();
  1799                         List<Type> formals = t.tsym.type.allparams();
  1800                         if (t.hasErasedSupertypes()) {
  1801                             t.interfaces_field = erasureRecursive(interfaces);
  1802                         } else if (formals.nonEmpty()) {
  1803                             t.interfaces_field =
  1804                                 upperBounds(subst(interfaces, formals, actuals));
  1806                         else {
  1807                             t.interfaces_field = interfaces;
  1811                 return t.interfaces_field;
  1814             @Override
  1815             public List<Type> visitTypeVar(TypeVar t, Void ignored) {
  1816                 if (t.bound.isCompound())
  1817                     return interfaces(t.bound);
  1819                 if (t.bound.isInterface())
  1820                     return List.of(t.bound);
  1822                 return List.nil();
  1824         };
  1825     // </editor-fold>
  1827     // <editor-fold defaultstate="collapsed" desc="isDerivedRaw">
  1828     Map<Type,Boolean> isDerivedRawCache = new HashMap<Type,Boolean>();
  1830     public boolean isDerivedRaw(Type t) {
  1831         Boolean result = isDerivedRawCache.get(t);
  1832         if (result == null) {
  1833             result = isDerivedRawInternal(t);
  1834             isDerivedRawCache.put(t, result);
  1836         return result;
  1839     public boolean isDerivedRawInternal(Type t) {
  1840         if (t.isErroneous())
  1841             return false;
  1842         return
  1843             t.isRaw() ||
  1844             supertype(t) != null && isDerivedRaw(supertype(t)) ||
  1845             isDerivedRaw(interfaces(t));
  1848     public boolean isDerivedRaw(List<Type> ts) {
  1849         List<Type> l = ts;
  1850         while (l.nonEmpty() && !isDerivedRaw(l.head)) l = l.tail;
  1851         return l.nonEmpty();
  1853     // </editor-fold>
  1855     // <editor-fold defaultstate="collapsed" desc="setBounds">
  1856     /**
  1857      * Set the bounds field of the given type variable to reflect a
  1858      * (possibly multiple) list of bounds.
  1859      * @param t                 a type variable
  1860      * @param bounds            the bounds, must be nonempty
  1861      * @param supertype         is objectType if all bounds are interfaces,
  1862      *                          null otherwise.
  1863      */
  1864     public void setBounds(TypeVar t, List<Type> bounds, Type supertype) {
  1865         if (bounds.tail.isEmpty())
  1866             t.bound = bounds.head;
  1867         else
  1868             t.bound = makeCompoundType(bounds, supertype);
  1869         t.rank_field = -1;
  1872     /**
  1873      * Same as {@link #setBounds(Type.TypeVar,List,Type)}, except that
  1874      * third parameter is computed directly, as follows: if all
  1875      * all bounds are interface types, the computed supertype is Object,
  1876      * otherwise the supertype is simply left null (in this case, the supertype
  1877      * is assumed to be the head of the bound list passed as second argument).
  1878      * Note that this check might cause a symbol completion. Hence, this version of
  1879      * setBounds may not be called during a classfile read.
  1880      */
  1881     public void setBounds(TypeVar t, List<Type> bounds) {
  1882         Type supertype = (bounds.head.tsym.flags() & INTERFACE) != 0 ?
  1883             syms.objectType : null;
  1884         setBounds(t, bounds, supertype);
  1885         t.rank_field = -1;
  1887     // </editor-fold>
  1889     // <editor-fold defaultstate="collapsed" desc="getBounds">
  1890     /**
  1891      * Return list of bounds of the given type variable.
  1892      */
  1893     public List<Type> getBounds(TypeVar t) {
  1894         if (t.bound.isErroneous() || !t.bound.isCompound())
  1895             return List.of(t.bound);
  1896         else if ((erasure(t).tsym.flags() & INTERFACE) == 0)
  1897             return interfaces(t).prepend(supertype(t));
  1898         else
  1899             // No superclass was given in bounds.
  1900             // In this case, supertype is Object, erasure is first interface.
  1901             return interfaces(t);
  1903     // </editor-fold>
  1905     // <editor-fold defaultstate="collapsed" desc="classBound">
  1906     /**
  1907      * If the given type is a (possibly selected) type variable,
  1908      * return the bounding class of this type, otherwise return the
  1909      * type itself.
  1910      */
  1911     public Type classBound(Type t) {
  1912         return classBound.visit(t);
  1914     // where
  1915         private UnaryVisitor<Type> classBound = new UnaryVisitor<Type>() {
  1917             public Type visitType(Type t, Void ignored) {
  1918                 return t;
  1921             @Override
  1922             public Type visitClassType(ClassType t, Void ignored) {
  1923                 Type outer1 = classBound(t.getEnclosingType());
  1924                 if (outer1 != t.getEnclosingType())
  1925                     return new ClassType(outer1, t.getTypeArguments(), t.tsym);
  1926                 else
  1927                     return t;
  1930             @Override
  1931             public Type visitTypeVar(TypeVar t, Void ignored) {
  1932                 return classBound(supertype(t));
  1935             @Override
  1936             public Type visitErrorType(ErrorType t, Void ignored) {
  1937                 return t;
  1939         };
  1940     // </editor-fold>
  1942     // <editor-fold defaultstate="collapsed" desc="sub signature / override equivalence">
  1943     /**
  1944      * Returns true iff the first signature is a <em>sub
  1945      * signature</em> of the other.  This is <b>not</b> an equivalence
  1946      * relation.
  1948      * @see "The Java Language Specification, Third Ed. (8.4.2)."
  1949      * @see #overrideEquivalent(Type t, Type s)
  1950      * @param t first signature (possibly raw).
  1951      * @param s second signature (could be subjected to erasure).
  1952      * @return true if t is a sub signature of s.
  1953      */
  1954     public boolean isSubSignature(Type t, Type s) {
  1955         return hasSameArgs(t, s) || hasSameArgs(t, erasure(s));
  1958     /**
  1959      * Returns true iff these signatures are related by <em>override
  1960      * equivalence</em>.  This is the natural extension of
  1961      * isSubSignature to an equivalence relation.
  1963      * @see "The Java Language Specification, Third Ed. (8.4.2)."
  1964      * @see #isSubSignature(Type t, Type s)
  1965      * @param t a signature (possible raw, could be subjected to
  1966      * erasure).
  1967      * @param s a signature (possible raw, could be subjected to
  1968      * erasure).
  1969      * @return true if either argument is a sub signature of the other.
  1970      */
  1971     public boolean overrideEquivalent(Type t, Type s) {
  1972         return hasSameArgs(t, s) ||
  1973             hasSameArgs(t, erasure(s)) || hasSameArgs(erasure(t), s);
  1976     private WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, MethodSymbol>>> implCache_check =
  1977             new WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, MethodSymbol>>>();
  1979     private WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, MethodSymbol>>> implCache_nocheck =
  1980             new WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, MethodSymbol>>>();
  1982     public MethodSymbol implementation(MethodSymbol ms, TypeSymbol origin, Types types, boolean checkResult) {
  1983         Map<MethodSymbol, SoftReference<Map<TypeSymbol, MethodSymbol>>> implCache = checkResult ?
  1984             implCache_check : implCache_nocheck;
  1985         SoftReference<Map<TypeSymbol, MethodSymbol>> ref_cache = implCache.get(ms);
  1986         Map<TypeSymbol, MethodSymbol> cache = ref_cache != null ? ref_cache.get() : null;
  1987         if (cache == null) {
  1988             cache = new HashMap<TypeSymbol, MethodSymbol>();
  1989             implCache.put(ms, new SoftReference<Map<TypeSymbol, MethodSymbol>>(cache));
  1991         MethodSymbol impl = cache.get(origin);
  1992         if (impl == null) {
  1993             for (Type t = origin.type; t.tag == CLASS || t.tag == TYPEVAR; t = types.supertype(t)) {
  1994                 while (t.tag == TYPEVAR)
  1995                     t = t.getUpperBound();
  1996                 TypeSymbol c = t.tsym;
  1997                 for (Scope.Entry e = c.members().lookup(ms.name);
  1998                      e.scope != null;
  1999                      e = e.next()) {
  2000                     if (e.sym.kind == Kinds.MTH) {
  2001                         MethodSymbol m = (MethodSymbol) e.sym;
  2002                         if (m.overrides(ms, origin, types, checkResult) &&
  2003                             (m.flags() & SYNTHETIC) == 0) {
  2004                             impl = m;
  2005                             cache.put(origin, m);
  2006                             return impl;
  2012         return impl;
  2015     /**
  2016      * Does t have the same arguments as s?  It is assumed that both
  2017      * types are (possibly polymorphic) method types.  Monomorphic
  2018      * method types "have the same arguments", if their argument lists
  2019      * are equal.  Polymorphic method types "have the same arguments",
  2020      * if they have the same arguments after renaming all type
  2021      * variables of one to corresponding type variables in the other,
  2022      * where correspondence is by position in the type parameter list.
  2023      */
  2024     public boolean hasSameArgs(Type t, Type s) {
  2025         return hasSameArgs.visit(t, s);
  2027     // where
  2028         private TypeRelation hasSameArgs = new TypeRelation() {
  2030             public Boolean visitType(Type t, Type s) {
  2031                 throw new AssertionError();
  2034             @Override
  2035             public Boolean visitMethodType(MethodType t, Type s) {
  2036                 return s.tag == METHOD
  2037                     && containsTypeEquivalent(t.argtypes, s.getParameterTypes());
  2040             @Override
  2041             public Boolean visitForAll(ForAll t, Type s) {
  2042                 if (s.tag != FORALL)
  2043                     return false;
  2045                 ForAll forAll = (ForAll)s;
  2046                 return hasSameBounds(t, forAll)
  2047                     && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
  2050             @Override
  2051             public Boolean visitErrorType(ErrorType t, Type s) {
  2052                 return false;
  2054         };
  2055     // </editor-fold>
  2057     // <editor-fold defaultstate="collapsed" desc="subst">
  2058     public List<Type> subst(List<Type> ts,
  2059                             List<Type> from,
  2060                             List<Type> to) {
  2061         return new Subst(from, to).subst(ts);
  2064     /**
  2065      * Substitute all occurrences of a type in `from' with the
  2066      * corresponding type in `to' in 't'. Match lists `from' and `to'
  2067      * from the right: If lists have different length, discard leading
  2068      * elements of the longer list.
  2069      */
  2070     public Type subst(Type t, List<Type> from, List<Type> to) {
  2071         return new Subst(from, to).subst(t);
  2074     private class Subst extends UnaryVisitor<Type> {
  2075         List<Type> from;
  2076         List<Type> to;
  2078         public Subst(List<Type> from, List<Type> to) {
  2079             int fromLength = from.length();
  2080             int toLength = to.length();
  2081             while (fromLength > toLength) {
  2082                 fromLength--;
  2083                 from = from.tail;
  2085             while (fromLength < toLength) {
  2086                 toLength--;
  2087                 to = to.tail;
  2089             this.from = from;
  2090             this.to = to;
  2093         Type subst(Type t) {
  2094             if (from.tail == null)
  2095                 return t;
  2096             else
  2097                 return visit(t);
  2100         List<Type> subst(List<Type> ts) {
  2101             if (from.tail == null)
  2102                 return ts;
  2103             boolean wild = false;
  2104             if (ts.nonEmpty() && from.nonEmpty()) {
  2105                 Type head1 = subst(ts.head);
  2106                 List<Type> tail1 = subst(ts.tail);
  2107                 if (head1 != ts.head || tail1 != ts.tail)
  2108                     return tail1.prepend(head1);
  2110             return ts;
  2113         public Type visitType(Type t, Void ignored) {
  2114             return t;
  2117         @Override
  2118         public Type visitMethodType(MethodType t, Void ignored) {
  2119             List<Type> argtypes = subst(t.argtypes);
  2120             Type restype = subst(t.restype);
  2121             List<Type> thrown = subst(t.thrown);
  2122             if (argtypes == t.argtypes &&
  2123                 restype == t.restype &&
  2124                 thrown == t.thrown)
  2125                 return t;
  2126             else
  2127                 return new MethodType(argtypes, restype, thrown, t.tsym);
  2130         @Override
  2131         public Type visitTypeVar(TypeVar t, Void ignored) {
  2132             for (List<Type> from = this.from, to = this.to;
  2133                  from.nonEmpty();
  2134                  from = from.tail, to = to.tail) {
  2135                 if (t == from.head) {
  2136                     return to.head.withTypeVar(t);
  2139             return t;
  2142         @Override
  2143         public Type visitClassType(ClassType t, Void ignored) {
  2144             if (!t.isCompound()) {
  2145                 List<Type> typarams = t.getTypeArguments();
  2146                 List<Type> typarams1 = subst(typarams);
  2147                 Type outer = t.getEnclosingType();
  2148                 Type outer1 = subst(outer);
  2149                 if (typarams1 == typarams && outer1 == outer)
  2150                     return t;
  2151                 else
  2152                     return new ClassType(outer1, typarams1, t.tsym);
  2153             } else {
  2154                 Type st = subst(supertype(t));
  2155                 List<Type> is = upperBounds(subst(interfaces(t)));
  2156                 if (st == supertype(t) && is == interfaces(t))
  2157                     return t;
  2158                 else
  2159                     return makeCompoundType(is.prepend(st));
  2163         @Override
  2164         public Type visitWildcardType(WildcardType t, Void ignored) {
  2165             Type bound = t.type;
  2166             if (t.kind != BoundKind.UNBOUND)
  2167                 bound = subst(bound);
  2168             if (bound == t.type) {
  2169                 return t;
  2170             } else {
  2171                 if (t.isExtendsBound() && bound.isExtendsBound())
  2172                     bound = upperBound(bound);
  2173                 return new WildcardType(bound, t.kind, syms.boundClass, t.bound);
  2177         @Override
  2178         public Type visitArrayType(ArrayType t, Void ignored) {
  2179             Type elemtype = subst(t.elemtype);
  2180             if (elemtype == t.elemtype)
  2181                 return t;
  2182             else
  2183                 return new ArrayType(upperBound(elemtype), t.tsym);
  2186         @Override
  2187         public Type visitForAll(ForAll t, Void ignored) {
  2188             List<Type> tvars1 = substBounds(t.tvars, from, to);
  2189             Type qtype1 = subst(t.qtype);
  2190             if (tvars1 == t.tvars && qtype1 == t.qtype) {
  2191                 return t;
  2192             } else if (tvars1 == t.tvars) {
  2193                 return new ForAll(tvars1, qtype1);
  2194             } else {
  2195                 return new ForAll(tvars1, Types.this.subst(qtype1, t.tvars, tvars1));
  2199         @Override
  2200         public Type visitErrorType(ErrorType t, Void ignored) {
  2201             return t;
  2205     public List<Type> substBounds(List<Type> tvars,
  2206                                   List<Type> from,
  2207                                   List<Type> to) {
  2208         if (tvars.isEmpty())
  2209             return tvars;
  2210         ListBuffer<Type> newBoundsBuf = lb();
  2211         boolean changed = false;
  2212         // calculate new bounds
  2213         for (Type t : tvars) {
  2214             TypeVar tv = (TypeVar) t;
  2215             Type bound = subst(tv.bound, from, to);
  2216             if (bound != tv.bound)
  2217                 changed = true;
  2218             newBoundsBuf.append(bound);
  2220         if (!changed)
  2221             return tvars;
  2222         ListBuffer<Type> newTvars = lb();
  2223         // create new type variables without bounds
  2224         for (Type t : tvars) {
  2225             newTvars.append(new TypeVar(t.tsym, null, syms.botType));
  2227         // the new bounds should use the new type variables in place
  2228         // of the old
  2229         List<Type> newBounds = newBoundsBuf.toList();
  2230         from = tvars;
  2231         to = newTvars.toList();
  2232         for (; !newBounds.isEmpty(); newBounds = newBounds.tail) {
  2233             newBounds.head = subst(newBounds.head, from, to);
  2235         newBounds = newBoundsBuf.toList();
  2236         // set the bounds of new type variables to the new bounds
  2237         for (Type t : newTvars.toList()) {
  2238             TypeVar tv = (TypeVar) t;
  2239             tv.bound = newBounds.head;
  2240             newBounds = newBounds.tail;
  2242         return newTvars.toList();
  2245     public TypeVar substBound(TypeVar t, List<Type> from, List<Type> to) {
  2246         Type bound1 = subst(t.bound, from, to);
  2247         if (bound1 == t.bound)
  2248             return t;
  2249         else {
  2250             // create new type variable without bounds
  2251             TypeVar tv = new TypeVar(t.tsym, null, syms.botType);
  2252             // the new bound should use the new type variable in place
  2253             // of the old
  2254             tv.bound = subst(bound1, List.<Type>of(t), List.<Type>of(tv));
  2255             return tv;
  2258     // </editor-fold>
  2260     // <editor-fold defaultstate="collapsed" desc="hasSameBounds">
  2261     /**
  2262      * Does t have the same bounds for quantified variables as s?
  2263      */
  2264     boolean hasSameBounds(ForAll t, ForAll s) {
  2265         List<Type> l1 = t.tvars;
  2266         List<Type> l2 = s.tvars;
  2267         while (l1.nonEmpty() && l2.nonEmpty() &&
  2268                isSameType(l1.head.getUpperBound(),
  2269                           subst(l2.head.getUpperBound(),
  2270                                 s.tvars,
  2271                                 t.tvars))) {
  2272             l1 = l1.tail;
  2273             l2 = l2.tail;
  2275         return l1.isEmpty() && l2.isEmpty();
  2277     // </editor-fold>
  2279     // <editor-fold defaultstate="collapsed" desc="newInstances">
  2280     /** Create new vector of type variables from list of variables
  2281      *  changing all recursive bounds from old to new list.
  2282      */
  2283     public List<Type> newInstances(List<Type> tvars) {
  2284         List<Type> tvars1 = Type.map(tvars, newInstanceFun);
  2285         for (List<Type> l = tvars1; l.nonEmpty(); l = l.tail) {
  2286             TypeVar tv = (TypeVar) l.head;
  2287             tv.bound = subst(tv.bound, tvars, tvars1);
  2289         return tvars1;
  2291     static private Mapping newInstanceFun = new Mapping("newInstanceFun") {
  2292             public Type apply(Type t) { return new TypeVar(t.tsym, t.getUpperBound(), t.getLowerBound()); }
  2293         };
  2294     // </editor-fold>
  2296     // <editor-fold defaultstate="collapsed" desc="createErrorType">
  2297     public Type createErrorType(Type originalType) {
  2298         return new ErrorType(originalType, syms.errSymbol);
  2301     public Type createErrorType(ClassSymbol c, Type originalType) {
  2302         return new ErrorType(c, originalType);
  2305     public Type createErrorType(Name name, TypeSymbol container, Type originalType) {
  2306         return new ErrorType(name, container, originalType);
  2308     // </editor-fold>
  2310     // <editor-fold defaultstate="collapsed" desc="rank">
  2311     /**
  2312      * The rank of a class is the length of the longest path between
  2313      * the class and java.lang.Object in the class inheritance
  2314      * graph. Undefined for all but reference types.
  2315      */
  2316     public int rank(Type t) {
  2317         switch(t.tag) {
  2318         case CLASS: {
  2319             ClassType cls = (ClassType)t;
  2320             if (cls.rank_field < 0) {
  2321                 Name fullname = cls.tsym.getQualifiedName();
  2322                 if (fullname == names.java_lang_Object)
  2323                     cls.rank_field = 0;
  2324                 else {
  2325                     int r = rank(supertype(cls));
  2326                     for (List<Type> l = interfaces(cls);
  2327                          l.nonEmpty();
  2328                          l = l.tail) {
  2329                         if (rank(l.head) > r)
  2330                             r = rank(l.head);
  2332                     cls.rank_field = r + 1;
  2335             return cls.rank_field;
  2337         case TYPEVAR: {
  2338             TypeVar tvar = (TypeVar)t;
  2339             if (tvar.rank_field < 0) {
  2340                 int r = rank(supertype(tvar));
  2341                 for (List<Type> l = interfaces(tvar);
  2342                      l.nonEmpty();
  2343                      l = l.tail) {
  2344                     if (rank(l.head) > r) r = rank(l.head);
  2346                 tvar.rank_field = r + 1;
  2348             return tvar.rank_field;
  2350         case ERROR:
  2351             return 0;
  2352         default:
  2353             throw new AssertionError();
  2356     // </editor-fold>
  2358     /**
  2359      * Helper method for generating a string representation of a given type
  2360      * accordingly to a given locale
  2361      */
  2362     public String toString(Type t, Locale locale) {
  2363         return Printer.createStandardPrinter(messages).visit(t, locale);
  2366     /**
  2367      * Helper method for generating a string representation of a given type
  2368      * accordingly to a given locale
  2369      */
  2370     public String toString(Symbol t, Locale locale) {
  2371         return Printer.createStandardPrinter(messages).visit(t, locale);
  2374     // <editor-fold defaultstate="collapsed" desc="toString">
  2375     /**
  2376      * This toString is slightly more descriptive than the one on Type.
  2378      * @deprecated Types.toString(Type t, Locale l) provides better support
  2379      * for localization
  2380      */
  2381     @Deprecated
  2382     public String toString(Type t) {
  2383         if (t.tag == FORALL) {
  2384             ForAll forAll = (ForAll)t;
  2385             return typaramsString(forAll.tvars) + forAll.qtype;
  2387         return "" + t;
  2389     // where
  2390         private String typaramsString(List<Type> tvars) {
  2391             StringBuffer s = new StringBuffer();
  2392             s.append('<');
  2393             boolean first = true;
  2394             for (Type t : tvars) {
  2395                 if (!first) s.append(", ");
  2396                 first = false;
  2397                 appendTyparamString(((TypeVar)t), s);
  2399             s.append('>');
  2400             return s.toString();
  2402         private void appendTyparamString(TypeVar t, StringBuffer buf) {
  2403             buf.append(t);
  2404             if (t.bound == null ||
  2405                 t.bound.tsym.getQualifiedName() == names.java_lang_Object)
  2406                 return;
  2407             buf.append(" extends "); // Java syntax; no need for i18n
  2408             Type bound = t.bound;
  2409             if (!bound.isCompound()) {
  2410                 buf.append(bound);
  2411             } else if ((erasure(t).tsym.flags() & INTERFACE) == 0) {
  2412                 buf.append(supertype(t));
  2413                 for (Type intf : interfaces(t)) {
  2414                     buf.append('&');
  2415                     buf.append(intf);
  2417             } else {
  2418                 // No superclass was given in bounds.
  2419                 // In this case, supertype is Object, erasure is first interface.
  2420                 boolean first = true;
  2421                 for (Type intf : interfaces(t)) {
  2422                     if (!first) buf.append('&');
  2423                     first = false;
  2424                     buf.append(intf);
  2428     // </editor-fold>
  2430     // <editor-fold defaultstate="collapsed" desc="Determining least upper bounds of types">
  2431     /**
  2432      * A cache for closures.
  2434      * <p>A closure is a list of all the supertypes and interfaces of
  2435      * a class or interface type, ordered by ClassSymbol.precedes
  2436      * (that is, subclasses come first, arbitrary but fixed
  2437      * otherwise).
  2438      */
  2439     private Map<Type,List<Type>> closureCache = new HashMap<Type,List<Type>>();
  2441     /**
  2442      * Returns the closure of a class or interface type.
  2443      */
  2444     public List<Type> closure(Type t) {
  2445         List<Type> cl = closureCache.get(t);
  2446         if (cl == null) {
  2447             Type st = supertype(t);
  2448             if (!t.isCompound()) {
  2449                 if (st.tag == CLASS) {
  2450                     cl = insert(closure(st), t);
  2451                 } else if (st.tag == TYPEVAR) {
  2452                     cl = closure(st).prepend(t);
  2453                 } else {
  2454                     cl = List.of(t);
  2456             } else {
  2457                 cl = closure(supertype(t));
  2459             for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail)
  2460                 cl = union(cl, closure(l.head));
  2461             closureCache.put(t, cl);
  2463         return cl;
  2466     /**
  2467      * Insert a type in a closure
  2468      */
  2469     public List<Type> insert(List<Type> cl, Type t) {
  2470         if (cl.isEmpty() || t.tsym.precedes(cl.head.tsym, this)) {
  2471             return cl.prepend(t);
  2472         } else if (cl.head.tsym.precedes(t.tsym, this)) {
  2473             return insert(cl.tail, t).prepend(cl.head);
  2474         } else {
  2475             return cl;
  2479     /**
  2480      * Form the union of two closures
  2481      */
  2482     public List<Type> union(List<Type> cl1, List<Type> cl2) {
  2483         if (cl1.isEmpty()) {
  2484             return cl2;
  2485         } else if (cl2.isEmpty()) {
  2486             return cl1;
  2487         } else if (cl1.head.tsym.precedes(cl2.head.tsym, this)) {
  2488             return union(cl1.tail, cl2).prepend(cl1.head);
  2489         } else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) {
  2490             return union(cl1, cl2.tail).prepend(cl2.head);
  2491         } else {
  2492             return union(cl1.tail, cl2.tail).prepend(cl1.head);
  2496     /**
  2497      * Intersect two closures
  2498      */
  2499     public List<Type> intersect(List<Type> cl1, List<Type> cl2) {
  2500         if (cl1 == cl2)
  2501             return cl1;
  2502         if (cl1.isEmpty() || cl2.isEmpty())
  2503             return List.nil();
  2504         if (cl1.head.tsym.precedes(cl2.head.tsym, this))
  2505             return intersect(cl1.tail, cl2);
  2506         if (cl2.head.tsym.precedes(cl1.head.tsym, this))
  2507             return intersect(cl1, cl2.tail);
  2508         if (isSameType(cl1.head, cl2.head))
  2509             return intersect(cl1.tail, cl2.tail).prepend(cl1.head);
  2510         if (cl1.head.tsym == cl2.head.tsym &&
  2511             cl1.head.tag == CLASS && cl2.head.tag == CLASS) {
  2512             if (cl1.head.isParameterized() && cl2.head.isParameterized()) {
  2513                 Type merge = merge(cl1.head,cl2.head);
  2514                 return intersect(cl1.tail, cl2.tail).prepend(merge);
  2516             if (cl1.head.isRaw() || cl2.head.isRaw())
  2517                 return intersect(cl1.tail, cl2.tail).prepend(erasure(cl1.head));
  2519         return intersect(cl1.tail, cl2.tail);
  2521     // where
  2522         class TypePair {
  2523             final Type t1;
  2524             final Type t2;
  2525             TypePair(Type t1, Type t2) {
  2526                 this.t1 = t1;
  2527                 this.t2 = t2;
  2529             @Override
  2530             public int hashCode() {
  2531                 return 127 * Types.hashCode(t1) + Types.hashCode(t2);
  2533             @Override
  2534             public boolean equals(Object obj) {
  2535                 if (!(obj instanceof TypePair))
  2536                     return false;
  2537                 TypePair typePair = (TypePair)obj;
  2538                 return isSameType(t1, typePair.t1)
  2539                     && isSameType(t2, typePair.t2);
  2542         Set<TypePair> mergeCache = new HashSet<TypePair>();
  2543         private Type merge(Type c1, Type c2) {
  2544             ClassType class1 = (ClassType) c1;
  2545             List<Type> act1 = class1.getTypeArguments();
  2546             ClassType class2 = (ClassType) c2;
  2547             List<Type> act2 = class2.getTypeArguments();
  2548             ListBuffer<Type> merged = new ListBuffer<Type>();
  2549             List<Type> typarams = class1.tsym.type.getTypeArguments();
  2551             while (act1.nonEmpty() && act2.nonEmpty() && typarams.nonEmpty()) {
  2552                 if (containsType(act1.head, act2.head)) {
  2553                     merged.append(act1.head);
  2554                 } else if (containsType(act2.head, act1.head)) {
  2555                     merged.append(act2.head);
  2556                 } else {
  2557                     TypePair pair = new TypePair(c1, c2);
  2558                     Type m;
  2559                     if (mergeCache.add(pair)) {
  2560                         m = new WildcardType(lub(upperBound(act1.head),
  2561                                                  upperBound(act2.head)),
  2562                                              BoundKind.EXTENDS,
  2563                                              syms.boundClass);
  2564                         mergeCache.remove(pair);
  2565                     } else {
  2566                         m = new WildcardType(syms.objectType,
  2567                                              BoundKind.UNBOUND,
  2568                                              syms.boundClass);
  2570                     merged.append(m.withTypeVar(typarams.head));
  2572                 act1 = act1.tail;
  2573                 act2 = act2.tail;
  2574                 typarams = typarams.tail;
  2576             assert(act1.isEmpty() && act2.isEmpty() && typarams.isEmpty());
  2577             return new ClassType(class1.getEnclosingType(), merged.toList(), class1.tsym);
  2580     /**
  2581      * Return the minimum type of a closure, a compound type if no
  2582      * unique minimum exists.
  2583      */
  2584     private Type compoundMin(List<Type> cl) {
  2585         if (cl.isEmpty()) return syms.objectType;
  2586         List<Type> compound = closureMin(cl);
  2587         if (compound.isEmpty())
  2588             return null;
  2589         else if (compound.tail.isEmpty())
  2590             return compound.head;
  2591         else
  2592             return makeCompoundType(compound);
  2595     /**
  2596      * Return the minimum types of a closure, suitable for computing
  2597      * compoundMin or glb.
  2598      */
  2599     private List<Type> closureMin(List<Type> cl) {
  2600         ListBuffer<Type> classes = lb();
  2601         ListBuffer<Type> interfaces = lb();
  2602         while (!cl.isEmpty()) {
  2603             Type current = cl.head;
  2604             if (current.isInterface())
  2605                 interfaces.append(current);
  2606             else
  2607                 classes.append(current);
  2608             ListBuffer<Type> candidates = lb();
  2609             for (Type t : cl.tail) {
  2610                 if (!isSubtypeNoCapture(current, t))
  2611                     candidates.append(t);
  2613             cl = candidates.toList();
  2615         return classes.appendList(interfaces).toList();
  2618     /**
  2619      * Return the least upper bound of pair of types.  if the lub does
  2620      * not exist return null.
  2621      */
  2622     public Type lub(Type t1, Type t2) {
  2623         return lub(List.of(t1, t2));
  2626     /**
  2627      * Return the least upper bound (lub) of set of types.  If the lub
  2628      * does not exist return the type of null (bottom).
  2629      */
  2630     public Type lub(List<Type> ts) {
  2631         final int ARRAY_BOUND = 1;
  2632         final int CLASS_BOUND = 2;
  2633         int boundkind = 0;
  2634         for (Type t : ts) {
  2635             switch (t.tag) {
  2636             case CLASS:
  2637                 boundkind |= CLASS_BOUND;
  2638                 break;
  2639             case ARRAY:
  2640                 boundkind |= ARRAY_BOUND;
  2641                 break;
  2642             case  TYPEVAR:
  2643                 do {
  2644                     t = t.getUpperBound();
  2645                 } while (t.tag == TYPEVAR);
  2646                 if (t.tag == ARRAY) {
  2647                     boundkind |= ARRAY_BOUND;
  2648                 } else {
  2649                     boundkind |= CLASS_BOUND;
  2651                 break;
  2652             default:
  2653                 if (t.isPrimitive())
  2654                     return syms.errType;
  2657         switch (boundkind) {
  2658         case 0:
  2659             return syms.botType;
  2661         case ARRAY_BOUND:
  2662             // calculate lub(A[], B[])
  2663             List<Type> elements = Type.map(ts, elemTypeFun);
  2664             for (Type t : elements) {
  2665                 if (t.isPrimitive()) {
  2666                     // if a primitive type is found, then return
  2667                     // arraySuperType unless all the types are the
  2668                     // same
  2669                     Type first = ts.head;
  2670                     for (Type s : ts.tail) {
  2671                         if (!isSameType(first, s)) {
  2672                              // lub(int[], B[]) is Cloneable & Serializable
  2673                             return arraySuperType();
  2676                     // all the array types are the same, return one
  2677                     // lub(int[], int[]) is int[]
  2678                     return first;
  2681             // lub(A[], B[]) is lub(A, B)[]
  2682             return new ArrayType(lub(elements), syms.arrayClass);
  2684         case CLASS_BOUND:
  2685             // calculate lub(A, B)
  2686             while (ts.head.tag != CLASS && ts.head.tag != TYPEVAR)
  2687                 ts = ts.tail;
  2688             assert !ts.isEmpty();
  2689             List<Type> cl = closure(ts.head);
  2690             for (Type t : ts.tail) {
  2691                 if (t.tag == CLASS || t.tag == TYPEVAR)
  2692                     cl = intersect(cl, closure(t));
  2694             return compoundMin(cl);
  2696         default:
  2697             // calculate lub(A, B[])
  2698             List<Type> classes = List.of(arraySuperType());
  2699             for (Type t : ts) {
  2700                 if (t.tag != ARRAY) // Filter out any arrays
  2701                     classes = classes.prepend(t);
  2703             // lub(A, B[]) is lub(A, arraySuperType)
  2704             return lub(classes);
  2707     // where
  2708         private Type arraySuperType = null;
  2709         private Type arraySuperType() {
  2710             // initialized lazily to avoid problems during compiler startup
  2711             if (arraySuperType == null) {
  2712                 synchronized (this) {
  2713                     if (arraySuperType == null) {
  2714                         // JLS 10.8: all arrays implement Cloneable and Serializable.
  2715                         arraySuperType = makeCompoundType(List.of(syms.serializableType,
  2716                                                                   syms.cloneableType),
  2717                                                           syms.objectType);
  2721             return arraySuperType;
  2723     // </editor-fold>
  2725     // <editor-fold defaultstate="collapsed" desc="Greatest lower bound">
  2726     public Type glb(List<Type> ts) {
  2727         Type t1 = ts.head;
  2728         for (Type t2 : ts.tail) {
  2729             if (t1.isErroneous())
  2730                 return t1;
  2731             t1 = glb(t1, t2);
  2733         return t1;
  2735     //where
  2736     public Type glb(Type t, Type s) {
  2737         if (s == null)
  2738             return t;
  2739         else if (isSubtypeNoCapture(t, s))
  2740             return t;
  2741         else if (isSubtypeNoCapture(s, t))
  2742             return s;
  2744         List<Type> closure = union(closure(t), closure(s));
  2745         List<Type> bounds = closureMin(closure);
  2747         if (bounds.isEmpty()) {             // length == 0
  2748             return syms.objectType;
  2749         } else if (bounds.tail.isEmpty()) { // length == 1
  2750             return bounds.head;
  2751         } else {                            // length > 1
  2752             int classCount = 0;
  2753             for (Type bound : bounds)
  2754                 if (!bound.isInterface())
  2755                     classCount++;
  2756             if (classCount > 1)
  2757                 return createErrorType(t);
  2759         return makeCompoundType(bounds);
  2761     // </editor-fold>
  2763     // <editor-fold defaultstate="collapsed" desc="hashCode">
  2764     /**
  2765      * Compute a hash code on a type.
  2766      */
  2767     public static int hashCode(Type t) {
  2768         return hashCode.visit(t);
  2770     // where
  2771         private static final UnaryVisitor<Integer> hashCode = new UnaryVisitor<Integer>() {
  2773             public Integer visitType(Type t, Void ignored) {
  2774                 return t.tag;
  2777             @Override
  2778             public Integer visitClassType(ClassType t, Void ignored) {
  2779                 int result = visit(t.getEnclosingType());
  2780                 result *= 127;
  2781                 result += t.tsym.flatName().hashCode();
  2782                 for (Type s : t.getTypeArguments()) {
  2783                     result *= 127;
  2784                     result += visit(s);
  2786                 return result;
  2789             @Override
  2790             public Integer visitWildcardType(WildcardType t, Void ignored) {
  2791                 int result = t.kind.hashCode();
  2792                 if (t.type != null) {
  2793                     result *= 127;
  2794                     result += visit(t.type);
  2796                 return result;
  2799             @Override
  2800             public Integer visitArrayType(ArrayType t, Void ignored) {
  2801                 return visit(t.elemtype) + 12;
  2804             @Override
  2805             public Integer visitTypeVar(TypeVar t, Void ignored) {
  2806                 return System.identityHashCode(t.tsym);
  2809             @Override
  2810             public Integer visitUndetVar(UndetVar t, Void ignored) {
  2811                 return System.identityHashCode(t);
  2814             @Override
  2815             public Integer visitErrorType(ErrorType t, Void ignored) {
  2816                 return 0;
  2818         };
  2819     // </editor-fold>
  2821     // <editor-fold defaultstate="collapsed" desc="Return-Type-Substitutable">
  2822     /**
  2823      * Does t have a result that is a subtype of the result type of s,
  2824      * suitable for covariant returns?  It is assumed that both types
  2825      * are (possibly polymorphic) method types.  Monomorphic method
  2826      * types are handled in the obvious way.  Polymorphic method types
  2827      * require renaming all type variables of one to corresponding
  2828      * type variables in the other, where correspondence is by
  2829      * position in the type parameter list. */
  2830     public boolean resultSubtype(Type t, Type s, Warner warner) {
  2831         List<Type> tvars = t.getTypeArguments();
  2832         List<Type> svars = s.getTypeArguments();
  2833         Type tres = t.getReturnType();
  2834         Type sres = subst(s.getReturnType(), svars, tvars);
  2835         return covariantReturnType(tres, sres, warner);
  2838     /**
  2839      * Return-Type-Substitutable.
  2840      * @see <a href="http://java.sun.com/docs/books/jls/">The Java
  2841      * Language Specification, Third Ed. (8.4.5)</a>
  2842      */
  2843     public boolean returnTypeSubstitutable(Type r1, Type r2) {
  2844         if (hasSameArgs(r1, r2))
  2845             return resultSubtype(r1, r2, Warner.noWarnings);
  2846         else
  2847             return covariantReturnType(r1.getReturnType(),
  2848                                        erasure(r2.getReturnType()),
  2849                                        Warner.noWarnings);
  2852     public boolean returnTypeSubstitutable(Type r1,
  2853                                            Type r2, Type r2res,
  2854                                            Warner warner) {
  2855         if (isSameType(r1.getReturnType(), r2res))
  2856             return true;
  2857         if (r1.getReturnType().isPrimitive() || r2res.isPrimitive())
  2858             return false;
  2860         if (hasSameArgs(r1, r2))
  2861             return covariantReturnType(r1.getReturnType(), r2res, warner);
  2862         if (!source.allowCovariantReturns())
  2863             return false;
  2864         if (isSubtypeUnchecked(r1.getReturnType(), r2res, warner))
  2865             return true;
  2866         if (!isSubtype(r1.getReturnType(), erasure(r2res)))
  2867             return false;
  2868         warner.warnUnchecked();
  2869         return true;
  2872     /**
  2873      * Is t an appropriate return type in an overrider for a
  2874      * method that returns s?
  2875      */
  2876     public boolean covariantReturnType(Type t, Type s, Warner warner) {
  2877         return
  2878             isSameType(t, s) ||
  2879             source.allowCovariantReturns() &&
  2880             !t.isPrimitive() &&
  2881             !s.isPrimitive() &&
  2882             isAssignable(t, s, warner);
  2884     // </editor-fold>
  2886     // <editor-fold defaultstate="collapsed" desc="Box/unbox support">
  2887     /**
  2888      * Return the class that boxes the given primitive.
  2889      */
  2890     public ClassSymbol boxedClass(Type t) {
  2891         return reader.enterClass(syms.boxedName[t.tag]);
  2894     /**
  2895      * Return the primitive type corresponding to a boxed type.
  2896      */
  2897     public Type unboxedType(Type t) {
  2898         if (allowBoxing) {
  2899             for (int i=0; i<syms.boxedName.length; i++) {
  2900                 Name box = syms.boxedName[i];
  2901                 if (box != null &&
  2902                     asSuper(t, reader.enterClass(box)) != null)
  2903                     return syms.typeOfTag[i];
  2906         return Type.noType;
  2908     // </editor-fold>
  2910     // <editor-fold defaultstate="collapsed" desc="Capture conversion">
  2911     /*
  2912      * JLS 3rd Ed. 5.1.10 Capture Conversion:
  2914      * Let G name a generic type declaration with n formal type
  2915      * parameters A1 ... An with corresponding bounds U1 ... Un. There
  2916      * exists a capture conversion from G<T1 ... Tn> to G<S1 ... Sn>,
  2917      * where, for 1 <= i <= n:
  2919      * + If Ti is a wildcard type argument (4.5.1) of the form ? then
  2920      *   Si is a fresh type variable whose upper bound is
  2921      *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is the null
  2922      *   type.
  2924      * + If Ti is a wildcard type argument of the form ? extends Bi,
  2925      *   then Si is a fresh type variable whose upper bound is
  2926      *   glb(Bi, Ui[A1 := S1, ..., An := Sn]) and whose lower bound is
  2927      *   the null type, where glb(V1,... ,Vm) is V1 & ... & Vm. It is
  2928      *   a compile-time error if for any two classes (not interfaces)
  2929      *   Vi and Vj,Vi is not a subclass of Vj or vice versa.
  2931      * + If Ti is a wildcard type argument of the form ? super Bi,
  2932      *   then Si is a fresh type variable whose upper bound is
  2933      *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is Bi.
  2935      * + Otherwise, Si = Ti.
  2937      * Capture conversion on any type other than a parameterized type
  2938      * (4.5) acts as an identity conversion (5.1.1). Capture
  2939      * conversions never require a special action at run time and
  2940      * therefore never throw an exception at run time.
  2942      * Capture conversion is not applied recursively.
  2943      */
  2944     /**
  2945      * Capture conversion as specified by JLS 3rd Ed.
  2946      */
  2948     public List<Type> capture(List<Type> ts) {
  2949         List<Type> buf = List.nil();
  2950         for (Type t : ts) {
  2951             buf = buf.prepend(capture(t));
  2953         return buf.reverse();
  2955     public Type capture(Type t) {
  2956         if (t.tag != CLASS)
  2957             return t;
  2958         if (t.getEnclosingType() != Type.noType) {
  2959             Type capturedEncl = capture(t.getEnclosingType());
  2960             if (capturedEncl != t.getEnclosingType()) {
  2961                 Type type1 = memberType(capturedEncl, t.tsym);
  2962                 t = subst(type1, t.tsym.type.getTypeArguments(), t.getTypeArguments());
  2965         ClassType cls = (ClassType)t;
  2966         if (cls.isRaw() || !cls.isParameterized())
  2967             return cls;
  2969         ClassType G = (ClassType)cls.asElement().asType();
  2970         List<Type> A = G.getTypeArguments();
  2971         List<Type> T = cls.getTypeArguments();
  2972         List<Type> S = freshTypeVariables(T);
  2974         List<Type> currentA = A;
  2975         List<Type> currentT = T;
  2976         List<Type> currentS = S;
  2977         boolean captured = false;
  2978         while (!currentA.isEmpty() &&
  2979                !currentT.isEmpty() &&
  2980                !currentS.isEmpty()) {
  2981             if (currentS.head != currentT.head) {
  2982                 captured = true;
  2983                 WildcardType Ti = (WildcardType)currentT.head;
  2984                 Type Ui = currentA.head.getUpperBound();
  2985                 CapturedType Si = (CapturedType)currentS.head;
  2986                 if (Ui == null)
  2987                     Ui = syms.objectType;
  2988                 switch (Ti.kind) {
  2989                 case UNBOUND:
  2990                     Si.bound = subst(Ui, A, S);
  2991                     Si.lower = syms.botType;
  2992                     break;
  2993                 case EXTENDS:
  2994                     Si.bound = glb(Ti.getExtendsBound(), subst(Ui, A, S));
  2995                     Si.lower = syms.botType;
  2996                     break;
  2997                 case SUPER:
  2998                     Si.bound = subst(Ui, A, S);
  2999                     Si.lower = Ti.getSuperBound();
  3000                     break;
  3002                 if (Si.bound == Si.lower)
  3003                     currentS.head = Si.bound;
  3005             currentA = currentA.tail;
  3006             currentT = currentT.tail;
  3007             currentS = currentS.tail;
  3009         if (!currentA.isEmpty() || !currentT.isEmpty() || !currentS.isEmpty())
  3010             return erasure(t); // some "rare" type involved
  3012         if (captured)
  3013             return new ClassType(cls.getEnclosingType(), S, cls.tsym);
  3014         else
  3015             return t;
  3017     // where
  3018         public List<Type> freshTypeVariables(List<Type> types) {
  3019             ListBuffer<Type> result = lb();
  3020             for (Type t : types) {
  3021                 if (t.tag == WILDCARD) {
  3022                     Type bound = ((WildcardType)t).getExtendsBound();
  3023                     if (bound == null)
  3024                         bound = syms.objectType;
  3025                     result.append(new CapturedType(capturedName,
  3026                                                    syms.noSymbol,
  3027                                                    bound,
  3028                                                    syms.botType,
  3029                                                    (WildcardType)t));
  3030                 } else {
  3031                     result.append(t);
  3034             return result.toList();
  3036     // </editor-fold>
  3038     // <editor-fold defaultstate="collapsed" desc="Internal utility methods">
  3039     private List<Type> upperBounds(List<Type> ss) {
  3040         if (ss.isEmpty()) return ss;
  3041         Type head = upperBound(ss.head);
  3042         List<Type> tail = upperBounds(ss.tail);
  3043         if (head != ss.head || tail != ss.tail)
  3044             return tail.prepend(head);
  3045         else
  3046             return ss;
  3049     private boolean sideCast(Type from, Type to, Warner warn) {
  3050         // We are casting from type $from$ to type $to$, which are
  3051         // non-final unrelated types.  This method
  3052         // tries to reject a cast by transferring type parameters
  3053         // from $to$ to $from$ by common superinterfaces.
  3054         boolean reverse = false;
  3055         Type target = to;
  3056         if ((to.tsym.flags() & INTERFACE) == 0) {
  3057             assert (from.tsym.flags() & INTERFACE) != 0;
  3058             reverse = true;
  3059             to = from;
  3060             from = target;
  3062         List<Type> commonSupers = superClosure(to, erasure(from));
  3063         boolean giveWarning = commonSupers.isEmpty();
  3064         // The arguments to the supers could be unified here to
  3065         // get a more accurate analysis
  3066         while (commonSupers.nonEmpty()) {
  3067             Type t1 = asSuper(from, commonSupers.head.tsym);
  3068             Type t2 = commonSupers.head; // same as asSuper(to, commonSupers.head.tsym);
  3069             if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
  3070                 return false;
  3071             giveWarning = giveWarning || (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2));
  3072             commonSupers = commonSupers.tail;
  3074         if (giveWarning && !isReifiable(reverse ? from : to))
  3075             warn.warnUnchecked();
  3076         if (!source.allowCovariantReturns())
  3077             // reject if there is a common method signature with
  3078             // incompatible return types.
  3079             chk.checkCompatibleAbstracts(warn.pos(), from, to);
  3080         return true;
  3083     private boolean sideCastFinal(Type from, Type to, Warner warn) {
  3084         // We are casting from type $from$ to type $to$, which are
  3085         // unrelated types one of which is final and the other of
  3086         // which is an interface.  This method
  3087         // tries to reject a cast by transferring type parameters
  3088         // from the final class to the interface.
  3089         boolean reverse = false;
  3090         Type target = to;
  3091         if ((to.tsym.flags() & INTERFACE) == 0) {
  3092             assert (from.tsym.flags() & INTERFACE) != 0;
  3093             reverse = true;
  3094             to = from;
  3095             from = target;
  3097         assert (from.tsym.flags() & FINAL) != 0;
  3098         Type t1 = asSuper(from, to.tsym);
  3099         if (t1 == null) return false;
  3100         Type t2 = to;
  3101         if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
  3102             return false;
  3103         if (!source.allowCovariantReturns())
  3104             // reject if there is a common method signature with
  3105             // incompatible return types.
  3106             chk.checkCompatibleAbstracts(warn.pos(), from, to);
  3107         if (!isReifiable(target) &&
  3108             (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2)))
  3109             warn.warnUnchecked();
  3110         return true;
  3113     private boolean giveWarning(Type from, Type to) {
  3114         Type subFrom = asSub(from, to.tsym);
  3115         return to.isParameterized() &&
  3116                 (!(isUnbounded(to) ||
  3117                 isSubtype(from, to) ||
  3118                 ((subFrom != null) && isSameType(subFrom, to))));
  3121     private List<Type> superClosure(Type t, Type s) {
  3122         List<Type> cl = List.nil();
  3123         for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
  3124             if (isSubtype(s, erasure(l.head))) {
  3125                 cl = insert(cl, l.head);
  3126             } else {
  3127                 cl = union(cl, superClosure(l.head, s));
  3130         return cl;
  3133     private boolean containsTypeEquivalent(Type t, Type s) {
  3134         return
  3135             isSameType(t, s) || // shortcut
  3136             containsType(t, s) && containsType(s, t);
  3139     // <editor-fold defaultstate="collapsed" desc="adapt">
  3140     /**
  3141      * Adapt a type by computing a substitution which maps a source
  3142      * type to a target type.
  3144      * @param source    the source type
  3145      * @param target    the target type
  3146      * @param from      the type variables of the computed substitution
  3147      * @param to        the types of the computed substitution.
  3148      */
  3149     public void adapt(Type source,
  3150                        Type target,
  3151                        ListBuffer<Type> from,
  3152                        ListBuffer<Type> to) throws AdaptFailure {
  3153         new Adapter(from, to).adapt(source, target);
  3156     class Adapter extends SimpleVisitor<Void, Type> {
  3158         ListBuffer<Type> from;
  3159         ListBuffer<Type> to;
  3160         Map<Symbol,Type> mapping;
  3162         Adapter(ListBuffer<Type> from, ListBuffer<Type> to) {
  3163             this.from = from;
  3164             this.to = to;
  3165             mapping = new HashMap<Symbol,Type>();
  3168         public void adapt(Type source, Type target) throws AdaptFailure {
  3169             visit(source, target);
  3170             List<Type> fromList = from.toList();
  3171             List<Type> toList = to.toList();
  3172             while (!fromList.isEmpty()) {
  3173                 Type val = mapping.get(fromList.head.tsym);
  3174                 if (toList.head != val)
  3175                     toList.head = val;
  3176                 fromList = fromList.tail;
  3177                 toList = toList.tail;
  3181         @Override
  3182         public Void visitClassType(ClassType source, Type target) throws AdaptFailure {
  3183             if (target.tag == CLASS)
  3184                 adaptRecursive(source.allparams(), target.allparams());
  3185             return null;
  3188         @Override
  3189         public Void visitArrayType(ArrayType source, Type target) throws AdaptFailure {
  3190             if (target.tag == ARRAY)
  3191                 adaptRecursive(elemtype(source), elemtype(target));
  3192             return null;
  3195         @Override
  3196         public Void visitWildcardType(WildcardType source, Type target) throws AdaptFailure {
  3197             if (source.isExtendsBound())
  3198                 adaptRecursive(upperBound(source), upperBound(target));
  3199             else if (source.isSuperBound())
  3200                 adaptRecursive(lowerBound(source), lowerBound(target));
  3201             return null;
  3204         @Override
  3205         public Void visitTypeVar(TypeVar source, Type target) throws AdaptFailure {
  3206             // Check to see if there is
  3207             // already a mapping for $source$, in which case
  3208             // the old mapping will be merged with the new
  3209             Type val = mapping.get(source.tsym);
  3210             if (val != null) {
  3211                 if (val.isSuperBound() && target.isSuperBound()) {
  3212                     val = isSubtype(lowerBound(val), lowerBound(target))
  3213                         ? target : val;
  3214                 } else if (val.isExtendsBound() && target.isExtendsBound()) {
  3215                     val = isSubtype(upperBound(val), upperBound(target))
  3216                         ? val : target;
  3217                 } else if (!isSameType(val, target)) {
  3218                     throw new AdaptFailure();
  3220             } else {
  3221                 val = target;
  3222                 from.append(source);
  3223                 to.append(target);
  3225             mapping.put(source.tsym, val);
  3226             return null;
  3229         @Override
  3230         public Void visitType(Type source, Type target) {
  3231             return null;
  3234         private Set<TypePair> cache = new HashSet<TypePair>();
  3236         private void adaptRecursive(Type source, Type target) {
  3237             TypePair pair = new TypePair(source, target);
  3238             if (cache.add(pair)) {
  3239                 try {
  3240                     visit(source, target);
  3241                 } finally {
  3242                     cache.remove(pair);
  3247         private void adaptRecursive(List<Type> source, List<Type> target) {
  3248             if (source.length() == target.length()) {
  3249                 while (source.nonEmpty()) {
  3250                     adaptRecursive(source.head, target.head);
  3251                     source = source.tail;
  3252                     target = target.tail;
  3258     public static class AdaptFailure extends RuntimeException {
  3259         static final long serialVersionUID = -7490231548272701566L;
  3262     private void adaptSelf(Type t,
  3263                            ListBuffer<Type> from,
  3264                            ListBuffer<Type> to) {
  3265         try {
  3266             //if (t.tsym.type != t)
  3267                 adapt(t.tsym.type, t, from, to);
  3268         } catch (AdaptFailure ex) {
  3269             // Adapt should never fail calculating a mapping from
  3270             // t.tsym.type to t as there can be no merge problem.
  3271             throw new AssertionError(ex);
  3274     // </editor-fold>
  3276     /**
  3277      * Rewrite all type variables (universal quantifiers) in the given
  3278      * type to wildcards (existential quantifiers).  This is used to
  3279      * determine if a cast is allowed.  For example, if high is true
  3280      * and {@code T <: Number}, then {@code List<T>} is rewritten to
  3281      * {@code List<?  extends Number>}.  Since {@code List<Integer> <:
  3282      * List<? extends Number>} a {@code List<T>} can be cast to {@code
  3283      * List<Integer>} with a warning.
  3284      * @param t a type
  3285      * @param high if true return an upper bound; otherwise a lower
  3286      * bound
  3287      * @param rewriteTypeVars only rewrite captured wildcards if false;
  3288      * otherwise rewrite all type variables
  3289      * @return the type rewritten with wildcards (existential
  3290      * quantifiers) only
  3291      */
  3292     private Type rewriteQuantifiers(Type t, boolean high, boolean rewriteTypeVars) {
  3293         return new Rewriter(high, rewriteTypeVars).visit(t);
  3296     class Rewriter extends UnaryVisitor<Type> {
  3298         boolean high;
  3299         boolean rewriteTypeVars;
  3301         Rewriter(boolean high, boolean rewriteTypeVars) {
  3302             this.high = high;
  3303             this.rewriteTypeVars = rewriteTypeVars;
  3306         @Override
  3307         public Type visitClassType(ClassType t, Void s) {
  3308             ListBuffer<Type> rewritten = new ListBuffer<Type>();
  3309             boolean changed = false;
  3310             for (Type arg : t.allparams()) {
  3311                 Type bound = visit(arg);
  3312                 if (arg != bound) {
  3313                     changed = true;
  3315                 rewritten.append(bound);
  3317             if (changed)
  3318                 return subst(t.tsym.type,
  3319                         t.tsym.type.allparams(),
  3320                         rewritten.toList());
  3321             else
  3322                 return t;
  3325         public Type visitType(Type t, Void s) {
  3326             return high ? upperBound(t) : lowerBound(t);
  3329         @Override
  3330         public Type visitCapturedType(CapturedType t, Void s) {
  3331             Type bound = visitWildcardType(t.wildcard, null);
  3332             return (bound.contains(t)) ?
  3333                     (high ? syms.objectType : syms.botType) :
  3334                         bound;
  3337         @Override
  3338         public Type visitTypeVar(TypeVar t, Void s) {
  3339             if (rewriteTypeVars) {
  3340                 Type bound = high ?
  3341                     (t.bound.contains(t) ?
  3342                         syms.objectType :
  3343                         visit(t.bound)) :
  3344                     syms.botType;
  3345                 return rewriteAsWildcardType(bound, t);
  3347             else
  3348                 return t;
  3351         @Override
  3352         public Type visitWildcardType(WildcardType t, Void s) {
  3353             Type bound = high ? t.getExtendsBound() :
  3354                                 t.getSuperBound();
  3355             if (bound == null)
  3356             bound = high ? syms.objectType : syms.botType;
  3357             return rewriteAsWildcardType(visit(bound), t.bound);
  3360         private Type rewriteAsWildcardType(Type bound, TypeVar formal) {
  3361             return high ?
  3362                 makeExtendsWildcard(B(bound), formal) :
  3363                 makeSuperWildcard(B(bound), formal);
  3366         Type B(Type t) {
  3367             while (t.tag == WILDCARD) {
  3368                 WildcardType w = (WildcardType)t;
  3369                 t = high ?
  3370                     w.getExtendsBound() :
  3371                     w.getSuperBound();
  3372                 if (t == null) {
  3373                     t = high ? syms.objectType : syms.botType;
  3376             return t;
  3381     /**
  3382      * Create a wildcard with the given upper (extends) bound; create
  3383      * an unbounded wildcard if bound is Object.
  3385      * @param bound the upper bound
  3386      * @param formal the formal type parameter that will be
  3387      * substituted by the wildcard
  3388      */
  3389     private WildcardType makeExtendsWildcard(Type bound, TypeVar formal) {
  3390         if (bound == syms.objectType) {
  3391             return new WildcardType(syms.objectType,
  3392                                     BoundKind.UNBOUND,
  3393                                     syms.boundClass,
  3394                                     formal);
  3395         } else {
  3396             return new WildcardType(bound,
  3397                                     BoundKind.EXTENDS,
  3398                                     syms.boundClass,
  3399                                     formal);
  3403     /**
  3404      * Create a wildcard with the given lower (super) bound; create an
  3405      * unbounded wildcard if bound is bottom (type of {@code null}).
  3407      * @param bound the lower bound
  3408      * @param formal the formal type parameter that will be
  3409      * substituted by the wildcard
  3410      */
  3411     private WildcardType makeSuperWildcard(Type bound, TypeVar formal) {
  3412         if (bound.tag == BOT) {
  3413             return new WildcardType(syms.objectType,
  3414                                     BoundKind.UNBOUND,
  3415                                     syms.boundClass,
  3416                                     formal);
  3417         } else {
  3418             return new WildcardType(bound,
  3419                                     BoundKind.SUPER,
  3420                                     syms.boundClass,
  3421                                     formal);
  3425     /**
  3426      * A wrapper for a type that allows use in sets.
  3427      */
  3428     class SingletonType {
  3429         final Type t;
  3430         SingletonType(Type t) {
  3431             this.t = t;
  3433         public int hashCode() {
  3434             return Types.hashCode(t);
  3436         public boolean equals(Object obj) {
  3437             return (obj instanceof SingletonType) &&
  3438                 isSameType(t, ((SingletonType)obj).t);
  3440         public String toString() {
  3441             return t.toString();
  3444     // </editor-fold>
  3446     // <editor-fold defaultstate="collapsed" desc="Visitors">
  3447     /**
  3448      * A default visitor for types.  All visitor methods except
  3449      * visitType are implemented by delegating to visitType.  Concrete
  3450      * subclasses must provide an implementation of visitType and can
  3451      * override other methods as needed.
  3453      * @param <R> the return type of the operation implemented by this
  3454      * visitor; use Void if no return type is needed.
  3455      * @param <S> the type of the second argument (the first being the
  3456      * type itself) of the operation implemented by this visitor; use
  3457      * Void if a second argument is not needed.
  3458      */
  3459     public static abstract class DefaultTypeVisitor<R,S> implements Type.Visitor<R,S> {
  3460         final public R visit(Type t, S s)               { return t.accept(this, s); }
  3461         public R visitClassType(ClassType t, S s)       { return visitType(t, s); }
  3462         public R visitWildcardType(WildcardType t, S s) { return visitType(t, s); }
  3463         public R visitArrayType(ArrayType t, S s)       { return visitType(t, s); }
  3464         public R visitMethodType(MethodType t, S s)     { return visitType(t, s); }
  3465         public R visitPackageType(PackageType t, S s)   { return visitType(t, s); }
  3466         public R visitTypeVar(TypeVar t, S s)           { return visitType(t, s); }
  3467         public R visitCapturedType(CapturedType t, S s) { return visitType(t, s); }
  3468         public R visitForAll(ForAll t, S s)             { return visitType(t, s); }
  3469         public R visitUndetVar(UndetVar t, S s)         { return visitType(t, s); }
  3470         public R visitErrorType(ErrorType t, S s)       { return visitType(t, s); }
  3473     /**
  3474      * A default visitor for symbols.  All visitor methods except
  3475      * visitSymbol are implemented by delegating to visitSymbol.  Concrete
  3476      * subclasses must provide an implementation of visitSymbol and can
  3477      * override other methods as needed.
  3479      * @param <R> the return type of the operation implemented by this
  3480      * visitor; use Void if no return type is needed.
  3481      * @param <S> the type of the second argument (the first being the
  3482      * symbol itself) of the operation implemented by this visitor; use
  3483      * Void if a second argument is not needed.
  3484      */
  3485     public static abstract class DefaultSymbolVisitor<R,S> implements Symbol.Visitor<R,S> {
  3486         final public R visit(Symbol s, S arg)                   { return s.accept(this, arg); }
  3487         public R visitClassSymbol(ClassSymbol s, S arg)         { return visitSymbol(s, arg); }
  3488         public R visitMethodSymbol(MethodSymbol s, S arg)       { return visitSymbol(s, arg); }
  3489         public R visitOperatorSymbol(OperatorSymbol s, S arg)   { return visitSymbol(s, arg); }
  3490         public R visitPackageSymbol(PackageSymbol s, S arg)     { return visitSymbol(s, arg); }
  3491         public R visitTypeSymbol(TypeSymbol s, S arg)           { return visitSymbol(s, arg); }
  3492         public R visitVarSymbol(VarSymbol s, S arg)             { return visitSymbol(s, arg); }
  3495     /**
  3496      * A <em>simple</em> visitor for types.  This visitor is simple as
  3497      * captured wildcards, for-all types (generic methods), and
  3498      * undetermined type variables (part of inference) are hidden.
  3499      * Captured wildcards are hidden by treating them as type
  3500      * variables and the rest are hidden by visiting their qtypes.
  3502      * @param <R> the return type of the operation implemented by this
  3503      * visitor; use Void if no return type is needed.
  3504      * @param <S> the type of the second argument (the first being the
  3505      * type itself) of the operation implemented by this visitor; use
  3506      * Void if a second argument is not needed.
  3507      */
  3508     public static abstract class SimpleVisitor<R,S> extends DefaultTypeVisitor<R,S> {
  3509         @Override
  3510         public R visitCapturedType(CapturedType t, S s) {
  3511             return visitTypeVar(t, s);
  3513         @Override
  3514         public R visitForAll(ForAll t, S s) {
  3515             return visit(t.qtype, s);
  3517         @Override
  3518         public R visitUndetVar(UndetVar t, S s) {
  3519             return visit(t.qtype, s);
  3523     /**
  3524      * A plain relation on types.  That is a 2-ary function on the
  3525      * form Type&nbsp;&times;&nbsp;Type&nbsp;&rarr;&nbsp;Boolean.
  3526      * <!-- In plain text: Type x Type -> Boolean -->
  3527      */
  3528     public static abstract class TypeRelation extends SimpleVisitor<Boolean,Type> {}
  3530     /**
  3531      * A convenience visitor for implementing operations that only
  3532      * require one argument (the type itself), that is, unary
  3533      * operations.
  3535      * @param <R> the return type of the operation implemented by this
  3536      * visitor; use Void if no return type is needed.
  3537      */
  3538     public static abstract class UnaryVisitor<R> extends SimpleVisitor<R,Void> {
  3539         final public R visit(Type t) { return t.accept(this, null); }
  3542     /**
  3543      * A visitor for implementing a mapping from types to types.  The
  3544      * default behavior of this class is to implement the identity
  3545      * mapping (mapping a type to itself).  This can be overridden in
  3546      * subclasses.
  3548      * @param <S> the type of the second argument (the first being the
  3549      * type itself) of this mapping; use Void if a second argument is
  3550      * not needed.
  3551      */
  3552     public static class MapVisitor<S> extends DefaultTypeVisitor<Type,S> {
  3553         final public Type visit(Type t) { return t.accept(this, null); }
  3554         public Type visitType(Type t, S s) { return t; }
  3556     // </editor-fold>

mercurial