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

Thu, 30 Jul 2009 10:29:53 +0100

author
mcimadamore
date
Thu, 30 Jul 2009 10:29:53 +0100
changeset 341
85fecace920b
parent 299
22872b24d38c
child 356
d5f6c475f475
permissions
-rw-r--r--

6827648: Extremely slow compilation time for visitor pattern code + generics
Summary: Javac unnecessarily recomputates type-substitutions multiple times
Reviewed-by: jjg

     1 /*
     2  * Copyright 2003-2009 Sun Microsystems, Inc.  All Rights Reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Sun designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Sun in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
    22  * CA 95054 USA or visit www.sun.com if you need additional information or
    23  * have any questions.
    24  */
    26 package com.sun.tools.javac.code;
    28 import java.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 API supported by Sun Microsystems.
    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                     return s.isSuperBound()
   593                         && !s.isExtendsBound()
   594                         && visit(t, upperBound(s));
   595                 default:
   596                     throw new AssertionError("isSameType " + t.tag);
   597                 }
   598             }
   600             @Override
   601             public Boolean visitWildcardType(WildcardType t, Type s) {
   602                 if (s.tag >= firstPartialTag)
   603                     return visit(s, t);
   604                 else
   605                     return false;
   606             }
   608             @Override
   609             public Boolean visitClassType(ClassType t, Type s) {
   610                 if (t == s)
   611                     return true;
   613                 if (s.tag >= firstPartialTag)
   614                     return visit(s, t);
   616                 if (s.isSuperBound() && !s.isExtendsBound())
   617                     return visit(t, upperBound(s)) && visit(t, lowerBound(s));
   619                 if (t.isCompound() && s.isCompound()) {
   620                     if (!visit(supertype(t), supertype(s)))
   621                         return false;
   623                     HashSet<SingletonType> set = new HashSet<SingletonType>();
   624                     for (Type x : interfaces(t))
   625                         set.add(new SingletonType(x));
   626                     for (Type x : interfaces(s)) {
   627                         if (!set.remove(new SingletonType(x)))
   628                             return false;
   629                     }
   630                     return (set.size() == 0);
   631                 }
   632                 return t.tsym == s.tsym
   633                     && visit(t.getEnclosingType(), s.getEnclosingType())
   634                     && containsTypeEquivalent(t.getTypeArguments(), s.getTypeArguments());
   635             }
   637             @Override
   638             public Boolean visitArrayType(ArrayType t, Type s) {
   639                 if (t == s)
   640                     return true;
   642                 if (s.tag >= firstPartialTag)
   643                     return visit(s, t);
   645                 return s.tag == ARRAY
   646                     && containsTypeEquivalent(t.elemtype, elemtype(s));
   647             }
   649             @Override
   650             public Boolean visitMethodType(MethodType t, Type s) {
   651                 // isSameType for methods does not take thrown
   652                 // exceptions into account!
   653                 return hasSameArgs(t, s) && visit(t.getReturnType(), s.getReturnType());
   654             }
   656             @Override
   657             public Boolean visitPackageType(PackageType t, Type s) {
   658                 return t == s;
   659             }
   661             @Override
   662             public Boolean visitForAll(ForAll t, Type s) {
   663                 if (s.tag != FORALL)
   664                     return false;
   666                 ForAll forAll = (ForAll)s;
   667                 return hasSameBounds(t, forAll)
   668                     && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
   669             }
   671             @Override
   672             public Boolean visitUndetVar(UndetVar t, Type s) {
   673                 if (s.tag == WILDCARD)
   674                     // FIXME, this might be leftovers from before capture conversion
   675                     return false;
   677                 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN)
   678                     return true;
   680                 if (t.inst != null)
   681                     return visit(t.inst, s);
   683                 t.inst = fromUnknownFun.apply(s);
   684                 for (List<Type> l = t.lobounds; l.nonEmpty(); l = l.tail) {
   685                     if (!isSubtype(l.head, t.inst))
   686                         return false;
   687                 }
   688                 for (List<Type> l = t.hibounds; l.nonEmpty(); l = l.tail) {
   689                     if (!isSubtype(t.inst, l.head))
   690                         return false;
   691                 }
   692                 return true;
   693             }
   695             @Override
   696             public Boolean visitErrorType(ErrorType t, Type s) {
   697                 return true;
   698             }
   699         };
   700     // </editor-fold>
   702     // <editor-fold defaultstate="collapsed" desc="fromUnknownFun">
   703     /**
   704      * A mapping that turns all unknown types in this type to fresh
   705      * unknown variables.
   706      */
   707     public Mapping fromUnknownFun = new Mapping("fromUnknownFun") {
   708             public Type apply(Type t) {
   709                 if (t.tag == UNKNOWN) return new UndetVar(t);
   710                 else return t.map(this);
   711             }
   712         };
   713     // </editor-fold>
   715     // <editor-fold defaultstate="collapsed" desc="Contains Type">
   716     public boolean containedBy(Type t, Type s) {
   717         switch (t.tag) {
   718         case UNDETVAR:
   719             if (s.tag == WILDCARD) {
   720                 UndetVar undetvar = (UndetVar)t;
   721                 WildcardType wt = (WildcardType)s;
   722                 switch(wt.kind) {
   723                     case UNBOUND: //similar to ? extends Object
   724                     case EXTENDS: {
   725                         Type bound = upperBound(s);
   726                         // We should check the new upper bound against any of the
   727                         // undetvar's lower bounds.
   728                         for (Type t2 : undetvar.lobounds) {
   729                             if (!isSubtype(t2, bound))
   730                                 return false;
   731                         }
   732                         undetvar.hibounds = undetvar.hibounds.prepend(bound);
   733                         break;
   734                     }
   735                     case SUPER: {
   736                         Type bound = lowerBound(s);
   737                         // We should check the new lower bound against any of the
   738                         // undetvar's lower bounds.
   739                         for (Type t2 : undetvar.hibounds) {
   740                             if (!isSubtype(bound, t2))
   741                                 return false;
   742                         }
   743                         undetvar.lobounds = undetvar.lobounds.prepend(bound);
   744                         break;
   745                     }
   746                 }
   747                 return true;
   748             } else {
   749                 return isSameType(t, s);
   750             }
   751         case ERROR:
   752             return true;
   753         default:
   754             return containsType(s, t);
   755         }
   756     }
   758     boolean containsType(List<Type> ts, List<Type> ss) {
   759         while (ts.nonEmpty() && ss.nonEmpty()
   760                && containsType(ts.head, ss.head)) {
   761             ts = ts.tail;
   762             ss = ss.tail;
   763         }
   764         return ts.isEmpty() && ss.isEmpty();
   765     }
   767     /**
   768      * Check if t contains s.
   769      *
   770      * <p>T contains S if:
   771      *
   772      * <p>{@code L(T) <: L(S) && U(S) <: U(T)}
   773      *
   774      * <p>This relation is only used by ClassType.isSubtype(), that
   775      * is,
   776      *
   777      * <p>{@code C<S> <: C<T> if T contains S.}
   778      *
   779      * <p>Because of F-bounds, this relation can lead to infinite
   780      * recursion.  Thus we must somehow break that recursion.  Notice
   781      * that containsType() is only called from ClassType.isSubtype().
   782      * Since the arguments have already been checked against their
   783      * bounds, we know:
   784      *
   785      * <p>{@code U(S) <: U(T) if T is "super" bound (U(T) *is* the bound)}
   786      *
   787      * <p>{@code L(T) <: L(S) if T is "extends" bound (L(T) is bottom)}
   788      *
   789      * @param t a type
   790      * @param s a type
   791      */
   792     public boolean containsType(Type t, Type s) {
   793         return containsType.visit(t, s);
   794     }
   795     // where
   796         private TypeRelation containsType = new TypeRelation() {
   798             private Type U(Type t) {
   799                 while (t.tag == WILDCARD) {
   800                     WildcardType w = (WildcardType)t;
   801                     if (w.isSuperBound())
   802                         return w.bound == null ? syms.objectType : w.bound.bound;
   803                     else
   804                         t = w.type;
   805                 }
   806                 return t;
   807             }
   809             private Type L(Type t) {
   810                 while (t.tag == WILDCARD) {
   811                     WildcardType w = (WildcardType)t;
   812                     if (w.isExtendsBound())
   813                         return syms.botType;
   814                     else
   815                         t = w.type;
   816                 }
   817                 return t;
   818             }
   820             public Boolean visitType(Type t, Type s) {
   821                 if (s.tag >= firstPartialTag)
   822                     return containedBy(s, t);
   823                 else
   824                     return isSameType(t, s);
   825             }
   827             void debugContainsType(WildcardType t, Type s) {
   828                 System.err.println();
   829                 System.err.format(" does %s contain %s?%n", t, s);
   830                 System.err.format(" %s U(%s) <: U(%s) %s = %s%n",
   831                                   upperBound(s), s, t, U(t),
   832                                   t.isSuperBound()
   833                                   || isSubtypeNoCapture(upperBound(s), U(t)));
   834                 System.err.format(" %s L(%s) <: L(%s) %s = %s%n",
   835                                   L(t), t, s, lowerBound(s),
   836                                   t.isExtendsBound()
   837                                   || isSubtypeNoCapture(L(t), lowerBound(s)));
   838                 System.err.println();
   839             }
   841             @Override
   842             public Boolean visitWildcardType(WildcardType t, Type s) {
   843                 if (s.tag >= firstPartialTag)
   844                     return containedBy(s, t);
   845                 else {
   846                     // debugContainsType(t, s);
   847                     return isSameWildcard(t, s)
   848                         || isCaptureOf(s, t)
   849                         || ((t.isExtendsBound() || isSubtypeNoCapture(L(t), lowerBound(s))) &&
   850                             (t.isSuperBound() || isSubtypeNoCapture(upperBound(s), U(t))));
   851                 }
   852             }
   854             @Override
   855             public Boolean visitUndetVar(UndetVar t, Type s) {
   856                 if (s.tag != WILDCARD)
   857                     return isSameType(t, s);
   858                 else
   859                     return false;
   860             }
   862             @Override
   863             public Boolean visitErrorType(ErrorType t, Type s) {
   864                 return true;
   865             }
   866         };
   868     public boolean isCaptureOf(Type s, WildcardType t) {
   869         if (s.tag != TYPEVAR || !((TypeVar)s).isCaptured())
   870             return false;
   871         return isSameWildcard(t, ((CapturedType)s).wildcard);
   872     }
   874     public boolean isSameWildcard(WildcardType t, Type s) {
   875         if (s.tag != WILDCARD)
   876             return false;
   877         WildcardType w = (WildcardType)s;
   878         return w.kind == t.kind && w.type == t.type;
   879     }
   881     public boolean containsTypeEquivalent(List<Type> ts, List<Type> ss) {
   882         while (ts.nonEmpty() && ss.nonEmpty()
   883                && containsTypeEquivalent(ts.head, ss.head)) {
   884             ts = ts.tail;
   885             ss = ss.tail;
   886         }
   887         return ts.isEmpty() && ss.isEmpty();
   888     }
   889     // </editor-fold>
   891     // <editor-fold defaultstate="collapsed" desc="isCastable">
   892     public boolean isCastable(Type t, Type s) {
   893         return isCastable(t, s, Warner.noWarnings);
   894     }
   896     /**
   897      * Is t is castable to s?<br>
   898      * s is assumed to be an erased type.<br>
   899      * (not defined for Method and ForAll types).
   900      */
   901     public boolean isCastable(Type t, Type s, Warner warn) {
   902         if (t == s)
   903             return true;
   905         if (t.isPrimitive() != s.isPrimitive())
   906             return allowBoxing && isConvertible(t, s, warn);
   908         if (warn != warnStack.head) {
   909             try {
   910                 warnStack = warnStack.prepend(warn);
   911                 return isCastable.visit(t,s);
   912             } finally {
   913                 warnStack = warnStack.tail;
   914             }
   915         } else {
   916             return isCastable.visit(t,s);
   917         }
   918     }
   919     // where
   920         private TypeRelation isCastable = new TypeRelation() {
   922             public Boolean visitType(Type t, Type s) {
   923                 if (s.tag == ERROR)
   924                     return true;
   926                 switch (t.tag) {
   927                 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
   928                 case DOUBLE:
   929                     return s.tag <= DOUBLE;
   930                 case BOOLEAN:
   931                     return s.tag == BOOLEAN;
   932                 case VOID:
   933                     return false;
   934                 case BOT:
   935                     return isSubtype(t, s);
   936                 default:
   937                     throw new AssertionError();
   938                 }
   939             }
   941             @Override
   942             public Boolean visitWildcardType(WildcardType t, Type s) {
   943                 return isCastable(upperBound(t), s, warnStack.head);
   944             }
   946             @Override
   947             public Boolean visitClassType(ClassType t, Type s) {
   948                 if (s.tag == ERROR || s.tag == BOT)
   949                     return true;
   951                 if (s.tag == TYPEVAR) {
   952                     if (isCastable(s.getUpperBound(), t, Warner.noWarnings)) {
   953                         warnStack.head.warnUnchecked();
   954                         return true;
   955                     } else {
   956                         return false;
   957                     }
   958                 }
   960                 if (t.isCompound()) {
   961                     Warner oldWarner = warnStack.head;
   962                     warnStack.head = Warner.noWarnings;
   963                     if (!visit(supertype(t), s))
   964                         return false;
   965                     for (Type intf : interfaces(t)) {
   966                         if (!visit(intf, s))
   967                             return false;
   968                     }
   969                     if (warnStack.head.unchecked == true)
   970                         oldWarner.warnUnchecked();
   971                     return true;
   972                 }
   974                 if (s.isCompound()) {
   975                     // call recursively to reuse the above code
   976                     return visitClassType((ClassType)s, t);
   977                 }
   979                 if (s.tag == CLASS || s.tag == ARRAY) {
   980                     boolean upcast;
   981                     if ((upcast = isSubtype(erasure(t), erasure(s)))
   982                         || isSubtype(erasure(s), erasure(t))) {
   983                         if (!upcast && s.tag == ARRAY) {
   984                             if (!isReifiable(s))
   985                                 warnStack.head.warnUnchecked();
   986                             return true;
   987                         } else if (s.isRaw()) {
   988                             return true;
   989                         } else if (t.isRaw()) {
   990                             if (!isUnbounded(s))
   991                                 warnStack.head.warnUnchecked();
   992                             return true;
   993                         }
   994                         // Assume |a| <: |b|
   995                         final Type a = upcast ? t : s;
   996                         final Type b = upcast ? s : t;
   997                         final boolean HIGH = true;
   998                         final boolean LOW = false;
   999                         final boolean DONT_REWRITE_TYPEVARS = false;
  1000                         Type aHigh = rewriteQuantifiers(a, HIGH, DONT_REWRITE_TYPEVARS);
  1001                         Type aLow  = rewriteQuantifiers(a, LOW,  DONT_REWRITE_TYPEVARS);
  1002                         Type bHigh = rewriteQuantifiers(b, HIGH, DONT_REWRITE_TYPEVARS);
  1003                         Type bLow  = rewriteQuantifiers(b, LOW,  DONT_REWRITE_TYPEVARS);
  1004                         Type lowSub = asSub(bLow, aLow.tsym);
  1005                         Type highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
  1006                         if (highSub == null) {
  1007                             final boolean REWRITE_TYPEVARS = true;
  1008                             aHigh = rewriteQuantifiers(a, HIGH, REWRITE_TYPEVARS);
  1009                             aLow  = rewriteQuantifiers(a, LOW,  REWRITE_TYPEVARS);
  1010                             bHigh = rewriteQuantifiers(b, HIGH, REWRITE_TYPEVARS);
  1011                             bLow  = rewriteQuantifiers(b, LOW,  REWRITE_TYPEVARS);
  1012                             lowSub = asSub(bLow, aLow.tsym);
  1013                             highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
  1015                         if (highSub != null) {
  1016                             assert a.tsym == highSub.tsym && a.tsym == lowSub.tsym
  1017                                 : a.tsym + " != " + highSub.tsym + " != " + lowSub.tsym;
  1018                             if (!disjointTypes(aHigh.allparams(), highSub.allparams())
  1019                                 && !disjointTypes(aHigh.allparams(), lowSub.allparams())
  1020                                 && !disjointTypes(aLow.allparams(), highSub.allparams())
  1021                                 && !disjointTypes(aLow.allparams(), lowSub.allparams())) {
  1022                                 if (upcast ? giveWarning(a, b) :
  1023                                     giveWarning(b, a))
  1024                                     warnStack.head.warnUnchecked();
  1025                                 return true;
  1028                         if (isReifiable(s))
  1029                             return isSubtypeUnchecked(a, b);
  1030                         else
  1031                             return isSubtypeUnchecked(a, b, warnStack.head);
  1034                     // Sidecast
  1035                     if (s.tag == CLASS) {
  1036                         if ((s.tsym.flags() & INTERFACE) != 0) {
  1037                             return ((t.tsym.flags() & FINAL) == 0)
  1038                                 ? sideCast(t, s, warnStack.head)
  1039                                 : sideCastFinal(t, s, warnStack.head);
  1040                         } else if ((t.tsym.flags() & INTERFACE) != 0) {
  1041                             return ((s.tsym.flags() & FINAL) == 0)
  1042                                 ? sideCast(t, s, warnStack.head)
  1043                                 : sideCastFinal(t, s, warnStack.head);
  1044                         } else {
  1045                             // unrelated class types
  1046                             return false;
  1050                 return false;
  1053             @Override
  1054             public Boolean visitArrayType(ArrayType t, Type s) {
  1055                 switch (s.tag) {
  1056                 case ERROR:
  1057                 case BOT:
  1058                     return true;
  1059                 case TYPEVAR:
  1060                     if (isCastable(s, t, Warner.noWarnings)) {
  1061                         warnStack.head.warnUnchecked();
  1062                         return true;
  1063                     } else {
  1064                         return false;
  1066                 case CLASS:
  1067                     return isSubtype(t, s);
  1068                 case ARRAY:
  1069                     if (elemtype(t).tag <= lastBaseTag) {
  1070                         return elemtype(t).tag == elemtype(s).tag;
  1071                     } else {
  1072                         return visit(elemtype(t), elemtype(s));
  1074                 default:
  1075                     return false;
  1079             @Override
  1080             public Boolean visitTypeVar(TypeVar t, Type s) {
  1081                 switch (s.tag) {
  1082                 case ERROR:
  1083                 case BOT:
  1084                     return true;
  1085                 case TYPEVAR:
  1086                     if (isSubtype(t, s)) {
  1087                         return true;
  1088                     } else if (isCastable(t.bound, s, Warner.noWarnings)) {
  1089                         warnStack.head.warnUnchecked();
  1090                         return true;
  1091                     } else {
  1092                         return false;
  1094                 default:
  1095                     return isCastable(t.bound, s, warnStack.head);
  1099             @Override
  1100             public Boolean visitErrorType(ErrorType t, Type s) {
  1101                 return true;
  1103         };
  1104     // </editor-fold>
  1106     // <editor-fold defaultstate="collapsed" desc="disjointTypes">
  1107     public boolean disjointTypes(List<Type> ts, List<Type> ss) {
  1108         while (ts.tail != null && ss.tail != null) {
  1109             if (disjointType(ts.head, ss.head)) return true;
  1110             ts = ts.tail;
  1111             ss = ss.tail;
  1113         return false;
  1116     /**
  1117      * Two types or wildcards are considered disjoint if it can be
  1118      * proven that no type can be contained in both. It is
  1119      * conservative in that it is allowed to say that two types are
  1120      * not disjoint, even though they actually are.
  1122      * The type C<X> is castable to C<Y> exactly if X and Y are not
  1123      * disjoint.
  1124      */
  1125     public boolean disjointType(Type t, Type s) {
  1126         return disjointType.visit(t, s);
  1128     // where
  1129         private TypeRelation disjointType = new TypeRelation() {
  1131             private Set<TypePair> cache = new HashSet<TypePair>();
  1133             public Boolean visitType(Type t, Type s) {
  1134                 if (s.tag == WILDCARD)
  1135                     return visit(s, t);
  1136                 else
  1137                     return notSoftSubtypeRecursive(t, s) || notSoftSubtypeRecursive(s, t);
  1140             private boolean isCastableRecursive(Type t, Type s) {
  1141                 TypePair pair = new TypePair(t, s);
  1142                 if (cache.add(pair)) {
  1143                     try {
  1144                         return Types.this.isCastable(t, s);
  1145                     } finally {
  1146                         cache.remove(pair);
  1148                 } else {
  1149                     return true;
  1153             private boolean notSoftSubtypeRecursive(Type t, Type s) {
  1154                 TypePair pair = new TypePair(t, s);
  1155                 if (cache.add(pair)) {
  1156                     try {
  1157                         return Types.this.notSoftSubtype(t, s);
  1158                     } finally {
  1159                         cache.remove(pair);
  1161                 } else {
  1162                     return false;
  1166             @Override
  1167             public Boolean visitWildcardType(WildcardType t, Type s) {
  1168                 if (t.isUnbound())
  1169                     return false;
  1171                 if (s.tag != WILDCARD) {
  1172                     if (t.isExtendsBound())
  1173                         return notSoftSubtypeRecursive(s, t.type);
  1174                     else // isSuperBound()
  1175                         return notSoftSubtypeRecursive(t.type, s);
  1178                 if (s.isUnbound())
  1179                     return false;
  1181                 if (t.isExtendsBound()) {
  1182                     if (s.isExtendsBound())
  1183                         return !isCastableRecursive(t.type, upperBound(s));
  1184                     else if (s.isSuperBound())
  1185                         return notSoftSubtypeRecursive(lowerBound(s), t.type);
  1186                 } else if (t.isSuperBound()) {
  1187                     if (s.isExtendsBound())
  1188                         return notSoftSubtypeRecursive(t.type, upperBound(s));
  1190                 return false;
  1192         };
  1193     // </editor-fold>
  1195     // <editor-fold defaultstate="collapsed" desc="lowerBoundArgtypes">
  1196     /**
  1197      * Returns the lower bounds of the formals of a method.
  1198      */
  1199     public List<Type> lowerBoundArgtypes(Type t) {
  1200         return map(t.getParameterTypes(), lowerBoundMapping);
  1202     private final Mapping lowerBoundMapping = new Mapping("lowerBound") {
  1203             public Type apply(Type t) {
  1204                 return lowerBound(t);
  1206         };
  1207     // </editor-fold>
  1209     // <editor-fold defaultstate="collapsed" desc="notSoftSubtype">
  1210     /**
  1211      * This relation answers the question: is impossible that
  1212      * something of type `t' can be a subtype of `s'? This is
  1213      * different from the question "is `t' not a subtype of `s'?"
  1214      * when type variables are involved: Integer is not a subtype of T
  1215      * where <T extends Number> but it is not true that Integer cannot
  1216      * possibly be a subtype of T.
  1217      */
  1218     public boolean notSoftSubtype(Type t, Type s) {
  1219         if (t == s) return false;
  1220         if (t.tag == TYPEVAR) {
  1221             TypeVar tv = (TypeVar) t;
  1222             if (s.tag == TYPEVAR)
  1223                 s = s.getUpperBound();
  1224             return !isCastable(tv.bound,
  1225                                s,
  1226                                Warner.noWarnings);
  1228         if (s.tag != WILDCARD)
  1229             s = upperBound(s);
  1230         if (s.tag == TYPEVAR)
  1231             s = s.getUpperBound();
  1233         return !isSubtype(t, s);
  1235     // </editor-fold>
  1237     // <editor-fold defaultstate="collapsed" desc="isReifiable">
  1238     public boolean isReifiable(Type t) {
  1239         return isReifiable.visit(t);
  1241     // where
  1242         private UnaryVisitor<Boolean> isReifiable = new UnaryVisitor<Boolean>() {
  1244             public Boolean visitType(Type t, Void ignored) {
  1245                 return true;
  1248             @Override
  1249             public Boolean visitClassType(ClassType t, Void ignored) {
  1250                 if (!t.isParameterized())
  1251                     return true;
  1253                 for (Type param : t.allparams()) {
  1254                     if (!param.isUnbound())
  1255                         return false;
  1257                 return true;
  1260             @Override
  1261             public Boolean visitArrayType(ArrayType t, Void ignored) {
  1262                 return visit(t.elemtype);
  1265             @Override
  1266             public Boolean visitTypeVar(TypeVar t, Void ignored) {
  1267                 return false;
  1269         };
  1270     // </editor-fold>
  1272     // <editor-fold defaultstate="collapsed" desc="Array Utils">
  1273     public boolean isArray(Type t) {
  1274         while (t.tag == WILDCARD)
  1275             t = upperBound(t);
  1276         return t.tag == ARRAY;
  1279     /**
  1280      * The element type of an array.
  1281      */
  1282     public Type elemtype(Type t) {
  1283         switch (t.tag) {
  1284         case WILDCARD:
  1285             return elemtype(upperBound(t));
  1286         case ARRAY:
  1287             return ((ArrayType)t).elemtype;
  1288         case FORALL:
  1289             return elemtype(((ForAll)t).qtype);
  1290         case ERROR:
  1291             return t;
  1292         default:
  1293             return null;
  1297     /**
  1298      * Mapping to take element type of an arraytype
  1299      */
  1300     private Mapping elemTypeFun = new Mapping ("elemTypeFun") {
  1301         public Type apply(Type t) { return elemtype(t); }
  1302     };
  1304     /**
  1305      * The number of dimensions of an array type.
  1306      */
  1307     public int dimensions(Type t) {
  1308         int result = 0;
  1309         while (t.tag == ARRAY) {
  1310             result++;
  1311             t = elemtype(t);
  1313         return result;
  1315     // </editor-fold>
  1317     // <editor-fold defaultstate="collapsed" desc="asSuper">
  1318     /**
  1319      * Return the (most specific) base type of t that starts with the
  1320      * given symbol.  If none exists, return null.
  1322      * @param t a type
  1323      * @param sym a symbol
  1324      */
  1325     public Type asSuper(Type t, Symbol sym) {
  1326         return asSuper.visit(t, sym);
  1328     // where
  1329         private SimpleVisitor<Type,Symbol> asSuper = new SimpleVisitor<Type,Symbol>() {
  1331             public Type visitType(Type t, Symbol sym) {
  1332                 return null;
  1335             @Override
  1336             public Type visitClassType(ClassType t, Symbol sym) {
  1337                 if (t.tsym == sym)
  1338                     return t;
  1340                 Type st = supertype(t);
  1341                 if (st.tag == CLASS || st.tag == TYPEVAR || st.tag == ERROR) {
  1342                     Type x = asSuper(st, sym);
  1343                     if (x != null)
  1344                         return x;
  1346                 if ((sym.flags() & INTERFACE) != 0) {
  1347                     for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
  1348                         Type x = asSuper(l.head, sym);
  1349                         if (x != null)
  1350                             return x;
  1353                 return null;
  1356             @Override
  1357             public Type visitArrayType(ArrayType t, Symbol sym) {
  1358                 return isSubtype(t, sym.type) ? sym.type : null;
  1361             @Override
  1362             public Type visitTypeVar(TypeVar t, Symbol sym) {
  1363                 if (t.tsym == sym)
  1364                     return t;
  1365                 else
  1366                     return asSuper(t.bound, sym);
  1369             @Override
  1370             public Type visitErrorType(ErrorType t, Symbol sym) {
  1371                 return t;
  1373         };
  1375     /**
  1376      * Return the base type of t or any of its outer types that starts
  1377      * with the given symbol.  If none exists, return null.
  1379      * @param t a type
  1380      * @param sym a symbol
  1381      */
  1382     public Type asOuterSuper(Type t, Symbol sym) {
  1383         switch (t.tag) {
  1384         case CLASS:
  1385             do {
  1386                 Type s = asSuper(t, sym);
  1387                 if (s != null) return s;
  1388                 t = t.getEnclosingType();
  1389             } while (t.tag == CLASS);
  1390             return null;
  1391         case ARRAY:
  1392             return isSubtype(t, sym.type) ? sym.type : null;
  1393         case TYPEVAR:
  1394             return asSuper(t, sym);
  1395         case ERROR:
  1396             return t;
  1397         default:
  1398             return null;
  1402     /**
  1403      * Return the base type of t or any of its enclosing types that
  1404      * starts with the given symbol.  If none exists, return null.
  1406      * @param t a type
  1407      * @param sym a symbol
  1408      */
  1409     public Type asEnclosingSuper(Type t, Symbol sym) {
  1410         switch (t.tag) {
  1411         case CLASS:
  1412             do {
  1413                 Type s = asSuper(t, sym);
  1414                 if (s != null) return s;
  1415                 Type outer = t.getEnclosingType();
  1416                 t = (outer.tag == CLASS) ? outer :
  1417                     (t.tsym.owner.enclClass() != null) ? t.tsym.owner.enclClass().type :
  1418                     Type.noType;
  1419             } while (t.tag == CLASS);
  1420             return null;
  1421         case ARRAY:
  1422             return isSubtype(t, sym.type) ? sym.type : null;
  1423         case TYPEVAR:
  1424             return asSuper(t, sym);
  1425         case ERROR:
  1426             return t;
  1427         default:
  1428             return null;
  1431     // </editor-fold>
  1433     // <editor-fold defaultstate="collapsed" desc="memberType">
  1434     /**
  1435      * The type of given symbol, seen as a member of t.
  1437      * @param t a type
  1438      * @param sym a symbol
  1439      */
  1440     public Type memberType(Type t, Symbol sym) {
  1441         return (sym.flags() & STATIC) != 0
  1442             ? sym.type
  1443             : memberType.visit(t, sym);
  1445     // where
  1446         private SimpleVisitor<Type,Symbol> memberType = new SimpleVisitor<Type,Symbol>() {
  1448             public Type visitType(Type t, Symbol sym) {
  1449                 return sym.type;
  1452             @Override
  1453             public Type visitWildcardType(WildcardType t, Symbol sym) {
  1454                 return memberType(upperBound(t), sym);
  1457             @Override
  1458             public Type visitClassType(ClassType t, Symbol sym) {
  1459                 Symbol owner = sym.owner;
  1460                 long flags = sym.flags();
  1461                 if (((flags & STATIC) == 0) && owner.type.isParameterized()) {
  1462                     Type base = asOuterSuper(t, owner);
  1463                     //if t is an intersection type T = CT & I1 & I2 ... & In
  1464                     //its supertypes CT, I1, ... In might contain wildcards
  1465                     //so we need to go through capture conversion
  1466                     base = t.isCompound() ? capture(base) : base;
  1467                     if (base != null) {
  1468                         List<Type> ownerParams = owner.type.allparams();
  1469                         List<Type> baseParams = base.allparams();
  1470                         if (ownerParams.nonEmpty()) {
  1471                             if (baseParams.isEmpty()) {
  1472                                 // then base is a raw type
  1473                                 return erasure(sym.type);
  1474                             } else {
  1475                                 return subst(sym.type, ownerParams, baseParams);
  1480                 return sym.type;
  1483             @Override
  1484             public Type visitTypeVar(TypeVar t, Symbol sym) {
  1485                 return memberType(t.bound, sym);
  1488             @Override
  1489             public Type visitErrorType(ErrorType t, Symbol sym) {
  1490                 return t;
  1492         };
  1493     // </editor-fold>
  1495     // <editor-fold defaultstate="collapsed" desc="isAssignable">
  1496     public boolean isAssignable(Type t, Type s) {
  1497         return isAssignable(t, s, Warner.noWarnings);
  1500     /**
  1501      * Is t assignable to s?<br>
  1502      * Equivalent to subtype except for constant values and raw
  1503      * types.<br>
  1504      * (not defined for Method and ForAll types)
  1505      */
  1506     public boolean isAssignable(Type t, Type s, Warner warn) {
  1507         if (t.tag == ERROR)
  1508             return true;
  1509         if (t.tag <= INT && t.constValue() != null) {
  1510             int value = ((Number)t.constValue()).intValue();
  1511             switch (s.tag) {
  1512             case BYTE:
  1513                 if (Byte.MIN_VALUE <= value && value <= Byte.MAX_VALUE)
  1514                     return true;
  1515                 break;
  1516             case CHAR:
  1517                 if (Character.MIN_VALUE <= value && value <= Character.MAX_VALUE)
  1518                     return true;
  1519                 break;
  1520             case SHORT:
  1521                 if (Short.MIN_VALUE <= value && value <= Short.MAX_VALUE)
  1522                     return true;
  1523                 break;
  1524             case INT:
  1525                 return true;
  1526             case CLASS:
  1527                 switch (unboxedType(s).tag) {
  1528                 case BYTE:
  1529                 case CHAR:
  1530                 case SHORT:
  1531                     return isAssignable(t, unboxedType(s), warn);
  1533                 break;
  1536         return isConvertible(t, s, warn);
  1538     // </editor-fold>
  1540     // <editor-fold defaultstate="collapsed" desc="erasure">
  1541     /**
  1542      * The erasure of t {@code |t|} -- the type that results when all
  1543      * type parameters in t are deleted.
  1544      */
  1545     public Type erasure(Type t) {
  1546         return erasure(t, false);
  1548     //where
  1549     private Type erasure(Type t, boolean recurse) {
  1550         if (t.tag <= lastBaseTag)
  1551             return t; /* fast special case */
  1552         else
  1553             return erasure.visit(t, recurse);
  1555     // where
  1556         private SimpleVisitor<Type, Boolean> erasure = new SimpleVisitor<Type, Boolean>() {
  1557             public Type visitType(Type t, Boolean recurse) {
  1558                 if (t.tag <= lastBaseTag)
  1559                     return t; /*fast special case*/
  1560                 else
  1561                     return t.map(recurse ? erasureRecFun : erasureFun);
  1564             @Override
  1565             public Type visitWildcardType(WildcardType t, Boolean recurse) {
  1566                 return erasure(upperBound(t), recurse);
  1569             @Override
  1570             public Type visitClassType(ClassType t, Boolean recurse) {
  1571                 Type erased = t.tsym.erasure(Types.this);
  1572                 if (recurse) {
  1573                     erased = new ErasedClassType(erased.getEnclosingType(),erased.tsym);
  1575                 return erased;
  1578             @Override
  1579             public Type visitTypeVar(TypeVar t, Boolean recurse) {
  1580                 return erasure(t.bound, recurse);
  1583             @Override
  1584             public Type visitErrorType(ErrorType t, Boolean recurse) {
  1585                 return t;
  1587         };
  1589     private Mapping erasureFun = new Mapping ("erasure") {
  1590             public Type apply(Type t) { return erasure(t); }
  1591         };
  1593     private Mapping erasureRecFun = new Mapping ("erasureRecursive") {
  1594         public Type apply(Type t) { return erasureRecursive(t); }
  1595     };
  1597     public List<Type> erasure(List<Type> ts) {
  1598         return Type.map(ts, erasureFun);
  1601     public Type erasureRecursive(Type t) {
  1602         return erasure(t, true);
  1605     public List<Type> erasureRecursive(List<Type> ts) {
  1606         return Type.map(ts, erasureRecFun);
  1608     // </editor-fold>
  1610     // <editor-fold defaultstate="collapsed" desc="makeCompoundType">
  1611     /**
  1612      * Make a compound type from non-empty list of types
  1614      * @param bounds            the types from which the compound type is formed
  1615      * @param supertype         is objectType if all bounds are interfaces,
  1616      *                          null otherwise.
  1617      */
  1618     public Type makeCompoundType(List<Type> bounds,
  1619                                  Type supertype) {
  1620         ClassSymbol bc =
  1621             new ClassSymbol(ABSTRACT|PUBLIC|SYNTHETIC|COMPOUND|ACYCLIC,
  1622                             Type.moreInfo
  1623                                 ? names.fromString(bounds.toString())
  1624                                 : names.empty,
  1625                             syms.noSymbol);
  1626         if (bounds.head.tag == TYPEVAR)
  1627             // error condition, recover
  1628                 bc.erasure_field = syms.objectType;
  1629             else
  1630                 bc.erasure_field = erasure(bounds.head);
  1631             bc.members_field = new Scope(bc);
  1632         ClassType bt = (ClassType)bc.type;
  1633         bt.allparams_field = List.nil();
  1634         if (supertype != null) {
  1635             bt.supertype_field = supertype;
  1636             bt.interfaces_field = bounds;
  1637         } else {
  1638             bt.supertype_field = bounds.head;
  1639             bt.interfaces_field = bounds.tail;
  1641         assert bt.supertype_field.tsym.completer != null
  1642             || !bt.supertype_field.isInterface()
  1643             : bt.supertype_field;
  1644         return bt;
  1647     /**
  1648      * Same as {@link #makeCompoundType(List,Type)}, except that the
  1649      * second parameter is computed directly. Note that this might
  1650      * cause a symbol completion.  Hence, this version of
  1651      * makeCompoundType may not be called during a classfile read.
  1652      */
  1653     public Type makeCompoundType(List<Type> bounds) {
  1654         Type supertype = (bounds.head.tsym.flags() & INTERFACE) != 0 ?
  1655             supertype(bounds.head) : null;
  1656         return makeCompoundType(bounds, supertype);
  1659     /**
  1660      * A convenience wrapper for {@link #makeCompoundType(List)}; the
  1661      * arguments are converted to a list and passed to the other
  1662      * method.  Note that this might cause a symbol completion.
  1663      * Hence, this version of makeCompoundType may not be called
  1664      * during a classfile read.
  1665      */
  1666     public Type makeCompoundType(Type bound1, Type bound2) {
  1667         return makeCompoundType(List.of(bound1, bound2));
  1669     // </editor-fold>
  1671     // <editor-fold defaultstate="collapsed" desc="supertype">
  1672     public Type supertype(Type t) {
  1673         return supertype.visit(t);
  1675     // where
  1676         private UnaryVisitor<Type> supertype = new UnaryVisitor<Type>() {
  1678             public Type visitType(Type t, Void ignored) {
  1679                 // A note on wildcards: there is no good way to
  1680                 // determine a supertype for a super bounded wildcard.
  1681                 return null;
  1684             @Override
  1685             public Type visitClassType(ClassType t, Void ignored) {
  1686                 if (t.supertype_field == null) {
  1687                     Type supertype = ((ClassSymbol)t.tsym).getSuperclass();
  1688                     // An interface has no superclass; its supertype is Object.
  1689                     if (t.isInterface())
  1690                         supertype = ((ClassType)t.tsym.type).supertype_field;
  1691                     if (t.supertype_field == null) {
  1692                         List<Type> actuals = classBound(t).allparams();
  1693                         List<Type> formals = t.tsym.type.allparams();
  1694                         if (t.hasErasedSupertypes()) {
  1695                             t.supertype_field = erasureRecursive(supertype);
  1696                         } else if (formals.nonEmpty()) {
  1697                             t.supertype_field = subst(supertype, formals, actuals);
  1699                         else {
  1700                             t.supertype_field = supertype;
  1704                 return t.supertype_field;
  1707             /**
  1708              * The supertype is always a class type. If the type
  1709              * variable's bounds start with a class type, this is also
  1710              * the supertype.  Otherwise, the supertype is
  1711              * java.lang.Object.
  1712              */
  1713             @Override
  1714             public Type visitTypeVar(TypeVar t, Void ignored) {
  1715                 if (t.bound.tag == TYPEVAR ||
  1716                     (!t.bound.isCompound() && !t.bound.isInterface())) {
  1717                     return t.bound;
  1718                 } else {
  1719                     return supertype(t.bound);
  1723             @Override
  1724             public Type visitArrayType(ArrayType t, Void ignored) {
  1725                 if (t.elemtype.isPrimitive() || isSameType(t.elemtype, syms.objectType))
  1726                     return arraySuperType();
  1727                 else
  1728                     return new ArrayType(supertype(t.elemtype), t.tsym);
  1731             @Override
  1732             public Type visitErrorType(ErrorType t, Void ignored) {
  1733                 return t;
  1735         };
  1736     // </editor-fold>
  1738     // <editor-fold defaultstate="collapsed" desc="interfaces">
  1739     /**
  1740      * Return the interfaces implemented by this class.
  1741      */
  1742     public List<Type> interfaces(Type t) {
  1743         return interfaces.visit(t);
  1745     // where
  1746         private UnaryVisitor<List<Type>> interfaces = new UnaryVisitor<List<Type>>() {
  1748             public List<Type> visitType(Type t, Void ignored) {
  1749                 return List.nil();
  1752             @Override
  1753             public List<Type> visitClassType(ClassType t, Void ignored) {
  1754                 if (t.interfaces_field == null) {
  1755                     List<Type> interfaces = ((ClassSymbol)t.tsym).getInterfaces();
  1756                     if (t.interfaces_field == null) {
  1757                         // If t.interfaces_field is null, then t must
  1758                         // be a parameterized type (not to be confused
  1759                         // with a generic type declaration).
  1760                         // Terminology:
  1761                         //    Parameterized type: List<String>
  1762                         //    Generic type declaration: class List<E> { ... }
  1763                         // So t corresponds to List<String> and
  1764                         // t.tsym.type corresponds to List<E>.
  1765                         // The reason t must be parameterized type is
  1766                         // that completion will happen as a side
  1767                         // effect of calling
  1768                         // ClassSymbol.getInterfaces.  Since
  1769                         // t.interfaces_field is null after
  1770                         // completion, we can assume that t is not the
  1771                         // type of a class/interface declaration.
  1772                         assert t != t.tsym.type : t.toString();
  1773                         List<Type> actuals = t.allparams();
  1774                         List<Type> formals = t.tsym.type.allparams();
  1775                         if (t.hasErasedSupertypes()) {
  1776                             t.interfaces_field = erasureRecursive(interfaces);
  1777                         } else if (formals.nonEmpty()) {
  1778                             t.interfaces_field =
  1779                                 upperBounds(subst(interfaces, formals, actuals));
  1781                         else {
  1782                             t.interfaces_field = interfaces;
  1786                 return t.interfaces_field;
  1789             @Override
  1790             public List<Type> visitTypeVar(TypeVar t, Void ignored) {
  1791                 if (t.bound.isCompound())
  1792                     return interfaces(t.bound);
  1794                 if (t.bound.isInterface())
  1795                     return List.of(t.bound);
  1797                 return List.nil();
  1799         };
  1800     // </editor-fold>
  1802     // <editor-fold defaultstate="collapsed" desc="isDerivedRaw">
  1803     Map<Type,Boolean> isDerivedRawCache = new HashMap<Type,Boolean>();
  1805     public boolean isDerivedRaw(Type t) {
  1806         Boolean result = isDerivedRawCache.get(t);
  1807         if (result == null) {
  1808             result = isDerivedRawInternal(t);
  1809             isDerivedRawCache.put(t, result);
  1811         return result;
  1814     public boolean isDerivedRawInternal(Type t) {
  1815         if (t.isErroneous())
  1816             return false;
  1817         return
  1818             t.isRaw() ||
  1819             supertype(t) != null && isDerivedRaw(supertype(t)) ||
  1820             isDerivedRaw(interfaces(t));
  1823     public boolean isDerivedRaw(List<Type> ts) {
  1824         List<Type> l = ts;
  1825         while (l.nonEmpty() && !isDerivedRaw(l.head)) l = l.tail;
  1826         return l.nonEmpty();
  1828     // </editor-fold>
  1830     // <editor-fold defaultstate="collapsed" desc="setBounds">
  1831     /**
  1832      * Set the bounds field of the given type variable to reflect a
  1833      * (possibly multiple) list of bounds.
  1834      * @param t                 a type variable
  1835      * @param bounds            the bounds, must be nonempty
  1836      * @param supertype         is objectType if all bounds are interfaces,
  1837      *                          null otherwise.
  1838      */
  1839     public void setBounds(TypeVar t, List<Type> bounds, Type supertype) {
  1840         if (bounds.tail.isEmpty())
  1841             t.bound = bounds.head;
  1842         else
  1843             t.bound = makeCompoundType(bounds, supertype);
  1844         t.rank_field = -1;
  1847     /**
  1848      * Same as {@link #setBounds(Type.TypeVar,List,Type)}, except that
  1849      * third parameter is computed directly.  Note that this test
  1850      * might cause a symbol completion.  Hence, this version of
  1851      * setBounds may not be called during a classfile read.
  1852      */
  1853     public void setBounds(TypeVar t, List<Type> bounds) {
  1854         Type supertype = (bounds.head.tsym.flags() & INTERFACE) != 0 ?
  1855             supertype(bounds.head) : null;
  1856         setBounds(t, bounds, supertype);
  1857         t.rank_field = -1;
  1859     // </editor-fold>
  1861     // <editor-fold defaultstate="collapsed" desc="getBounds">
  1862     /**
  1863      * Return list of bounds of the given type variable.
  1864      */
  1865     public List<Type> getBounds(TypeVar t) {
  1866         if (t.bound.isErroneous() || !t.bound.isCompound())
  1867             return List.of(t.bound);
  1868         else if ((erasure(t).tsym.flags() & INTERFACE) == 0)
  1869             return interfaces(t).prepend(supertype(t));
  1870         else
  1871             // No superclass was given in bounds.
  1872             // In this case, supertype is Object, erasure is first interface.
  1873             return interfaces(t);
  1875     // </editor-fold>
  1877     // <editor-fold defaultstate="collapsed" desc="classBound">
  1878     /**
  1879      * If the given type is a (possibly selected) type variable,
  1880      * return the bounding class of this type, otherwise return the
  1881      * type itself.
  1882      */
  1883     public Type classBound(Type t) {
  1884         return classBound.visit(t);
  1886     // where
  1887         private UnaryVisitor<Type> classBound = new UnaryVisitor<Type>() {
  1889             public Type visitType(Type t, Void ignored) {
  1890                 return t;
  1893             @Override
  1894             public Type visitClassType(ClassType t, Void ignored) {
  1895                 Type outer1 = classBound(t.getEnclosingType());
  1896                 if (outer1 != t.getEnclosingType())
  1897                     return new ClassType(outer1, t.getTypeArguments(), t.tsym);
  1898                 else
  1899                     return t;
  1902             @Override
  1903             public Type visitTypeVar(TypeVar t, Void ignored) {
  1904                 return classBound(supertype(t));
  1907             @Override
  1908             public Type visitErrorType(ErrorType t, Void ignored) {
  1909                 return t;
  1911         };
  1912     // </editor-fold>
  1914     // <editor-fold defaultstate="collapsed" desc="sub signature / override equivalence">
  1915     /**
  1916      * Returns true iff the first signature is a <em>sub
  1917      * signature</em> of the other.  This is <b>not</b> an equivalence
  1918      * relation.
  1920      * @see "The Java Language Specification, Third Ed. (8.4.2)."
  1921      * @see #overrideEquivalent(Type t, Type s)
  1922      * @param t first signature (possibly raw).
  1923      * @param s second signature (could be subjected to erasure).
  1924      * @return true if t is a sub signature of s.
  1925      */
  1926     public boolean isSubSignature(Type t, Type s) {
  1927         return hasSameArgs(t, s) || hasSameArgs(t, erasure(s));
  1930     /**
  1931      * Returns true iff these signatures are related by <em>override
  1932      * equivalence</em>.  This is the natural extension of
  1933      * isSubSignature to an equivalence relation.
  1935      * @see "The Java Language Specification, Third Ed. (8.4.2)."
  1936      * @see #isSubSignature(Type t, Type s)
  1937      * @param t a signature (possible raw, could be subjected to
  1938      * erasure).
  1939      * @param s a signature (possible raw, could be subjected to
  1940      * erasure).
  1941      * @return true if either argument is a sub signature of the other.
  1942      */
  1943     public boolean overrideEquivalent(Type t, Type s) {
  1944         return hasSameArgs(t, s) ||
  1945             hasSameArgs(t, erasure(s)) || hasSameArgs(erasure(t), s);
  1948     private WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, MethodSymbol>>> implCache_check =
  1949             new WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, MethodSymbol>>>();
  1951     private WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, MethodSymbol>>> implCache_nocheck =
  1952             new WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, MethodSymbol>>>();
  1954     public MethodSymbol implementation(MethodSymbol ms, TypeSymbol origin, Types types, boolean checkResult) {
  1955         Map<MethodSymbol, SoftReference<Map<TypeSymbol, MethodSymbol>>> implCache = checkResult ?
  1956             implCache_check : implCache_nocheck;
  1957         SoftReference<Map<TypeSymbol, MethodSymbol>> ref_cache = implCache.get(ms);
  1958         Map<TypeSymbol, MethodSymbol> cache = ref_cache != null ? ref_cache.get() : null;
  1959         if (cache == null) {
  1960             cache = new HashMap<TypeSymbol, MethodSymbol>();
  1961             implCache.put(ms, new SoftReference<Map<TypeSymbol, MethodSymbol>>(cache));
  1963         MethodSymbol impl = cache.get(origin);
  1964         if (impl == null) {
  1965             for (Type t = origin.type; t.tag == CLASS || t.tag == TYPEVAR; t = types.supertype(t)) {
  1966                 while (t.tag == TYPEVAR)
  1967                     t = t.getUpperBound();
  1968                 TypeSymbol c = t.tsym;
  1969                 for (Scope.Entry e = c.members().lookup(ms.name);
  1970                      e.scope != null;
  1971                      e = e.next()) {
  1972                     if (e.sym.kind == Kinds.MTH) {
  1973                         MethodSymbol m = (MethodSymbol) e.sym;
  1974                         if (m.overrides(ms, origin, types, checkResult) &&
  1975                             (m.flags() & SYNTHETIC) == 0) {
  1976                             impl = m;
  1977                             cache.put(origin, m);
  1978                             return impl;
  1984         return impl;
  1987     /**
  1988      * Does t have the same arguments as s?  It is assumed that both
  1989      * types are (possibly polymorphic) method types.  Monomorphic
  1990      * method types "have the same arguments", if their argument lists
  1991      * are equal.  Polymorphic method types "have the same arguments",
  1992      * if they have the same arguments after renaming all type
  1993      * variables of one to corresponding type variables in the other,
  1994      * where correspondence is by position in the type parameter list.
  1995      */
  1996     public boolean hasSameArgs(Type t, Type s) {
  1997         return hasSameArgs.visit(t, s);
  1999     // where
  2000         private TypeRelation hasSameArgs = new TypeRelation() {
  2002             public Boolean visitType(Type t, Type s) {
  2003                 throw new AssertionError();
  2006             @Override
  2007             public Boolean visitMethodType(MethodType t, Type s) {
  2008                 return s.tag == METHOD
  2009                     && containsTypeEquivalent(t.argtypes, s.getParameterTypes());
  2012             @Override
  2013             public Boolean visitForAll(ForAll t, Type s) {
  2014                 if (s.tag != FORALL)
  2015                     return false;
  2017                 ForAll forAll = (ForAll)s;
  2018                 return hasSameBounds(t, forAll)
  2019                     && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
  2022             @Override
  2023             public Boolean visitErrorType(ErrorType t, Type s) {
  2024                 return false;
  2026         };
  2027     // </editor-fold>
  2029     // <editor-fold defaultstate="collapsed" desc="subst">
  2030     public List<Type> subst(List<Type> ts,
  2031                             List<Type> from,
  2032                             List<Type> to) {
  2033         return new Subst(from, to).subst(ts);
  2036     /**
  2037      * Substitute all occurrences of a type in `from' with the
  2038      * corresponding type in `to' in 't'. Match lists `from' and `to'
  2039      * from the right: If lists have different length, discard leading
  2040      * elements of the longer list.
  2041      */
  2042     public Type subst(Type t, List<Type> from, List<Type> to) {
  2043         return new Subst(from, to).subst(t);
  2046     private class Subst extends UnaryVisitor<Type> {
  2047         List<Type> from;
  2048         List<Type> to;
  2050         public Subst(List<Type> from, List<Type> to) {
  2051             int fromLength = from.length();
  2052             int toLength = to.length();
  2053             while (fromLength > toLength) {
  2054                 fromLength--;
  2055                 from = from.tail;
  2057             while (fromLength < toLength) {
  2058                 toLength--;
  2059                 to = to.tail;
  2061             this.from = from;
  2062             this.to = to;
  2065         Type subst(Type t) {
  2066             if (from.tail == null)
  2067                 return t;
  2068             else
  2069                 return visit(t);
  2072         List<Type> subst(List<Type> ts) {
  2073             if (from.tail == null)
  2074                 return ts;
  2075             boolean wild = false;
  2076             if (ts.nonEmpty() && from.nonEmpty()) {
  2077                 Type head1 = subst(ts.head);
  2078                 List<Type> tail1 = subst(ts.tail);
  2079                 if (head1 != ts.head || tail1 != ts.tail)
  2080                     return tail1.prepend(head1);
  2082             return ts;
  2085         public Type visitType(Type t, Void ignored) {
  2086             return t;
  2089         @Override
  2090         public Type visitMethodType(MethodType t, Void ignored) {
  2091             List<Type> argtypes = subst(t.argtypes);
  2092             Type restype = subst(t.restype);
  2093             List<Type> thrown = subst(t.thrown);
  2094             if (argtypes == t.argtypes &&
  2095                 restype == t.restype &&
  2096                 thrown == t.thrown)
  2097                 return t;
  2098             else
  2099                 return new MethodType(argtypes, restype, thrown, t.tsym);
  2102         @Override
  2103         public Type visitTypeVar(TypeVar t, Void ignored) {
  2104             for (List<Type> from = this.from, to = this.to;
  2105                  from.nonEmpty();
  2106                  from = from.tail, to = to.tail) {
  2107                 if (t == from.head) {
  2108                     return to.head.withTypeVar(t);
  2111             return t;
  2114         @Override
  2115         public Type visitClassType(ClassType t, Void ignored) {
  2116             if (!t.isCompound()) {
  2117                 List<Type> typarams = t.getTypeArguments();
  2118                 List<Type> typarams1 = subst(typarams);
  2119                 Type outer = t.getEnclosingType();
  2120                 Type outer1 = subst(outer);
  2121                 if (typarams1 == typarams && outer1 == outer)
  2122                     return t;
  2123                 else
  2124                     return new ClassType(outer1, typarams1, t.tsym);
  2125             } else {
  2126                 Type st = subst(supertype(t));
  2127                 List<Type> is = upperBounds(subst(interfaces(t)));
  2128                 if (st == supertype(t) && is == interfaces(t))
  2129                     return t;
  2130                 else
  2131                     return makeCompoundType(is.prepend(st));
  2135         @Override
  2136         public Type visitWildcardType(WildcardType t, Void ignored) {
  2137             Type bound = t.type;
  2138             if (t.kind != BoundKind.UNBOUND)
  2139                 bound = subst(bound);
  2140             if (bound == t.type) {
  2141                 return t;
  2142             } else {
  2143                 if (t.isExtendsBound() && bound.isExtendsBound())
  2144                     bound = upperBound(bound);
  2145                 return new WildcardType(bound, t.kind, syms.boundClass, t.bound);
  2149         @Override
  2150         public Type visitArrayType(ArrayType t, Void ignored) {
  2151             Type elemtype = subst(t.elemtype);
  2152             if (elemtype == t.elemtype)
  2153                 return t;
  2154             else
  2155                 return new ArrayType(upperBound(elemtype), t.tsym);
  2158         @Override
  2159         public Type visitForAll(ForAll t, Void ignored) {
  2160             List<Type> tvars1 = substBounds(t.tvars, from, to);
  2161             Type qtype1 = subst(t.qtype);
  2162             if (tvars1 == t.tvars && qtype1 == t.qtype) {
  2163                 return t;
  2164             } else if (tvars1 == t.tvars) {
  2165                 return new ForAll(tvars1, qtype1);
  2166             } else {
  2167                 return new ForAll(tvars1, Types.this.subst(qtype1, t.tvars, tvars1));
  2171         @Override
  2172         public Type visitErrorType(ErrorType t, Void ignored) {
  2173             return t;
  2177     public List<Type> substBounds(List<Type> tvars,
  2178                                   List<Type> from,
  2179                                   List<Type> to) {
  2180         if (tvars.isEmpty())
  2181             return tvars;
  2182         ListBuffer<Type> newBoundsBuf = lb();
  2183         boolean changed = false;
  2184         // calculate new bounds
  2185         for (Type t : tvars) {
  2186             TypeVar tv = (TypeVar) t;
  2187             Type bound = subst(tv.bound, from, to);
  2188             if (bound != tv.bound)
  2189                 changed = true;
  2190             newBoundsBuf.append(bound);
  2192         if (!changed)
  2193             return tvars;
  2194         ListBuffer<Type> newTvars = lb();
  2195         // create new type variables without bounds
  2196         for (Type t : tvars) {
  2197             newTvars.append(new TypeVar(t.tsym, null, syms.botType));
  2199         // the new bounds should use the new type variables in place
  2200         // of the old
  2201         List<Type> newBounds = newBoundsBuf.toList();
  2202         from = tvars;
  2203         to = newTvars.toList();
  2204         for (; !newBounds.isEmpty(); newBounds = newBounds.tail) {
  2205             newBounds.head = subst(newBounds.head, from, to);
  2207         newBounds = newBoundsBuf.toList();
  2208         // set the bounds of new type variables to the new bounds
  2209         for (Type t : newTvars.toList()) {
  2210             TypeVar tv = (TypeVar) t;
  2211             tv.bound = newBounds.head;
  2212             newBounds = newBounds.tail;
  2214         return newTvars.toList();
  2217     public TypeVar substBound(TypeVar t, List<Type> from, List<Type> to) {
  2218         Type bound1 = subst(t.bound, from, to);
  2219         if (bound1 == t.bound)
  2220             return t;
  2221         else {
  2222             // create new type variable without bounds
  2223             TypeVar tv = new TypeVar(t.tsym, null, syms.botType);
  2224             // the new bound should use the new type variable in place
  2225             // of the old
  2226             tv.bound = subst(bound1, List.<Type>of(t), List.<Type>of(tv));
  2227             return tv;
  2230     // </editor-fold>
  2232     // <editor-fold defaultstate="collapsed" desc="hasSameBounds">
  2233     /**
  2234      * Does t have the same bounds for quantified variables as s?
  2235      */
  2236     boolean hasSameBounds(ForAll t, ForAll s) {
  2237         List<Type> l1 = t.tvars;
  2238         List<Type> l2 = s.tvars;
  2239         while (l1.nonEmpty() && l2.nonEmpty() &&
  2240                isSameType(l1.head.getUpperBound(),
  2241                           subst(l2.head.getUpperBound(),
  2242                                 s.tvars,
  2243                                 t.tvars))) {
  2244             l1 = l1.tail;
  2245             l2 = l2.tail;
  2247         return l1.isEmpty() && l2.isEmpty();
  2249     // </editor-fold>
  2251     // <editor-fold defaultstate="collapsed" desc="newInstances">
  2252     /** Create new vector of type variables from list of variables
  2253      *  changing all recursive bounds from old to new list.
  2254      */
  2255     public List<Type> newInstances(List<Type> tvars) {
  2256         List<Type> tvars1 = Type.map(tvars, newInstanceFun);
  2257         for (List<Type> l = tvars1; l.nonEmpty(); l = l.tail) {
  2258             TypeVar tv = (TypeVar) l.head;
  2259             tv.bound = subst(tv.bound, tvars, tvars1);
  2261         return tvars1;
  2263     static private Mapping newInstanceFun = new Mapping("newInstanceFun") {
  2264             public Type apply(Type t) { return new TypeVar(t.tsym, t.getUpperBound(), t.getLowerBound()); }
  2265         };
  2266     // </editor-fold>
  2268     // <editor-fold defaultstate="collapsed" desc="createErrorType">
  2269     public Type createErrorType(Type originalType) {
  2270         return new ErrorType(originalType, syms.errSymbol);
  2273     public Type createErrorType(ClassSymbol c, Type originalType) {
  2274         return new ErrorType(c, originalType);
  2277     public Type createErrorType(Name name, TypeSymbol container, Type originalType) {
  2278         return new ErrorType(name, container, originalType);
  2280     // </editor-fold>
  2282     // <editor-fold defaultstate="collapsed" desc="rank">
  2283     /**
  2284      * The rank of a class is the length of the longest path between
  2285      * the class and java.lang.Object in the class inheritance
  2286      * graph. Undefined for all but reference types.
  2287      */
  2288     public int rank(Type t) {
  2289         switch(t.tag) {
  2290         case CLASS: {
  2291             ClassType cls = (ClassType)t;
  2292             if (cls.rank_field < 0) {
  2293                 Name fullname = cls.tsym.getQualifiedName();
  2294                 if (fullname == names.java_lang_Object)
  2295                     cls.rank_field = 0;
  2296                 else {
  2297                     int r = rank(supertype(cls));
  2298                     for (List<Type> l = interfaces(cls);
  2299                          l.nonEmpty();
  2300                          l = l.tail) {
  2301                         if (rank(l.head) > r)
  2302                             r = rank(l.head);
  2304                     cls.rank_field = r + 1;
  2307             return cls.rank_field;
  2309         case TYPEVAR: {
  2310             TypeVar tvar = (TypeVar)t;
  2311             if (tvar.rank_field < 0) {
  2312                 int r = rank(supertype(tvar));
  2313                 for (List<Type> l = interfaces(tvar);
  2314                      l.nonEmpty();
  2315                      l = l.tail) {
  2316                     if (rank(l.head) > r) r = rank(l.head);
  2318                 tvar.rank_field = r + 1;
  2320             return tvar.rank_field;
  2322         case ERROR:
  2323             return 0;
  2324         default:
  2325             throw new AssertionError();
  2328     // </editor-fold>
  2330     /**
  2331      * Helper method for generating a string representation of a given type
  2332      * accordingly to a given locale
  2333      */
  2334     public String toString(Type t, Locale locale) {
  2335         return Printer.createStandardPrinter(messages).visit(t, locale);
  2338     /**
  2339      * Helper method for generating a string representation of a given type
  2340      * accordingly to a given locale
  2341      */
  2342     public String toString(Symbol t, Locale locale) {
  2343         return Printer.createStandardPrinter(messages).visit(t, locale);
  2346     // <editor-fold defaultstate="collapsed" desc="toString">
  2347     /**
  2348      * This toString is slightly more descriptive than the one on Type.
  2350      * @deprecated Types.toString(Type t, Locale l) provides better support
  2351      * for localization
  2352      */
  2353     @Deprecated
  2354     public String toString(Type t) {
  2355         if (t.tag == FORALL) {
  2356             ForAll forAll = (ForAll)t;
  2357             return typaramsString(forAll.tvars) + forAll.qtype;
  2359         return "" + t;
  2361     // where
  2362         private String typaramsString(List<Type> tvars) {
  2363             StringBuffer s = new StringBuffer();
  2364             s.append('<');
  2365             boolean first = true;
  2366             for (Type t : tvars) {
  2367                 if (!first) s.append(", ");
  2368                 first = false;
  2369                 appendTyparamString(((TypeVar)t), s);
  2371             s.append('>');
  2372             return s.toString();
  2374         private void appendTyparamString(TypeVar t, StringBuffer buf) {
  2375             buf.append(t);
  2376             if (t.bound == null ||
  2377                 t.bound.tsym.getQualifiedName() == names.java_lang_Object)
  2378                 return;
  2379             buf.append(" extends "); // Java syntax; no need for i18n
  2380             Type bound = t.bound;
  2381             if (!bound.isCompound()) {
  2382                 buf.append(bound);
  2383             } else if ((erasure(t).tsym.flags() & INTERFACE) == 0) {
  2384                 buf.append(supertype(t));
  2385                 for (Type intf : interfaces(t)) {
  2386                     buf.append('&');
  2387                     buf.append(intf);
  2389             } else {
  2390                 // No superclass was given in bounds.
  2391                 // In this case, supertype is Object, erasure is first interface.
  2392                 boolean first = true;
  2393                 for (Type intf : interfaces(t)) {
  2394                     if (!first) buf.append('&');
  2395                     first = false;
  2396                     buf.append(intf);
  2400     // </editor-fold>
  2402     // <editor-fold defaultstate="collapsed" desc="Determining least upper bounds of types">
  2403     /**
  2404      * A cache for closures.
  2406      * <p>A closure is a list of all the supertypes and interfaces of
  2407      * a class or interface type, ordered by ClassSymbol.precedes
  2408      * (that is, subclasses come first, arbitrary but fixed
  2409      * otherwise).
  2410      */
  2411     private Map<Type,List<Type>> closureCache = new HashMap<Type,List<Type>>();
  2413     /**
  2414      * Returns the closure of a class or interface type.
  2415      */
  2416     public List<Type> closure(Type t) {
  2417         List<Type> cl = closureCache.get(t);
  2418         if (cl == null) {
  2419             Type st = supertype(t);
  2420             if (!t.isCompound()) {
  2421                 if (st.tag == CLASS) {
  2422                     cl = insert(closure(st), t);
  2423                 } else if (st.tag == TYPEVAR) {
  2424                     cl = closure(st).prepend(t);
  2425                 } else {
  2426                     cl = List.of(t);
  2428             } else {
  2429                 cl = closure(supertype(t));
  2431             for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail)
  2432                 cl = union(cl, closure(l.head));
  2433             closureCache.put(t, cl);
  2435         return cl;
  2438     /**
  2439      * Insert a type in a closure
  2440      */
  2441     public List<Type> insert(List<Type> cl, Type t) {
  2442         if (cl.isEmpty() || t.tsym.precedes(cl.head.tsym, this)) {
  2443             return cl.prepend(t);
  2444         } else if (cl.head.tsym.precedes(t.tsym, this)) {
  2445             return insert(cl.tail, t).prepend(cl.head);
  2446         } else {
  2447             return cl;
  2451     /**
  2452      * Form the union of two closures
  2453      */
  2454     public List<Type> union(List<Type> cl1, List<Type> cl2) {
  2455         if (cl1.isEmpty()) {
  2456             return cl2;
  2457         } else if (cl2.isEmpty()) {
  2458             return cl1;
  2459         } else if (cl1.head.tsym.precedes(cl2.head.tsym, this)) {
  2460             return union(cl1.tail, cl2).prepend(cl1.head);
  2461         } else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) {
  2462             return union(cl1, cl2.tail).prepend(cl2.head);
  2463         } else {
  2464             return union(cl1.tail, cl2.tail).prepend(cl1.head);
  2468     /**
  2469      * Intersect two closures
  2470      */
  2471     public List<Type> intersect(List<Type> cl1, List<Type> cl2) {
  2472         if (cl1 == cl2)
  2473             return cl1;
  2474         if (cl1.isEmpty() || cl2.isEmpty())
  2475             return List.nil();
  2476         if (cl1.head.tsym.precedes(cl2.head.tsym, this))
  2477             return intersect(cl1.tail, cl2);
  2478         if (cl2.head.tsym.precedes(cl1.head.tsym, this))
  2479             return intersect(cl1, cl2.tail);
  2480         if (isSameType(cl1.head, cl2.head))
  2481             return intersect(cl1.tail, cl2.tail).prepend(cl1.head);
  2482         if (cl1.head.tsym == cl2.head.tsym &&
  2483             cl1.head.tag == CLASS && cl2.head.tag == CLASS) {
  2484             if (cl1.head.isParameterized() && cl2.head.isParameterized()) {
  2485                 Type merge = merge(cl1.head,cl2.head);
  2486                 return intersect(cl1.tail, cl2.tail).prepend(merge);
  2488             if (cl1.head.isRaw() || cl2.head.isRaw())
  2489                 return intersect(cl1.tail, cl2.tail).prepend(erasure(cl1.head));
  2491         return intersect(cl1.tail, cl2.tail);
  2493     // where
  2494         class TypePair {
  2495             final Type t1;
  2496             final Type t2;
  2497             TypePair(Type t1, Type t2) {
  2498                 this.t1 = t1;
  2499                 this.t2 = t2;
  2501             @Override
  2502             public int hashCode() {
  2503                 return 127 * Types.this.hashCode(t1) + Types.this.hashCode(t2);
  2505             @Override
  2506             public boolean equals(Object obj) {
  2507                 if (!(obj instanceof TypePair))
  2508                     return false;
  2509                 TypePair typePair = (TypePair)obj;
  2510                 return isSameType(t1, typePair.t1)
  2511                     && isSameType(t2, typePair.t2);
  2514         Set<TypePair> mergeCache = new HashSet<TypePair>();
  2515         private Type merge(Type c1, Type c2) {
  2516             ClassType class1 = (ClassType) c1;
  2517             List<Type> act1 = class1.getTypeArguments();
  2518             ClassType class2 = (ClassType) c2;
  2519             List<Type> act2 = class2.getTypeArguments();
  2520             ListBuffer<Type> merged = new ListBuffer<Type>();
  2521             List<Type> typarams = class1.tsym.type.getTypeArguments();
  2523             while (act1.nonEmpty() && act2.nonEmpty() && typarams.nonEmpty()) {
  2524                 if (containsType(act1.head, act2.head)) {
  2525                     merged.append(act1.head);
  2526                 } else if (containsType(act2.head, act1.head)) {
  2527                     merged.append(act2.head);
  2528                 } else {
  2529                     TypePair pair = new TypePair(c1, c2);
  2530                     Type m;
  2531                     if (mergeCache.add(pair)) {
  2532                         m = new WildcardType(lub(upperBound(act1.head),
  2533                                                  upperBound(act2.head)),
  2534                                              BoundKind.EXTENDS,
  2535                                              syms.boundClass);
  2536                         mergeCache.remove(pair);
  2537                     } else {
  2538                         m = new WildcardType(syms.objectType,
  2539                                              BoundKind.UNBOUND,
  2540                                              syms.boundClass);
  2542                     merged.append(m.withTypeVar(typarams.head));
  2544                 act1 = act1.tail;
  2545                 act2 = act2.tail;
  2546                 typarams = typarams.tail;
  2548             assert(act1.isEmpty() && act2.isEmpty() && typarams.isEmpty());
  2549             return new ClassType(class1.getEnclosingType(), merged.toList(), class1.tsym);
  2552     /**
  2553      * Return the minimum type of a closure, a compound type if no
  2554      * unique minimum exists.
  2555      */
  2556     private Type compoundMin(List<Type> cl) {
  2557         if (cl.isEmpty()) return syms.objectType;
  2558         List<Type> compound = closureMin(cl);
  2559         if (compound.isEmpty())
  2560             return null;
  2561         else if (compound.tail.isEmpty())
  2562             return compound.head;
  2563         else
  2564             return makeCompoundType(compound);
  2567     /**
  2568      * Return the minimum types of a closure, suitable for computing
  2569      * compoundMin or glb.
  2570      */
  2571     private List<Type> closureMin(List<Type> cl) {
  2572         ListBuffer<Type> classes = lb();
  2573         ListBuffer<Type> interfaces = lb();
  2574         while (!cl.isEmpty()) {
  2575             Type current = cl.head;
  2576             if (current.isInterface())
  2577                 interfaces.append(current);
  2578             else
  2579                 classes.append(current);
  2580             ListBuffer<Type> candidates = lb();
  2581             for (Type t : cl.tail) {
  2582                 if (!isSubtypeNoCapture(current, t))
  2583                     candidates.append(t);
  2585             cl = candidates.toList();
  2587         return classes.appendList(interfaces).toList();
  2590     /**
  2591      * Return the least upper bound of pair of types.  if the lub does
  2592      * not exist return null.
  2593      */
  2594     public Type lub(Type t1, Type t2) {
  2595         return lub(List.of(t1, t2));
  2598     /**
  2599      * Return the least upper bound (lub) of set of types.  If the lub
  2600      * does not exist return the type of null (bottom).
  2601      */
  2602     public Type lub(List<Type> ts) {
  2603         final int ARRAY_BOUND = 1;
  2604         final int CLASS_BOUND = 2;
  2605         int boundkind = 0;
  2606         for (Type t : ts) {
  2607             switch (t.tag) {
  2608             case CLASS:
  2609                 boundkind |= CLASS_BOUND;
  2610                 break;
  2611             case ARRAY:
  2612                 boundkind |= ARRAY_BOUND;
  2613                 break;
  2614             case  TYPEVAR:
  2615                 do {
  2616                     t = t.getUpperBound();
  2617                 } while (t.tag == TYPEVAR);
  2618                 if (t.tag == ARRAY) {
  2619                     boundkind |= ARRAY_BOUND;
  2620                 } else {
  2621                     boundkind |= CLASS_BOUND;
  2623                 break;
  2624             default:
  2625                 if (t.isPrimitive())
  2626                     return syms.errType;
  2629         switch (boundkind) {
  2630         case 0:
  2631             return syms.botType;
  2633         case ARRAY_BOUND:
  2634             // calculate lub(A[], B[])
  2635             List<Type> elements = Type.map(ts, elemTypeFun);
  2636             for (Type t : elements) {
  2637                 if (t.isPrimitive()) {
  2638                     // if a primitive type is found, then return
  2639                     // arraySuperType unless all the types are the
  2640                     // same
  2641                     Type first = ts.head;
  2642                     for (Type s : ts.tail) {
  2643                         if (!isSameType(first, s)) {
  2644                              // lub(int[], B[]) is Cloneable & Serializable
  2645                             return arraySuperType();
  2648                     // all the array types are the same, return one
  2649                     // lub(int[], int[]) is int[]
  2650                     return first;
  2653             // lub(A[], B[]) is lub(A, B)[]
  2654             return new ArrayType(lub(elements), syms.arrayClass);
  2656         case CLASS_BOUND:
  2657             // calculate lub(A, B)
  2658             while (ts.head.tag != CLASS && ts.head.tag != TYPEVAR)
  2659                 ts = ts.tail;
  2660             assert !ts.isEmpty();
  2661             List<Type> cl = closure(ts.head);
  2662             for (Type t : ts.tail) {
  2663                 if (t.tag == CLASS || t.tag == TYPEVAR)
  2664                     cl = intersect(cl, closure(t));
  2666             return compoundMin(cl);
  2668         default:
  2669             // calculate lub(A, B[])
  2670             List<Type> classes = List.of(arraySuperType());
  2671             for (Type t : ts) {
  2672                 if (t.tag != ARRAY) // Filter out any arrays
  2673                     classes = classes.prepend(t);
  2675             // lub(A, B[]) is lub(A, arraySuperType)
  2676             return lub(classes);
  2679     // where
  2680         private Type arraySuperType = null;
  2681         private Type arraySuperType() {
  2682             // initialized lazily to avoid problems during compiler startup
  2683             if (arraySuperType == null) {
  2684                 synchronized (this) {
  2685                     if (arraySuperType == null) {
  2686                         // JLS 10.8: all arrays implement Cloneable and Serializable.
  2687                         arraySuperType = makeCompoundType(List.of(syms.serializableType,
  2688                                                                   syms.cloneableType),
  2689                                                           syms.objectType);
  2693             return arraySuperType;
  2695     // </editor-fold>
  2697     // <editor-fold defaultstate="collapsed" desc="Greatest lower bound">
  2698     public Type glb(List<Type> ts) {
  2699         Type t1 = ts.head;
  2700         for (Type t2 : ts.tail) {
  2701             if (t1.isErroneous())
  2702                 return t1;
  2703             t1 = glb(t1, t2);
  2705         return t1;
  2707     //where
  2708     public Type glb(Type t, Type s) {
  2709         if (s == null)
  2710             return t;
  2711         else if (isSubtypeNoCapture(t, s))
  2712             return t;
  2713         else if (isSubtypeNoCapture(s, t))
  2714             return s;
  2716         List<Type> closure = union(closure(t), closure(s));
  2717         List<Type> bounds = closureMin(closure);
  2719         if (bounds.isEmpty()) {             // length == 0
  2720             return syms.objectType;
  2721         } else if (bounds.tail.isEmpty()) { // length == 1
  2722             return bounds.head;
  2723         } else {                            // length > 1
  2724             int classCount = 0;
  2725             for (Type bound : bounds)
  2726                 if (!bound.isInterface())
  2727                     classCount++;
  2728             if (classCount > 1)
  2729                 return createErrorType(t);
  2731         return makeCompoundType(bounds);
  2733     // </editor-fold>
  2735     // <editor-fold defaultstate="collapsed" desc="hashCode">
  2736     /**
  2737      * Compute a hash code on a type.
  2738      */
  2739     public static int hashCode(Type t) {
  2740         return hashCode.visit(t);
  2742     // where
  2743         private static final UnaryVisitor<Integer> hashCode = new UnaryVisitor<Integer>() {
  2745             public Integer visitType(Type t, Void ignored) {
  2746                 return t.tag;
  2749             @Override
  2750             public Integer visitClassType(ClassType t, Void ignored) {
  2751                 int result = visit(t.getEnclosingType());
  2752                 result *= 127;
  2753                 result += t.tsym.flatName().hashCode();
  2754                 for (Type s : t.getTypeArguments()) {
  2755                     result *= 127;
  2756                     result += visit(s);
  2758                 return result;
  2761             @Override
  2762             public Integer visitWildcardType(WildcardType t, Void ignored) {
  2763                 int result = t.kind.hashCode();
  2764                 if (t.type != null) {
  2765                     result *= 127;
  2766                     result += visit(t.type);
  2768                 return result;
  2771             @Override
  2772             public Integer visitArrayType(ArrayType t, Void ignored) {
  2773                 return visit(t.elemtype) + 12;
  2776             @Override
  2777             public Integer visitTypeVar(TypeVar t, Void ignored) {
  2778                 return System.identityHashCode(t.tsym);
  2781             @Override
  2782             public Integer visitUndetVar(UndetVar t, Void ignored) {
  2783                 return System.identityHashCode(t);
  2786             @Override
  2787             public Integer visitErrorType(ErrorType t, Void ignored) {
  2788                 return 0;
  2790         };
  2791     // </editor-fold>
  2793     // <editor-fold defaultstate="collapsed" desc="Return-Type-Substitutable">
  2794     /**
  2795      * Does t have a result that is a subtype of the result type of s,
  2796      * suitable for covariant returns?  It is assumed that both types
  2797      * are (possibly polymorphic) method types.  Monomorphic method
  2798      * types are handled in the obvious way.  Polymorphic method types
  2799      * require renaming all type variables of one to corresponding
  2800      * type variables in the other, where correspondence is by
  2801      * position in the type parameter list. */
  2802     public boolean resultSubtype(Type t, Type s, Warner warner) {
  2803         List<Type> tvars = t.getTypeArguments();
  2804         List<Type> svars = s.getTypeArguments();
  2805         Type tres = t.getReturnType();
  2806         Type sres = subst(s.getReturnType(), svars, tvars);
  2807         return covariantReturnType(tres, sres, warner);
  2810     /**
  2811      * Return-Type-Substitutable.
  2812      * @see <a href="http://java.sun.com/docs/books/jls/">The Java
  2813      * Language Specification, Third Ed. (8.4.5)</a>
  2814      */
  2815     public boolean returnTypeSubstitutable(Type r1, Type r2) {
  2816         if (hasSameArgs(r1, r2))
  2817             return resultSubtype(r1, r2, Warner.noWarnings);
  2818         else
  2819             return covariantReturnType(r1.getReturnType(),
  2820                                        erasure(r2.getReturnType()),
  2821                                        Warner.noWarnings);
  2824     public boolean returnTypeSubstitutable(Type r1,
  2825                                            Type r2, Type r2res,
  2826                                            Warner warner) {
  2827         if (isSameType(r1.getReturnType(), r2res))
  2828             return true;
  2829         if (r1.getReturnType().isPrimitive() || r2res.isPrimitive())
  2830             return false;
  2832         if (hasSameArgs(r1, r2))
  2833             return covariantReturnType(r1.getReturnType(), r2res, warner);
  2834         if (!source.allowCovariantReturns())
  2835             return false;
  2836         if (isSubtypeUnchecked(r1.getReturnType(), r2res, warner))
  2837             return true;
  2838         if (!isSubtype(r1.getReturnType(), erasure(r2res)))
  2839             return false;
  2840         warner.warnUnchecked();
  2841         return true;
  2844     /**
  2845      * Is t an appropriate return type in an overrider for a
  2846      * method that returns s?
  2847      */
  2848     public boolean covariantReturnType(Type t, Type s, Warner warner) {
  2849         return
  2850             isSameType(t, s) ||
  2851             source.allowCovariantReturns() &&
  2852             !t.isPrimitive() &&
  2853             !s.isPrimitive() &&
  2854             isAssignable(t, s, warner);
  2856     // </editor-fold>
  2858     // <editor-fold defaultstate="collapsed" desc="Box/unbox support">
  2859     /**
  2860      * Return the class that boxes the given primitive.
  2861      */
  2862     public ClassSymbol boxedClass(Type t) {
  2863         return reader.enterClass(syms.boxedName[t.tag]);
  2866     /**
  2867      * Return the primitive type corresponding to a boxed type.
  2868      */
  2869     public Type unboxedType(Type t) {
  2870         if (allowBoxing) {
  2871             for (int i=0; i<syms.boxedName.length; i++) {
  2872                 Name box = syms.boxedName[i];
  2873                 if (box != null &&
  2874                     asSuper(t, reader.enterClass(box)) != null)
  2875                     return syms.typeOfTag[i];
  2878         return Type.noType;
  2880     // </editor-fold>
  2882     // <editor-fold defaultstate="collapsed" desc="Capture conversion">
  2883     /*
  2884      * JLS 3rd Ed. 5.1.10 Capture Conversion:
  2886      * Let G name a generic type declaration with n formal type
  2887      * parameters A1 ... An with corresponding bounds U1 ... Un. There
  2888      * exists a capture conversion from G<T1 ... Tn> to G<S1 ... Sn>,
  2889      * where, for 1 <= i <= n:
  2891      * + If Ti is a wildcard type argument (4.5.1) of the form ? then
  2892      *   Si is a fresh type variable whose upper bound is
  2893      *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is the null
  2894      *   type.
  2896      * + If Ti is a wildcard type argument of the form ? extends Bi,
  2897      *   then Si is a fresh type variable whose upper bound is
  2898      *   glb(Bi, Ui[A1 := S1, ..., An := Sn]) and whose lower bound is
  2899      *   the null type, where glb(V1,... ,Vm) is V1 & ... & Vm. It is
  2900      *   a compile-time error if for any two classes (not interfaces)
  2901      *   Vi and Vj,Vi is not a subclass of Vj or vice versa.
  2903      * + If Ti is a wildcard type argument of the form ? super Bi,
  2904      *   then Si is a fresh type variable whose upper bound is
  2905      *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is Bi.
  2907      * + Otherwise, Si = Ti.
  2909      * Capture conversion on any type other than a parameterized type
  2910      * (4.5) acts as an identity conversion (5.1.1). Capture
  2911      * conversions never require a special action at run time and
  2912      * therefore never throw an exception at run time.
  2914      * Capture conversion is not applied recursively.
  2915      */
  2916     /**
  2917      * Capture conversion as specified by JLS 3rd Ed.
  2918      */
  2920     public List<Type> capture(List<Type> ts) {
  2921         List<Type> buf = List.nil();
  2922         for (Type t : ts) {
  2923             buf = buf.prepend(capture(t));
  2925         return buf.reverse();
  2927     public Type capture(Type t) {
  2928         if (t.tag != CLASS)
  2929             return t;
  2930         ClassType cls = (ClassType)t;
  2931         if (cls.isRaw() || !cls.isParameterized())
  2932             return cls;
  2934         ClassType G = (ClassType)cls.asElement().asType();
  2935         List<Type> A = G.getTypeArguments();
  2936         List<Type> T = cls.getTypeArguments();
  2937         List<Type> S = freshTypeVariables(T);
  2939         List<Type> currentA = A;
  2940         List<Type> currentT = T;
  2941         List<Type> currentS = S;
  2942         boolean captured = false;
  2943         while (!currentA.isEmpty() &&
  2944                !currentT.isEmpty() &&
  2945                !currentS.isEmpty()) {
  2946             if (currentS.head != currentT.head) {
  2947                 captured = true;
  2948                 WildcardType Ti = (WildcardType)currentT.head;
  2949                 Type Ui = currentA.head.getUpperBound();
  2950                 CapturedType Si = (CapturedType)currentS.head;
  2951                 if (Ui == null)
  2952                     Ui = syms.objectType;
  2953                 switch (Ti.kind) {
  2954                 case UNBOUND:
  2955                     Si.bound = subst(Ui, A, S);
  2956                     Si.lower = syms.botType;
  2957                     break;
  2958                 case EXTENDS:
  2959                     Si.bound = glb(Ti.getExtendsBound(), subst(Ui, A, S));
  2960                     Si.lower = syms.botType;
  2961                     break;
  2962                 case SUPER:
  2963                     Si.bound = subst(Ui, A, S);
  2964                     Si.lower = Ti.getSuperBound();
  2965                     break;
  2967                 if (Si.bound == Si.lower)
  2968                     currentS.head = Si.bound;
  2970             currentA = currentA.tail;
  2971             currentT = currentT.tail;
  2972             currentS = currentS.tail;
  2974         if (!currentA.isEmpty() || !currentT.isEmpty() || !currentS.isEmpty())
  2975             return erasure(t); // some "rare" type involved
  2977         if (captured)
  2978             return new ClassType(cls.getEnclosingType(), S, cls.tsym);
  2979         else
  2980             return t;
  2982     // where
  2983         public List<Type> freshTypeVariables(List<Type> types) {
  2984             ListBuffer<Type> result = lb();
  2985             for (Type t : types) {
  2986                 if (t.tag == WILDCARD) {
  2987                     Type bound = ((WildcardType)t).getExtendsBound();
  2988                     if (bound == null)
  2989                         bound = syms.objectType;
  2990                     result.append(new CapturedType(capturedName,
  2991                                                    syms.noSymbol,
  2992                                                    bound,
  2993                                                    syms.botType,
  2994                                                    (WildcardType)t));
  2995                 } else {
  2996                     result.append(t);
  2999             return result.toList();
  3001     // </editor-fold>
  3003     // <editor-fold defaultstate="collapsed" desc="Internal utility methods">
  3004     private List<Type> upperBounds(List<Type> ss) {
  3005         if (ss.isEmpty()) return ss;
  3006         Type head = upperBound(ss.head);
  3007         List<Type> tail = upperBounds(ss.tail);
  3008         if (head != ss.head || tail != ss.tail)
  3009             return tail.prepend(head);
  3010         else
  3011             return ss;
  3014     private boolean sideCast(Type from, Type to, Warner warn) {
  3015         // We are casting from type $from$ to type $to$, which are
  3016         // non-final unrelated types.  This method
  3017         // tries to reject a cast by transferring type parameters
  3018         // from $to$ to $from$ by common superinterfaces.
  3019         boolean reverse = false;
  3020         Type target = to;
  3021         if ((to.tsym.flags() & INTERFACE) == 0) {
  3022             assert (from.tsym.flags() & INTERFACE) != 0;
  3023             reverse = true;
  3024             to = from;
  3025             from = target;
  3027         List<Type> commonSupers = superClosure(to, erasure(from));
  3028         boolean giveWarning = commonSupers.isEmpty();
  3029         // The arguments to the supers could be unified here to
  3030         // get a more accurate analysis
  3031         while (commonSupers.nonEmpty()) {
  3032             Type t1 = asSuper(from, commonSupers.head.tsym);
  3033             Type t2 = commonSupers.head; // same as asSuper(to, commonSupers.head.tsym);
  3034             if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
  3035                 return false;
  3036             giveWarning = giveWarning || (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2));
  3037             commonSupers = commonSupers.tail;
  3039         if (giveWarning && !isReifiable(reverse ? from : to))
  3040             warn.warnUnchecked();
  3041         if (!source.allowCovariantReturns())
  3042             // reject if there is a common method signature with
  3043             // incompatible return types.
  3044             chk.checkCompatibleAbstracts(warn.pos(), from, to);
  3045         return true;
  3048     private boolean sideCastFinal(Type from, Type to, Warner warn) {
  3049         // We are casting from type $from$ to type $to$, which are
  3050         // unrelated types one of which is final and the other of
  3051         // which is an interface.  This method
  3052         // tries to reject a cast by transferring type parameters
  3053         // from the final class to the interface.
  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         assert (from.tsym.flags() & FINAL) != 0;
  3063         Type t1 = asSuper(from, to.tsym);
  3064         if (t1 == null) return false;
  3065         Type t2 = to;
  3066         if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
  3067             return false;
  3068         if (!source.allowCovariantReturns())
  3069             // reject if there is a common method signature with
  3070             // incompatible return types.
  3071             chk.checkCompatibleAbstracts(warn.pos(), from, to);
  3072         if (!isReifiable(target) &&
  3073             (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2)))
  3074             warn.warnUnchecked();
  3075         return true;
  3078     private boolean giveWarning(Type from, Type to) {
  3079         Type subFrom = asSub(from, to.tsym);
  3080         return to.isParameterized() &&
  3081                 (!(isUnbounded(to) ||
  3082                 isSubtype(from, to) ||
  3083                 ((subFrom != null) && isSameType(subFrom, to))));
  3086     private List<Type> superClosure(Type t, Type s) {
  3087         List<Type> cl = List.nil();
  3088         for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
  3089             if (isSubtype(s, erasure(l.head))) {
  3090                 cl = insert(cl, l.head);
  3091             } else {
  3092                 cl = union(cl, superClosure(l.head, s));
  3095         return cl;
  3098     private boolean containsTypeEquivalent(Type t, Type s) {
  3099         return
  3100             isSameType(t, s) || // shortcut
  3101             containsType(t, s) && containsType(s, t);
  3104     // <editor-fold defaultstate="collapsed" desc="adapt">
  3105     /**
  3106      * Adapt a type by computing a substitution which maps a source
  3107      * type to a target type.
  3109      * @param source    the source type
  3110      * @param target    the target type
  3111      * @param from      the type variables of the computed substitution
  3112      * @param to        the types of the computed substitution.
  3113      */
  3114     public void adapt(Type source,
  3115                        Type target,
  3116                        ListBuffer<Type> from,
  3117                        ListBuffer<Type> to) throws AdaptFailure {
  3118         new Adapter(from, to).adapt(source, target);
  3121     class Adapter extends SimpleVisitor<Void, Type> {
  3123         ListBuffer<Type> from;
  3124         ListBuffer<Type> to;
  3125         Map<Symbol,Type> mapping;
  3127         Adapter(ListBuffer<Type> from, ListBuffer<Type> to) {
  3128             this.from = from;
  3129             this.to = to;
  3130             mapping = new HashMap<Symbol,Type>();
  3133         public void adapt(Type source, Type target) throws AdaptFailure {
  3134             visit(source, target);
  3135             List<Type> fromList = from.toList();
  3136             List<Type> toList = to.toList();
  3137             while (!fromList.isEmpty()) {
  3138                 Type val = mapping.get(fromList.head.tsym);
  3139                 if (toList.head != val)
  3140                     toList.head = val;
  3141                 fromList = fromList.tail;
  3142                 toList = toList.tail;
  3146         @Override
  3147         public Void visitClassType(ClassType source, Type target) throws AdaptFailure {
  3148             if (target.tag == CLASS)
  3149                 adaptRecursive(source.allparams(), target.allparams());
  3150             return null;
  3153         @Override
  3154         public Void visitArrayType(ArrayType source, Type target) throws AdaptFailure {
  3155             if (target.tag == ARRAY)
  3156                 adaptRecursive(elemtype(source), elemtype(target));
  3157             return null;
  3160         @Override
  3161         public Void visitWildcardType(WildcardType source, Type target) throws AdaptFailure {
  3162             if (source.isExtendsBound())
  3163                 adaptRecursive(upperBound(source), upperBound(target));
  3164             else if (source.isSuperBound())
  3165                 adaptRecursive(lowerBound(source), lowerBound(target));
  3166             return null;
  3169         @Override
  3170         public Void visitTypeVar(TypeVar source, Type target) throws AdaptFailure {
  3171             // Check to see if there is
  3172             // already a mapping for $source$, in which case
  3173             // the old mapping will be merged with the new
  3174             Type val = mapping.get(source.tsym);
  3175             if (val != null) {
  3176                 if (val.isSuperBound() && target.isSuperBound()) {
  3177                     val = isSubtype(lowerBound(val), lowerBound(target))
  3178                         ? target : val;
  3179                 } else if (val.isExtendsBound() && target.isExtendsBound()) {
  3180                     val = isSubtype(upperBound(val), upperBound(target))
  3181                         ? val : target;
  3182                 } else if (!isSameType(val, target)) {
  3183                     throw new AdaptFailure();
  3185             } else {
  3186                 val = target;
  3187                 from.append(source);
  3188                 to.append(target);
  3190             mapping.put(source.tsym, val);
  3191             return null;
  3194         @Override
  3195         public Void visitType(Type source, Type target) {
  3196             return null;
  3199         private Set<TypePair> cache = new HashSet<TypePair>();
  3201         private void adaptRecursive(Type source, Type target) {
  3202             TypePair pair = new TypePair(source, target);
  3203             if (cache.add(pair)) {
  3204                 try {
  3205                     visit(source, target);
  3206                 } finally {
  3207                     cache.remove(pair);
  3212         private void adaptRecursive(List<Type> source, List<Type> target) {
  3213             if (source.length() == target.length()) {
  3214                 while (source.nonEmpty()) {
  3215                     adaptRecursive(source.head, target.head);
  3216                     source = source.tail;
  3217                     target = target.tail;
  3223     public static class AdaptFailure extends RuntimeException {
  3224         static final long serialVersionUID = -7490231548272701566L;
  3227     private void adaptSelf(Type t,
  3228                            ListBuffer<Type> from,
  3229                            ListBuffer<Type> to) {
  3230         try {
  3231             //if (t.tsym.type != t)
  3232                 adapt(t.tsym.type, t, from, to);
  3233         } catch (AdaptFailure ex) {
  3234             // Adapt should never fail calculating a mapping from
  3235             // t.tsym.type to t as there can be no merge problem.
  3236             throw new AssertionError(ex);
  3239     // </editor-fold>
  3241     /**
  3242      * Rewrite all type variables (universal quantifiers) in the given
  3243      * type to wildcards (existential quantifiers).  This is used to
  3244      * determine if a cast is allowed.  For example, if high is true
  3245      * and {@code T <: Number}, then {@code List<T>} is rewritten to
  3246      * {@code List<?  extends Number>}.  Since {@code List<Integer> <:
  3247      * List<? extends Number>} a {@code List<T>} can be cast to {@code
  3248      * List<Integer>} with a warning.
  3249      * @param t a type
  3250      * @param high if true return an upper bound; otherwise a lower
  3251      * bound
  3252      * @param rewriteTypeVars only rewrite captured wildcards if false;
  3253      * otherwise rewrite all type variables
  3254      * @return the type rewritten with wildcards (existential
  3255      * quantifiers) only
  3256      */
  3257     private Type rewriteQuantifiers(Type t, boolean high, boolean rewriteTypeVars) {
  3258         return new Rewriter(high, rewriteTypeVars).rewrite(t);
  3261     class Rewriter extends UnaryVisitor<Type> {
  3263         boolean high;
  3264         boolean rewriteTypeVars;
  3266         Rewriter(boolean high, boolean rewriteTypeVars) {
  3267             this.high = high;
  3268             this.rewriteTypeVars = rewriteTypeVars;
  3271         Type rewrite(Type t) {
  3272             ListBuffer<Type> from = new ListBuffer<Type>();
  3273             ListBuffer<Type> to = new ListBuffer<Type>();
  3274             adaptSelf(t, from, to);
  3275             ListBuffer<Type> rewritten = new ListBuffer<Type>();
  3276             List<Type> formals = from.toList();
  3277             boolean changed = false;
  3278             for (Type arg : to.toList()) {
  3279                 Type bound = visit(arg);
  3280                 if (arg != bound) {
  3281                     changed = true;
  3282                     bound = high ? makeExtendsWildcard(bound, (TypeVar)formals.head)
  3283                               : makeSuperWildcard(bound, (TypeVar)formals.head);
  3285                 rewritten.append(bound);
  3286                 formals = formals.tail;
  3288             if (changed)
  3289                 return subst(t.tsym.type, from.toList(), rewritten.toList());
  3290             else
  3291                 return t;
  3294         public Type visitType(Type t, Void s) {
  3295             return high ? upperBound(t) : lowerBound(t);
  3298         @Override
  3299         public Type visitCapturedType(CapturedType t, Void s) {
  3300             return visitWildcardType(t.wildcard, null);
  3303         @Override
  3304         public Type visitTypeVar(TypeVar t, Void s) {
  3305             if (rewriteTypeVars)
  3306                 return high ? t.bound : syms.botType;
  3307             else
  3308                 return t;
  3311         @Override
  3312         public Type visitWildcardType(WildcardType t, Void s) {
  3313             Type bound = high ? t.getExtendsBound() :
  3314                                 t.getSuperBound();
  3315             if (bound == null)
  3316                 bound = high ? syms.objectType : syms.botType;
  3317             return bound;
  3321     /**
  3322      * Create a wildcard with the given upper (extends) bound; create
  3323      * an unbounded wildcard if bound is Object.
  3325      * @param bound the upper bound
  3326      * @param formal the formal type parameter that will be
  3327      * substituted by the wildcard
  3328      */
  3329     private WildcardType makeExtendsWildcard(Type bound, TypeVar formal) {
  3330         if (bound == syms.objectType) {
  3331             return new WildcardType(syms.objectType,
  3332                                     BoundKind.UNBOUND,
  3333                                     syms.boundClass,
  3334                                     formal);
  3335         } else {
  3336             return new WildcardType(bound,
  3337                                     BoundKind.EXTENDS,
  3338                                     syms.boundClass,
  3339                                     formal);
  3343     /**
  3344      * Create a wildcard with the given lower (super) bound; create an
  3345      * unbounded wildcard if bound is bottom (type of {@code null}).
  3347      * @param bound the lower bound
  3348      * @param formal the formal type parameter that will be
  3349      * substituted by the wildcard
  3350      */
  3351     private WildcardType makeSuperWildcard(Type bound, TypeVar formal) {
  3352         if (bound.tag == BOT) {
  3353             return new WildcardType(syms.objectType,
  3354                                     BoundKind.UNBOUND,
  3355                                     syms.boundClass,
  3356                                     formal);
  3357         } else {
  3358             return new WildcardType(bound,
  3359                                     BoundKind.SUPER,
  3360                                     syms.boundClass,
  3361                                     formal);
  3365     /**
  3366      * A wrapper for a type that allows use in sets.
  3367      */
  3368     class SingletonType {
  3369         final Type t;
  3370         SingletonType(Type t) {
  3371             this.t = t;
  3373         public int hashCode() {
  3374             return Types.this.hashCode(t);
  3376         public boolean equals(Object obj) {
  3377             return (obj instanceof SingletonType) &&
  3378                 isSameType(t, ((SingletonType)obj).t);
  3380         public String toString() {
  3381             return t.toString();
  3384     // </editor-fold>
  3386     // <editor-fold defaultstate="collapsed" desc="Visitors">
  3387     /**
  3388      * A default visitor for types.  All visitor methods except
  3389      * visitType are implemented by delegating to visitType.  Concrete
  3390      * subclasses must provide an implementation of visitType and can
  3391      * override other methods as needed.
  3393      * @param <R> the return type of the operation implemented by this
  3394      * visitor; use Void if no return type is needed.
  3395      * @param <S> the type of the second argument (the first being the
  3396      * type itself) of the operation implemented by this visitor; use
  3397      * Void if a second argument is not needed.
  3398      */
  3399     public static abstract class DefaultTypeVisitor<R,S> implements Type.Visitor<R,S> {
  3400         final public R visit(Type t, S s)               { return t.accept(this, s); }
  3401         public R visitClassType(ClassType t, S s)       { return visitType(t, s); }
  3402         public R visitWildcardType(WildcardType t, S s) { return visitType(t, s); }
  3403         public R visitArrayType(ArrayType t, S s)       { return visitType(t, s); }
  3404         public R visitMethodType(MethodType t, S s)     { return visitType(t, s); }
  3405         public R visitPackageType(PackageType t, S s)   { return visitType(t, s); }
  3406         public R visitTypeVar(TypeVar t, S s)           { return visitType(t, s); }
  3407         public R visitCapturedType(CapturedType t, S s) { return visitType(t, s); }
  3408         public R visitForAll(ForAll t, S s)             { return visitType(t, s); }
  3409         public R visitUndetVar(UndetVar t, S s)         { return visitType(t, s); }
  3410         public R visitErrorType(ErrorType t, S s)       { return visitType(t, s); }
  3413     /**
  3414      * A default visitor for symbols.  All visitor methods except
  3415      * visitSymbol are implemented by delegating to visitSymbol.  Concrete
  3416      * subclasses must provide an implementation of visitSymbol and can
  3417      * override other methods as needed.
  3419      * @param <R> the return type of the operation implemented by this
  3420      * visitor; use Void if no return type is needed.
  3421      * @param <S> the type of the second argument (the first being the
  3422      * symbol itself) of the operation implemented by this visitor; use
  3423      * Void if a second argument is not needed.
  3424      */
  3425     public static abstract class DefaultSymbolVisitor<R,S> implements Symbol.Visitor<R,S> {
  3426         final public R visit(Symbol s, S arg)                   { return s.accept(this, arg); }
  3427         public R visitClassSymbol(ClassSymbol s, S arg)         { return visitSymbol(s, arg); }
  3428         public R visitMethodSymbol(MethodSymbol s, S arg)       { return visitSymbol(s, arg); }
  3429         public R visitOperatorSymbol(OperatorSymbol s, S arg)   { return visitSymbol(s, arg); }
  3430         public R visitPackageSymbol(PackageSymbol s, S arg)     { return visitSymbol(s, arg); }
  3431         public R visitTypeSymbol(TypeSymbol s, S arg)           { return visitSymbol(s, arg); }
  3432         public R visitVarSymbol(VarSymbol s, S arg)             { return visitSymbol(s, arg); }
  3435     /**
  3436      * A <em>simple</em> visitor for types.  This visitor is simple as
  3437      * captured wildcards, for-all types (generic methods), and
  3438      * undetermined type variables (part of inference) are hidden.
  3439      * Captured wildcards are hidden by treating them as type
  3440      * variables and the rest are hidden by visiting their qtypes.
  3442      * @param <R> the return type of the operation implemented by this
  3443      * visitor; use Void if no return type is needed.
  3444      * @param <S> the type of the second argument (the first being the
  3445      * type itself) of the operation implemented by this visitor; use
  3446      * Void if a second argument is not needed.
  3447      */
  3448     public static abstract class SimpleVisitor<R,S> extends DefaultTypeVisitor<R,S> {
  3449         @Override
  3450         public R visitCapturedType(CapturedType t, S s) {
  3451             return visitTypeVar(t, s);
  3453         @Override
  3454         public R visitForAll(ForAll t, S s) {
  3455             return visit(t.qtype, s);
  3457         @Override
  3458         public R visitUndetVar(UndetVar t, S s) {
  3459             return visit(t.qtype, s);
  3463     /**
  3464      * A plain relation on types.  That is a 2-ary function on the
  3465      * form Type&nbsp;&times;&nbsp;Type&nbsp;&rarr;&nbsp;Boolean.
  3466      * <!-- In plain text: Type x Type -> Boolean -->
  3467      */
  3468     public static abstract class TypeRelation extends SimpleVisitor<Boolean,Type> {}
  3470     /**
  3471      * A convenience visitor for implementing operations that only
  3472      * require one argument (the type itself), that is, unary
  3473      * operations.
  3475      * @param <R> the return type of the operation implemented by this
  3476      * visitor; use Void if no return type is needed.
  3477      */
  3478     public static abstract class UnaryVisitor<R> extends SimpleVisitor<R,Void> {
  3479         final public R visit(Type t) { return t.accept(this, null); }
  3482     /**
  3483      * A visitor for implementing a mapping from types to types.  The
  3484      * default behavior of this class is to implement the identity
  3485      * mapping (mapping a type to itself).  This can be overridden in
  3486      * subclasses.
  3488      * @param <S> the type of the second argument (the first being the
  3489      * type itself) of this mapping; use Void if a second argument is
  3490      * not needed.
  3491      */
  3492     public static class MapVisitor<S> extends DefaultTypeVisitor<Type,S> {
  3493         final public Type visit(Type t) { return t.accept(this, null); }
  3494         public Type visitType(Type t, S s) { return t; }
  3496     // </editor-fold>

mercurial