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

Thu, 10 Jun 2010 16:08:01 -0700

author
jjg
date
Thu, 10 Jun 2010 16:08:01 -0700
changeset 581
f2fdd52e4e87
parent 567
593a59e40bdb
child 637
c655e0280bdc
permissions
-rw-r--r--

6944312: Potential rebranding issues in openjdk/langtools repository sources
Reviewed-by: darcy

     1 /*
     2  * Copyright (c) 2003, 2009, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    26 package com.sun.tools.javac.code;
    28 import java.lang.ref.SoftReference;
    29 import java.util.*;
    31 import com.sun.tools.javac.util.*;
    32 import com.sun.tools.javac.util.List;
    34 import com.sun.tools.javac.jvm.ClassReader;
    35 import com.sun.tools.javac.comp.Check;
    37 import static com.sun.tools.javac.code.Type.*;
    38 import static com.sun.tools.javac.code.TypeTags.*;
    39 import static com.sun.tools.javac.code.Symbol.*;
    40 import static com.sun.tools.javac.code.Flags.*;
    41 import static com.sun.tools.javac.code.BoundKind.*;
    42 import static com.sun.tools.javac.util.ListBuffer.lb;
    44 /**
    45  * Utility class containing various operations on types.
    46  *
    47  * <p>Unless other names are more illustrative, the following naming
    48  * conventions should be observed in this file:
    49  *
    50  * <dl>
    51  * <dt>t</dt>
    52  * <dd>If the first argument to an operation is a type, it should be named t.</dd>
    53  * <dt>s</dt>
    54  * <dd>Similarly, if the second argument to an operation is a type, it should be named s.</dd>
    55  * <dt>ts</dt>
    56  * <dd>If an operations takes a list of types, the first should be named ts.</dd>
    57  * <dt>ss</dt>
    58  * <dd>A second list of types should be named ss.</dd>
    59  * </dl>
    60  *
    61  * <p><b>This is NOT part of any supported API.
    62  * If you write code that depends on this, you do so at your own risk.
    63  * This code and its internal interfaces are subject to change or
    64  * deletion without notice.</b>
    65  */
    66 public class Types {
    67     protected static final Context.Key<Types> typesKey =
    68         new Context.Key<Types>();
    70     final Symtab syms;
    71     final JavacMessages messages;
    72     final Names names;
    73     final boolean allowBoxing;
    74     final ClassReader reader;
    75     final Source source;
    76     final Check chk;
    77     List<Warner> warnStack = List.nil();
    78     final Name capturedName;
    80     // <editor-fold defaultstate="collapsed" desc="Instantiating">
    81     public static Types instance(Context context) {
    82         Types instance = context.get(typesKey);
    83         if (instance == null)
    84             instance = new Types(context);
    85         return instance;
    86     }
    88     protected Types(Context context) {
    89         context.put(typesKey, this);
    90         syms = Symtab.instance(context);
    91         names = Names.instance(context);
    92         allowBoxing = Source.instance(context).allowBoxing();
    93         reader = ClassReader.instance(context);
    94         source = Source.instance(context);
    95         chk = Check.instance(context);
    96         capturedName = names.fromString("<captured wildcard>");
    97         messages = JavacMessages.instance(context);
    98     }
    99     // </editor-fold>
   101     // <editor-fold defaultstate="collapsed" desc="upperBound">
   102     /**
   103      * The "rvalue conversion".<br>
   104      * The upper bound of most types is the type
   105      * itself.  Wildcards, on the other hand have upper
   106      * and lower bounds.
   107      * @param t a type
   108      * @return the upper bound of the given type
   109      */
   110     public Type upperBound(Type t) {
   111         return upperBound.visit(t);
   112     }
   113     // where
   114         private final MapVisitor<Void> upperBound = new MapVisitor<Void>() {
   116             @Override
   117             public Type visitWildcardType(WildcardType t, Void ignored) {
   118                 if (t.isSuperBound())
   119                     return t.bound == null ? syms.objectType : t.bound.bound;
   120                 else
   121                     return visit(t.type);
   122             }
   124             @Override
   125             public Type visitCapturedType(CapturedType t, Void ignored) {
   126                 return visit(t.bound);
   127             }
   128         };
   129     // </editor-fold>
   131     // <editor-fold defaultstate="collapsed" desc="lowerBound">
   132     /**
   133      * The "lvalue conversion".<br>
   134      * The lower bound of most types is the type
   135      * itself.  Wildcards, on the other hand have upper
   136      * and lower bounds.
   137      * @param t a type
   138      * @return the lower bound of the given type
   139      */
   140     public Type lowerBound(Type t) {
   141         return lowerBound.visit(t);
   142     }
   143     // where
   144         private final MapVisitor<Void> lowerBound = new MapVisitor<Void>() {
   146             @Override
   147             public Type visitWildcardType(WildcardType t, Void ignored) {
   148                 return t.isExtendsBound() ? syms.botType : visit(t.type);
   149             }
   151             @Override
   152             public Type visitCapturedType(CapturedType t, Void ignored) {
   153                 return visit(t.getLowerBound());
   154             }
   155         };
   156     // </editor-fold>
   158     // <editor-fold defaultstate="collapsed" desc="isUnbounded">
   159     /**
   160      * Checks that all the arguments to a class are unbounded
   161      * wildcards or something else that doesn't make any restrictions
   162      * on the arguments. If a class isUnbounded, a raw super- or
   163      * subclass can be cast to it without a warning.
   164      * @param t a type
   165      * @return true iff the given type is unbounded or raw
   166      */
   167     public boolean isUnbounded(Type t) {
   168         return isUnbounded.visit(t);
   169     }
   170     // where
   171         private final UnaryVisitor<Boolean> isUnbounded = new UnaryVisitor<Boolean>() {
   173             public Boolean visitType(Type t, Void ignored) {
   174                 return true;
   175             }
   177             @Override
   178             public Boolean visitClassType(ClassType t, Void ignored) {
   179                 List<Type> parms = t.tsym.type.allparams();
   180                 List<Type> args = t.allparams();
   181                 while (parms.nonEmpty()) {
   182                     WildcardType unb = new WildcardType(syms.objectType,
   183                                                         BoundKind.UNBOUND,
   184                                                         syms.boundClass,
   185                                                         (TypeVar)parms.head);
   186                     if (!containsType(args.head, unb))
   187                         return false;
   188                     parms = parms.tail;
   189                     args = args.tail;
   190                 }
   191                 return true;
   192             }
   193         };
   194     // </editor-fold>
   196     // <editor-fold defaultstate="collapsed" desc="asSub">
   197     /**
   198      * Return the least specific subtype of t that starts with symbol
   199      * sym.  If none exists, return null.  The least specific subtype
   200      * is determined as follows:
   201      *
   202      * <p>If there is exactly one parameterized instance of sym that is a
   203      * subtype of t, that parameterized instance is returned.<br>
   204      * Otherwise, if the plain type or raw type `sym' is a subtype of
   205      * type t, the type `sym' itself is returned.  Otherwise, null is
   206      * returned.
   207      */
   208     public Type asSub(Type t, Symbol sym) {
   209         return asSub.visit(t, sym);
   210     }
   211     // where
   212         private final SimpleVisitor<Type,Symbol> asSub = new SimpleVisitor<Type,Symbol>() {
   214             public Type visitType(Type t, Symbol sym) {
   215                 return null;
   216             }
   218             @Override
   219             public Type visitClassType(ClassType t, Symbol sym) {
   220                 if (t.tsym == sym)
   221                     return t;
   222                 Type base = asSuper(sym.type, t.tsym);
   223                 if (base == null)
   224                     return null;
   225                 ListBuffer<Type> from = new ListBuffer<Type>();
   226                 ListBuffer<Type> to = new ListBuffer<Type>();
   227                 try {
   228                     adapt(base, t, from, to);
   229                 } catch (AdaptFailure ex) {
   230                     return null;
   231                 }
   232                 Type res = subst(sym.type, from.toList(), to.toList());
   233                 if (!isSubtype(res, t))
   234                     return null;
   235                 ListBuffer<Type> openVars = new ListBuffer<Type>();
   236                 for (List<Type> l = sym.type.allparams();
   237                      l.nonEmpty(); l = l.tail)
   238                     if (res.contains(l.head) && !t.contains(l.head))
   239                         openVars.append(l.head);
   240                 if (openVars.nonEmpty()) {
   241                     if (t.isRaw()) {
   242                         // The subtype of a raw type is raw
   243                         res = erasure(res);
   244                     } else {
   245                         // Unbound type arguments default to ?
   246                         List<Type> opens = openVars.toList();
   247                         ListBuffer<Type> qs = new ListBuffer<Type>();
   248                         for (List<Type> iter = opens; iter.nonEmpty(); iter = iter.tail) {
   249                             qs.append(new WildcardType(syms.objectType, BoundKind.UNBOUND, syms.boundClass, (TypeVar) iter.head));
   250                         }
   251                         res = subst(res, opens, qs.toList());
   252                     }
   253                 }
   254                 return res;
   255             }
   257             @Override
   258             public Type visitErrorType(ErrorType t, Symbol sym) {
   259                 return t;
   260             }
   261         };
   262     // </editor-fold>
   264     // <editor-fold defaultstate="collapsed" desc="isConvertible">
   265     /**
   266      * Is t a subtype of or convertiable via boxing/unboxing
   267      * convertions to s?
   268      */
   269     public boolean isConvertible(Type t, Type s, Warner warn) {
   270         boolean tPrimitive = t.isPrimitive();
   271         boolean sPrimitive = s.isPrimitive();
   272         if (tPrimitive == sPrimitive)
   273             return isSubtypeUnchecked(t, s, warn);
   274         if (!allowBoxing) return false;
   275         return tPrimitive
   276             ? isSubtype(boxedClass(t).type, s)
   277             : isSubtype(unboxedType(t), s);
   278     }
   280     /**
   281      * Is t a subtype of or convertiable via boxing/unboxing
   282      * convertions to s?
   283      */
   284     public boolean isConvertible(Type t, Type s) {
   285         return isConvertible(t, s, Warner.noWarnings);
   286     }
   287     // </editor-fold>
   289     // <editor-fold defaultstate="collapsed" desc="isSubtype">
   290     /**
   291      * Is t an unchecked subtype of s?
   292      */
   293     public boolean isSubtypeUnchecked(Type t, Type s) {
   294         return isSubtypeUnchecked(t, s, Warner.noWarnings);
   295     }
   296     /**
   297      * Is t an unchecked subtype of s?
   298      */
   299     public boolean isSubtypeUnchecked(Type t, Type s, Warner warn) {
   300         if (t.tag == ARRAY && s.tag == ARRAY) {
   301             return (((ArrayType)t).elemtype.tag <= lastBaseTag)
   302                 ? isSameType(elemtype(t), elemtype(s))
   303                 : isSubtypeUnchecked(elemtype(t), elemtype(s), warn);
   304         } else if (isSubtype(t, s)) {
   305             return true;
   306         }
   307         else if (t.tag == TYPEVAR) {
   308             return isSubtypeUnchecked(t.getUpperBound(), s, warn);
   309         }
   310         else if (s.tag == UNDETVAR) {
   311             UndetVar uv = (UndetVar)s;
   312             if (uv.inst != null)
   313                 return isSubtypeUnchecked(t, uv.inst, warn);
   314         }
   315         else if (!s.isRaw()) {
   316             Type t2 = asSuper(t, s.tsym);
   317             if (t2 != null && t2.isRaw()) {
   318                 if (isReifiable(s))
   319                     warn.silentUnchecked();
   320                 else
   321                     warn.warnUnchecked();
   322                 return true;
   323             }
   324         }
   325         return false;
   326     }
   328     /**
   329      * Is t a subtype of s?<br>
   330      * (not defined for Method and ForAll types)
   331      */
   332     final public boolean isSubtype(Type t, Type s) {
   333         return isSubtype(t, s, true);
   334     }
   335     final public boolean isSubtypeNoCapture(Type t, Type s) {
   336         return isSubtype(t, s, false);
   337     }
   338     public boolean isSubtype(Type t, Type s, boolean capture) {
   339         if (t == s)
   340             return true;
   342         if (s.tag >= firstPartialTag)
   343             return isSuperType(s, t);
   345         if (s.isCompound()) {
   346             for (Type s2 : interfaces(s).prepend(supertype(s))) {
   347                 if (!isSubtype(t, s2, capture))
   348                     return false;
   349             }
   350             return true;
   351         }
   353         Type lower = lowerBound(s);
   354         if (s != lower)
   355             return isSubtype(capture ? capture(t) : t, lower, false);
   357         return isSubtype.visit(capture ? capture(t) : t, s);
   358     }
   359     // where
   360         private TypeRelation isSubtype = new TypeRelation()
   361         {
   362             public Boolean visitType(Type t, Type s) {
   363                 switch (t.tag) {
   364                 case BYTE: case CHAR:
   365                     return (t.tag == s.tag ||
   366                               t.tag + 2 <= s.tag && s.tag <= DOUBLE);
   367                 case SHORT: case INT: case LONG: case FLOAT: case DOUBLE:
   368                     return t.tag <= s.tag && s.tag <= DOUBLE;
   369                 case BOOLEAN: case VOID:
   370                     return t.tag == s.tag;
   371                 case TYPEVAR:
   372                     return isSubtypeNoCapture(t.getUpperBound(), s);
   373                 case BOT:
   374                     return
   375                         s.tag == BOT || s.tag == CLASS ||
   376                         s.tag == ARRAY || s.tag == TYPEVAR;
   377                 case NONE:
   378                     return false;
   379                 default:
   380                     throw new AssertionError("isSubtype " + t.tag);
   381                 }
   382             }
   384             private Set<TypePair> cache = new HashSet<TypePair>();
   386             private boolean containsTypeRecursive(Type t, Type s) {
   387                 TypePair pair = new TypePair(t, s);
   388                 if (cache.add(pair)) {
   389                     try {
   390                         return containsType(t.getTypeArguments(),
   391                                             s.getTypeArguments());
   392                     } finally {
   393                         cache.remove(pair);
   394                     }
   395                 } else {
   396                     return containsType(t.getTypeArguments(),
   397                                         rewriteSupers(s).getTypeArguments());
   398                 }
   399             }
   401             private Type rewriteSupers(Type t) {
   402                 if (!t.isParameterized())
   403                     return t;
   404                 ListBuffer<Type> from = lb();
   405                 ListBuffer<Type> to = lb();
   406                 adaptSelf(t, from, to);
   407                 if (from.isEmpty())
   408                     return t;
   409                 ListBuffer<Type> rewrite = lb();
   410                 boolean changed = false;
   411                 for (Type orig : to.toList()) {
   412                     Type s = rewriteSupers(orig);
   413                     if (s.isSuperBound() && !s.isExtendsBound()) {
   414                         s = new WildcardType(syms.objectType,
   415                                              BoundKind.UNBOUND,
   416                                              syms.boundClass);
   417                         changed = true;
   418                     } else if (s != orig) {
   419                         s = new WildcardType(upperBound(s),
   420                                              BoundKind.EXTENDS,
   421                                              syms.boundClass);
   422                         changed = true;
   423                     }
   424                     rewrite.append(s);
   425                 }
   426                 if (changed)
   427                     return subst(t.tsym.type, from.toList(), rewrite.toList());
   428                 else
   429                     return t;
   430             }
   432             @Override
   433             public Boolean visitClassType(ClassType t, Type s) {
   434                 Type sup = asSuper(t, s.tsym);
   435                 return sup != null
   436                     && sup.tsym == s.tsym
   437                     // You're not allowed to write
   438                     //     Vector<Object> vec = new Vector<String>();
   439                     // But with wildcards you can write
   440                     //     Vector<? extends Object> vec = new Vector<String>();
   441                     // which means that subtype checking must be done
   442                     // here instead of same-type checking (via containsType).
   443                     && (!s.isParameterized() || containsTypeRecursive(s, sup))
   444                     && isSubtypeNoCapture(sup.getEnclosingType(),
   445                                           s.getEnclosingType());
   446             }
   448             @Override
   449             public Boolean visitArrayType(ArrayType t, Type s) {
   450                 if (s.tag == ARRAY) {
   451                     if (t.elemtype.tag <= lastBaseTag)
   452                         return isSameType(t.elemtype, elemtype(s));
   453                     else
   454                         return isSubtypeNoCapture(t.elemtype, elemtype(s));
   455                 }
   457                 if (s.tag == CLASS) {
   458                     Name sname = s.tsym.getQualifiedName();
   459                     return sname == names.java_lang_Object
   460                         || sname == names.java_lang_Cloneable
   461                         || sname == names.java_io_Serializable;
   462                 }
   464                 return false;
   465             }
   467             @Override
   468             public Boolean visitUndetVar(UndetVar t, Type s) {
   469                 //todo: test against origin needed? or replace with substitution?
   470                 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN)
   471                     return true;
   473                 if (t.inst != null)
   474                     return isSubtypeNoCapture(t.inst, s); // TODO: ", warn"?
   476                 t.hibounds = t.hibounds.prepend(s);
   477                 return true;
   478             }
   480             @Override
   481             public Boolean visitErrorType(ErrorType t, Type s) {
   482                 return true;
   483             }
   484         };
   486     /**
   487      * Is t a subtype of every type in given list `ts'?<br>
   488      * (not defined for Method and ForAll types)<br>
   489      * Allows unchecked conversions.
   490      */
   491     public boolean isSubtypeUnchecked(Type t, List<Type> ts, Warner warn) {
   492         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
   493             if (!isSubtypeUnchecked(t, l.head, warn))
   494                 return false;
   495         return true;
   496     }
   498     /**
   499      * Are corresponding elements of ts subtypes of ss?  If lists are
   500      * of different length, return false.
   501      */
   502     public boolean isSubtypes(List<Type> ts, List<Type> ss) {
   503         while (ts.tail != null && ss.tail != null
   504                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   505                isSubtype(ts.head, ss.head)) {
   506             ts = ts.tail;
   507             ss = ss.tail;
   508         }
   509         return ts.tail == null && ss.tail == null;
   510         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   511     }
   513     /**
   514      * Are corresponding elements of ts subtypes of ss, allowing
   515      * unchecked conversions?  If lists are of different length,
   516      * return false.
   517      **/
   518     public boolean isSubtypesUnchecked(List<Type> ts, List<Type> ss, Warner warn) {
   519         while (ts.tail != null && ss.tail != null
   520                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   521                isSubtypeUnchecked(ts.head, ss.head, warn)) {
   522             ts = ts.tail;
   523             ss = ss.tail;
   524         }
   525         return ts.tail == null && ss.tail == null;
   526         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   527     }
   528     // </editor-fold>
   530     // <editor-fold defaultstate="collapsed" desc="isSuperType">
   531     /**
   532      * Is t a supertype of s?
   533      */
   534     public boolean isSuperType(Type t, Type s) {
   535         switch (t.tag) {
   536         case ERROR:
   537             return true;
   538         case UNDETVAR: {
   539             UndetVar undet = (UndetVar)t;
   540             if (t == s ||
   541                 undet.qtype == s ||
   542                 s.tag == ERROR ||
   543                 s.tag == BOT) return true;
   544             if (undet.inst != null)
   545                 return isSubtype(s, undet.inst);
   546             undet.lobounds = undet.lobounds.prepend(s);
   547             return true;
   548         }
   549         default:
   550             return isSubtype(s, t);
   551         }
   552     }
   553     // </editor-fold>
   555     // <editor-fold defaultstate="collapsed" desc="isSameType">
   556     /**
   557      * Are corresponding elements of the lists the same type?  If
   558      * lists are of different length, return false.
   559      */
   560     public boolean isSameTypes(List<Type> ts, List<Type> ss) {
   561         while (ts.tail != null && ss.tail != null
   562                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   563                isSameType(ts.head, ss.head)) {
   564             ts = ts.tail;
   565             ss = ss.tail;
   566         }
   567         return ts.tail == null && ss.tail == null;
   568         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   569     }
   571     /**
   572      * Is t the same type as s?
   573      */
   574     public boolean isSameType(Type t, Type s) {
   575         return isSameType.visit(t, s);
   576     }
   577     // where
   578         private TypeRelation isSameType = new TypeRelation() {
   580             public Boolean visitType(Type t, Type s) {
   581                 if (t == s)
   582                     return true;
   584                 if (s.tag >= firstPartialTag)
   585                     return visit(s, t);
   587                 switch (t.tag) {
   588                 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
   589                 case DOUBLE: case BOOLEAN: case VOID: case BOT: case NONE:
   590                     return t.tag == s.tag;
   591                 case TYPEVAR: {
   592                     if (s.tag == TYPEVAR) {
   593                         //type-substitution does not preserve type-var types
   594                         //check that type var symbols and bounds are indeed the same
   595                         return t.tsym == s.tsym &&
   596                                 visit(t.getUpperBound(), s.getUpperBound());
   597                     }
   598                     else {
   599                         //special case for s == ? super X, where upper(s) = u
   600                         //check that u == t, where u has been set by Type.withTypeVar
   601                         return s.isSuperBound() &&
   602                                 !s.isExtendsBound() &&
   603                                 visit(t, upperBound(s));
   604                     }
   605                 }
   606                 default:
   607                     throw new AssertionError("isSameType " + t.tag);
   608                 }
   609             }
   611             @Override
   612             public Boolean visitWildcardType(WildcardType t, Type s) {
   613                 if (s.tag >= firstPartialTag)
   614                     return visit(s, t);
   615                 else
   616                     return false;
   617             }
   619             @Override
   620             public Boolean visitClassType(ClassType t, Type s) {
   621                 if (t == s)
   622                     return true;
   624                 if (s.tag >= firstPartialTag)
   625                     return visit(s, t);
   627                 if (s.isSuperBound() && !s.isExtendsBound())
   628                     return visit(t, upperBound(s)) && visit(t, lowerBound(s));
   630                 if (t.isCompound() && s.isCompound()) {
   631                     if (!visit(supertype(t), supertype(s)))
   632                         return false;
   634                     HashSet<SingletonType> set = new HashSet<SingletonType>();
   635                     for (Type x : interfaces(t))
   636                         set.add(new SingletonType(x));
   637                     for (Type x : interfaces(s)) {
   638                         if (!set.remove(new SingletonType(x)))
   639                             return false;
   640                     }
   641                     return (set.size() == 0);
   642                 }
   643                 return t.tsym == s.tsym
   644                     && visit(t.getEnclosingType(), s.getEnclosingType())
   645                     && containsTypeEquivalent(t.getTypeArguments(), s.getTypeArguments());
   646             }
   648             @Override
   649             public Boolean visitArrayType(ArrayType t, Type s) {
   650                 if (t == s)
   651                     return true;
   653                 if (s.tag >= firstPartialTag)
   654                     return visit(s, t);
   656                 return s.tag == ARRAY
   657                     && containsTypeEquivalent(t.elemtype, elemtype(s));
   658             }
   660             @Override
   661             public Boolean visitMethodType(MethodType t, Type s) {
   662                 // isSameType for methods does not take thrown
   663                 // exceptions into account!
   664                 return hasSameArgs(t, s) && visit(t.getReturnType(), s.getReturnType());
   665             }
   667             @Override
   668             public Boolean visitPackageType(PackageType t, Type s) {
   669                 return t == s;
   670             }
   672             @Override
   673             public Boolean visitForAll(ForAll t, Type s) {
   674                 if (s.tag != FORALL)
   675                     return false;
   677                 ForAll forAll = (ForAll)s;
   678                 return hasSameBounds(t, forAll)
   679                     && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
   680             }
   682             @Override
   683             public Boolean visitUndetVar(UndetVar t, Type s) {
   684                 if (s.tag == WILDCARD)
   685                     // FIXME, this might be leftovers from before capture conversion
   686                     return false;
   688                 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN)
   689                     return true;
   691                 if (t.inst != null)
   692                     return visit(t.inst, s);
   694                 t.inst = fromUnknownFun.apply(s);
   695                 for (List<Type> l = t.lobounds; l.nonEmpty(); l = l.tail) {
   696                     if (!isSubtype(l.head, t.inst))
   697                         return false;
   698                 }
   699                 for (List<Type> l = t.hibounds; l.nonEmpty(); l = l.tail) {
   700                     if (!isSubtype(t.inst, l.head))
   701                         return false;
   702                 }
   703                 return true;
   704             }
   706             @Override
   707             public Boolean visitErrorType(ErrorType t, Type s) {
   708                 return true;
   709             }
   710         };
   711     // </editor-fold>
   713     // <editor-fold defaultstate="collapsed" desc="fromUnknownFun">
   714     /**
   715      * A mapping that turns all unknown types in this type to fresh
   716      * unknown variables.
   717      */
   718     public Mapping fromUnknownFun = new Mapping("fromUnknownFun") {
   719             public Type apply(Type t) {
   720                 if (t.tag == UNKNOWN) return new UndetVar(t);
   721                 else return t.map(this);
   722             }
   723         };
   724     // </editor-fold>
   726     // <editor-fold defaultstate="collapsed" desc="Contains Type">
   727     public boolean containedBy(Type t, Type s) {
   728         switch (t.tag) {
   729         case UNDETVAR:
   730             if (s.tag == WILDCARD) {
   731                 UndetVar undetvar = (UndetVar)t;
   732                 WildcardType wt = (WildcardType)s;
   733                 switch(wt.kind) {
   734                     case UNBOUND: //similar to ? extends Object
   735                     case EXTENDS: {
   736                         Type bound = upperBound(s);
   737                         // We should check the new upper bound against any of the
   738                         // undetvar's lower bounds.
   739                         for (Type t2 : undetvar.lobounds) {
   740                             if (!isSubtype(t2, bound))
   741                                 return false;
   742                         }
   743                         undetvar.hibounds = undetvar.hibounds.prepend(bound);
   744                         break;
   745                     }
   746                     case SUPER: {
   747                         Type bound = lowerBound(s);
   748                         // We should check the new lower bound against any of the
   749                         // undetvar's lower bounds.
   750                         for (Type t2 : undetvar.hibounds) {
   751                             if (!isSubtype(bound, t2))
   752                                 return false;
   753                         }
   754                         undetvar.lobounds = undetvar.lobounds.prepend(bound);
   755                         break;
   756                     }
   757                 }
   758                 return true;
   759             } else {
   760                 return isSameType(t, s);
   761             }
   762         case ERROR:
   763             return true;
   764         default:
   765             return containsType(s, t);
   766         }
   767     }
   769     boolean containsType(List<Type> ts, List<Type> ss) {
   770         while (ts.nonEmpty() && ss.nonEmpty()
   771                && containsType(ts.head, ss.head)) {
   772             ts = ts.tail;
   773             ss = ss.tail;
   774         }
   775         return ts.isEmpty() && ss.isEmpty();
   776     }
   778     /**
   779      * Check if t contains s.
   780      *
   781      * <p>T contains S if:
   782      *
   783      * <p>{@code L(T) <: L(S) && U(S) <: U(T)}
   784      *
   785      * <p>This relation is only used by ClassType.isSubtype(), that
   786      * is,
   787      *
   788      * <p>{@code C<S> <: C<T> if T contains S.}
   789      *
   790      * <p>Because of F-bounds, this relation can lead to infinite
   791      * recursion.  Thus we must somehow break that recursion.  Notice
   792      * that containsType() is only called from ClassType.isSubtype().
   793      * Since the arguments have already been checked against their
   794      * bounds, we know:
   795      *
   796      * <p>{@code U(S) <: U(T) if T is "super" bound (U(T) *is* the bound)}
   797      *
   798      * <p>{@code L(T) <: L(S) if T is "extends" bound (L(T) is bottom)}
   799      *
   800      * @param t a type
   801      * @param s a type
   802      */
   803     public boolean containsType(Type t, Type s) {
   804         return containsType.visit(t, s);
   805     }
   806     // where
   807         private TypeRelation containsType = new TypeRelation() {
   809             private Type U(Type t) {
   810                 while (t.tag == WILDCARD) {
   811                     WildcardType w = (WildcardType)t;
   812                     if (w.isSuperBound())
   813                         return w.bound == null ? syms.objectType : w.bound.bound;
   814                     else
   815                         t = w.type;
   816                 }
   817                 return t;
   818             }
   820             private Type L(Type t) {
   821                 while (t.tag == WILDCARD) {
   822                     WildcardType w = (WildcardType)t;
   823                     if (w.isExtendsBound())
   824                         return syms.botType;
   825                     else
   826                         t = w.type;
   827                 }
   828                 return t;
   829             }
   831             public Boolean visitType(Type t, Type s) {
   832                 if (s.tag >= firstPartialTag)
   833                     return containedBy(s, t);
   834                 else
   835                     return isSameType(t, s);
   836             }
   838             void debugContainsType(WildcardType t, Type s) {
   839                 System.err.println();
   840                 System.err.format(" does %s contain %s?%n", t, s);
   841                 System.err.format(" %s U(%s) <: U(%s) %s = %s%n",
   842                                   upperBound(s), s, t, U(t),
   843                                   t.isSuperBound()
   844                                   || isSubtypeNoCapture(upperBound(s), U(t)));
   845                 System.err.format(" %s L(%s) <: L(%s) %s = %s%n",
   846                                   L(t), t, s, lowerBound(s),
   847                                   t.isExtendsBound()
   848                                   || isSubtypeNoCapture(L(t), lowerBound(s)));
   849                 System.err.println();
   850             }
   852             @Override
   853             public Boolean visitWildcardType(WildcardType t, Type s) {
   854                 if (s.tag >= firstPartialTag)
   855                     return containedBy(s, t);
   856                 else {
   857                     // debugContainsType(t, s);
   858                     return isSameWildcard(t, s)
   859                         || isCaptureOf(s, t)
   860                         || ((t.isExtendsBound() || isSubtypeNoCapture(L(t), lowerBound(s))) &&
   861                             (t.isSuperBound() || isSubtypeNoCapture(upperBound(s), U(t))));
   862                 }
   863             }
   865             @Override
   866             public Boolean visitUndetVar(UndetVar t, Type s) {
   867                 if (s.tag != WILDCARD)
   868                     return isSameType(t, s);
   869                 else
   870                     return false;
   871             }
   873             @Override
   874             public Boolean visitErrorType(ErrorType t, Type s) {
   875                 return true;
   876             }
   877         };
   879     public boolean isCaptureOf(Type s, WildcardType t) {
   880         if (s.tag != TYPEVAR || !((TypeVar)s).isCaptured())
   881             return false;
   882         return isSameWildcard(t, ((CapturedType)s).wildcard);
   883     }
   885     public boolean isSameWildcard(WildcardType t, Type s) {
   886         if (s.tag != WILDCARD)
   887             return false;
   888         WildcardType w = (WildcardType)s;
   889         return w.kind == t.kind && w.type == t.type;
   890     }
   892     public boolean containsTypeEquivalent(List<Type> ts, List<Type> ss) {
   893         while (ts.nonEmpty() && ss.nonEmpty()
   894                && containsTypeEquivalent(ts.head, ss.head)) {
   895             ts = ts.tail;
   896             ss = ss.tail;
   897         }
   898         return ts.isEmpty() && ss.isEmpty();
   899     }
   900     // </editor-fold>
   902     // <editor-fold defaultstate="collapsed" desc="isCastable">
   903     public boolean isCastable(Type t, Type s) {
   904         return isCastable(t, s, Warner.noWarnings);
   905     }
   907     /**
   908      * Is t is castable to s?<br>
   909      * s is assumed to be an erased type.<br>
   910      * (not defined for Method and ForAll types).
   911      */
   912     public boolean isCastable(Type t, Type s, Warner warn) {
   913         if (t == s)
   914             return true;
   916         if (t.isPrimitive() != s.isPrimitive())
   917             return allowBoxing && isConvertible(t, s, warn);
   919         if (warn != warnStack.head) {
   920             try {
   921                 warnStack = warnStack.prepend(warn);
   922                 return isCastable.visit(t,s);
   923             } finally {
   924                 warnStack = warnStack.tail;
   925             }
   926         } else {
   927             return isCastable.visit(t,s);
   928         }
   929     }
   930     // where
   931         private TypeRelation isCastable = new TypeRelation() {
   933             public Boolean visitType(Type t, Type s) {
   934                 if (s.tag == ERROR)
   935                     return true;
   937                 switch (t.tag) {
   938                 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
   939                 case DOUBLE:
   940                     return s.tag <= DOUBLE;
   941                 case BOOLEAN:
   942                     return s.tag == BOOLEAN;
   943                 case VOID:
   944                     return false;
   945                 case BOT:
   946                     return isSubtype(t, s);
   947                 default:
   948                     throw new AssertionError();
   949                 }
   950             }
   952             @Override
   953             public Boolean visitWildcardType(WildcardType t, Type s) {
   954                 return isCastable(upperBound(t), s, warnStack.head);
   955             }
   957             @Override
   958             public Boolean visitClassType(ClassType t, Type s) {
   959                 if (s.tag == ERROR || s.tag == BOT)
   960                     return true;
   962                 if (s.tag == TYPEVAR) {
   963                     if (isCastable(s.getUpperBound(), t, Warner.noWarnings)) {
   964                         warnStack.head.warnUnchecked();
   965                         return true;
   966                     } else {
   967                         return false;
   968                     }
   969                 }
   971                 if (t.isCompound()) {
   972                     Warner oldWarner = warnStack.head;
   973                     warnStack.head = Warner.noWarnings;
   974                     if (!visit(supertype(t), s))
   975                         return false;
   976                     for (Type intf : interfaces(t)) {
   977                         if (!visit(intf, s))
   978                             return false;
   979                     }
   980                     if (warnStack.head.unchecked == true)
   981                         oldWarner.warnUnchecked();
   982                     return true;
   983                 }
   985                 if (s.isCompound()) {
   986                     // call recursively to reuse the above code
   987                     return visitClassType((ClassType)s, t);
   988                 }
   990                 if (s.tag == CLASS || s.tag == ARRAY) {
   991                     boolean upcast;
   992                     if ((upcast = isSubtype(erasure(t), erasure(s)))
   993                         || isSubtype(erasure(s), erasure(t))) {
   994                         if (!upcast && s.tag == ARRAY) {
   995                             if (!isReifiable(s))
   996                                 warnStack.head.warnUnchecked();
   997                             return true;
   998                         } else if (s.isRaw()) {
   999                             return true;
  1000                         } else if (t.isRaw()) {
  1001                             if (!isUnbounded(s))
  1002                                 warnStack.head.warnUnchecked();
  1003                             return true;
  1005                         // Assume |a| <: |b|
  1006                         final Type a = upcast ? t : s;
  1007                         final Type b = upcast ? s : t;
  1008                         final boolean HIGH = true;
  1009                         final boolean LOW = false;
  1010                         final boolean DONT_REWRITE_TYPEVARS = false;
  1011                         Type aHigh = rewriteQuantifiers(a, HIGH, DONT_REWRITE_TYPEVARS);
  1012                         Type aLow  = rewriteQuantifiers(a, LOW,  DONT_REWRITE_TYPEVARS);
  1013                         Type bHigh = rewriteQuantifiers(b, HIGH, DONT_REWRITE_TYPEVARS);
  1014                         Type bLow  = rewriteQuantifiers(b, LOW,  DONT_REWRITE_TYPEVARS);
  1015                         Type lowSub = asSub(bLow, aLow.tsym);
  1016                         Type highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
  1017                         if (highSub == null) {
  1018                             final boolean REWRITE_TYPEVARS = true;
  1019                             aHigh = rewriteQuantifiers(a, HIGH, REWRITE_TYPEVARS);
  1020                             aLow  = rewriteQuantifiers(a, LOW,  REWRITE_TYPEVARS);
  1021                             bHigh = rewriteQuantifiers(b, HIGH, REWRITE_TYPEVARS);
  1022                             bLow  = rewriteQuantifiers(b, LOW,  REWRITE_TYPEVARS);
  1023                             lowSub = asSub(bLow, aLow.tsym);
  1024                             highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
  1026                         if (highSub != null) {
  1027                             assert a.tsym == highSub.tsym && a.tsym == lowSub.tsym
  1028                                 : a.tsym + " != " + highSub.tsym + " != " + lowSub.tsym;
  1029                             if (!disjointTypes(aHigh.allparams(), highSub.allparams())
  1030                                 && !disjointTypes(aHigh.allparams(), lowSub.allparams())
  1031                                 && !disjointTypes(aLow.allparams(), highSub.allparams())
  1032                                 && !disjointTypes(aLow.allparams(), lowSub.allparams())) {
  1033                                 if (upcast ? giveWarning(a, b) :
  1034                                     giveWarning(b, a))
  1035                                     warnStack.head.warnUnchecked();
  1036                                 return true;
  1039                         if (isReifiable(s))
  1040                             return isSubtypeUnchecked(a, b);
  1041                         else
  1042                             return isSubtypeUnchecked(a, b, warnStack.head);
  1045                     // Sidecast
  1046                     if (s.tag == CLASS) {
  1047                         if ((s.tsym.flags() & INTERFACE) != 0) {
  1048                             return ((t.tsym.flags() & FINAL) == 0)
  1049                                 ? sideCast(t, s, warnStack.head)
  1050                                 : sideCastFinal(t, s, warnStack.head);
  1051                         } else if ((t.tsym.flags() & INTERFACE) != 0) {
  1052                             return ((s.tsym.flags() & FINAL) == 0)
  1053                                 ? sideCast(t, s, warnStack.head)
  1054                                 : sideCastFinal(t, s, warnStack.head);
  1055                         } else {
  1056                             // unrelated class types
  1057                             return false;
  1061                 return false;
  1064             @Override
  1065             public Boolean visitArrayType(ArrayType t, Type s) {
  1066                 switch (s.tag) {
  1067                 case ERROR:
  1068                 case BOT:
  1069                     return true;
  1070                 case TYPEVAR:
  1071                     if (isCastable(s, t, Warner.noWarnings)) {
  1072                         warnStack.head.warnUnchecked();
  1073                         return true;
  1074                     } else {
  1075                         return false;
  1077                 case CLASS:
  1078                     return isSubtype(t, s);
  1079                 case ARRAY:
  1080                     if (elemtype(t).tag <= lastBaseTag) {
  1081                         return elemtype(t).tag == elemtype(s).tag;
  1082                     } else {
  1083                         return visit(elemtype(t), elemtype(s));
  1085                 default:
  1086                     return false;
  1090             @Override
  1091             public Boolean visitTypeVar(TypeVar t, Type s) {
  1092                 switch (s.tag) {
  1093                 case ERROR:
  1094                 case BOT:
  1095                     return true;
  1096                 case TYPEVAR:
  1097                     if (isSubtype(t, s)) {
  1098                         return true;
  1099                     } else if (isCastable(t.bound, s, Warner.noWarnings)) {
  1100                         warnStack.head.warnUnchecked();
  1101                         return true;
  1102                     } else {
  1103                         return false;
  1105                 default:
  1106                     return isCastable(t.bound, s, warnStack.head);
  1110             @Override
  1111             public Boolean visitErrorType(ErrorType t, Type s) {
  1112                 return true;
  1114         };
  1115     // </editor-fold>
  1117     // <editor-fold defaultstate="collapsed" desc="disjointTypes">
  1118     public boolean disjointTypes(List<Type> ts, List<Type> ss) {
  1119         while (ts.tail != null && ss.tail != null) {
  1120             if (disjointType(ts.head, ss.head)) return true;
  1121             ts = ts.tail;
  1122             ss = ss.tail;
  1124         return false;
  1127     /**
  1128      * Two types or wildcards are considered disjoint if it can be
  1129      * proven that no type can be contained in both. It is
  1130      * conservative in that it is allowed to say that two types are
  1131      * not disjoint, even though they actually are.
  1133      * The type C<X> is castable to C<Y> exactly if X and Y are not
  1134      * disjoint.
  1135      */
  1136     public boolean disjointType(Type t, Type s) {
  1137         return disjointType.visit(t, s);
  1139     // where
  1140         private TypeRelation disjointType = new TypeRelation() {
  1142             private Set<TypePair> cache = new HashSet<TypePair>();
  1144             public Boolean visitType(Type t, Type s) {
  1145                 if (s.tag == WILDCARD)
  1146                     return visit(s, t);
  1147                 else
  1148                     return notSoftSubtypeRecursive(t, s) || notSoftSubtypeRecursive(s, t);
  1151             private boolean isCastableRecursive(Type t, Type s) {
  1152                 TypePair pair = new TypePair(t, s);
  1153                 if (cache.add(pair)) {
  1154                     try {
  1155                         return Types.this.isCastable(t, s);
  1156                     } finally {
  1157                         cache.remove(pair);
  1159                 } else {
  1160                     return true;
  1164             private boolean notSoftSubtypeRecursive(Type t, Type s) {
  1165                 TypePair pair = new TypePair(t, s);
  1166                 if (cache.add(pair)) {
  1167                     try {
  1168                         return Types.this.notSoftSubtype(t, s);
  1169                     } finally {
  1170                         cache.remove(pair);
  1172                 } else {
  1173                     return false;
  1177             @Override
  1178             public Boolean visitWildcardType(WildcardType t, Type s) {
  1179                 if (t.isUnbound())
  1180                     return false;
  1182                 if (s.tag != WILDCARD) {
  1183                     if (t.isExtendsBound())
  1184                         return notSoftSubtypeRecursive(s, t.type);
  1185                     else // isSuperBound()
  1186                         return notSoftSubtypeRecursive(t.type, s);
  1189                 if (s.isUnbound())
  1190                     return false;
  1192                 if (t.isExtendsBound()) {
  1193                     if (s.isExtendsBound())
  1194                         return !isCastableRecursive(t.type, upperBound(s));
  1195                     else if (s.isSuperBound())
  1196                         return notSoftSubtypeRecursive(lowerBound(s), t.type);
  1197                 } else if (t.isSuperBound()) {
  1198                     if (s.isExtendsBound())
  1199                         return notSoftSubtypeRecursive(t.type, upperBound(s));
  1201                 return false;
  1203         };
  1204     // </editor-fold>
  1206     // <editor-fold defaultstate="collapsed" desc="lowerBoundArgtypes">
  1207     /**
  1208      * Returns the lower bounds of the formals of a method.
  1209      */
  1210     public List<Type> lowerBoundArgtypes(Type t) {
  1211         return map(t.getParameterTypes(), lowerBoundMapping);
  1213     private final Mapping lowerBoundMapping = new Mapping("lowerBound") {
  1214             public Type apply(Type t) {
  1215                 return lowerBound(t);
  1217         };
  1218     // </editor-fold>
  1220     // <editor-fold defaultstate="collapsed" desc="notSoftSubtype">
  1221     /**
  1222      * This relation answers the question: is impossible that
  1223      * something of type `t' can be a subtype of `s'? This is
  1224      * different from the question "is `t' not a subtype of `s'?"
  1225      * when type variables are involved: Integer is not a subtype of T
  1226      * where <T extends Number> but it is not true that Integer cannot
  1227      * possibly be a subtype of T.
  1228      */
  1229     public boolean notSoftSubtype(Type t, Type s) {
  1230         if (t == s) return false;
  1231         if (t.tag == TYPEVAR) {
  1232             TypeVar tv = (TypeVar) t;
  1233             if (s.tag == TYPEVAR)
  1234                 s = s.getUpperBound();
  1235             return !isCastable(tv.bound,
  1236                                s,
  1237                                Warner.noWarnings);
  1239         if (s.tag != WILDCARD)
  1240             s = upperBound(s);
  1241         if (s.tag == TYPEVAR)
  1242             s = s.getUpperBound();
  1244         return !isSubtype(t, s);
  1246     // </editor-fold>
  1248     // <editor-fold defaultstate="collapsed" desc="isReifiable">
  1249     public boolean isReifiable(Type t) {
  1250         return isReifiable.visit(t);
  1252     // where
  1253         private UnaryVisitor<Boolean> isReifiable = new UnaryVisitor<Boolean>() {
  1255             public Boolean visitType(Type t, Void ignored) {
  1256                 return true;
  1259             @Override
  1260             public Boolean visitClassType(ClassType t, Void ignored) {
  1261                 if (t.isCompound())
  1262                     return false;
  1263                 else {
  1264                     if (!t.isParameterized())
  1265                         return true;
  1267                     for (Type param : t.allparams()) {
  1268                         if (!param.isUnbound())
  1269                             return false;
  1271                     return true;
  1275             @Override
  1276             public Boolean visitArrayType(ArrayType t, Void ignored) {
  1277                 return visit(t.elemtype);
  1280             @Override
  1281             public Boolean visitTypeVar(TypeVar t, Void ignored) {
  1282                 return false;
  1284         };
  1285     // </editor-fold>
  1287     // <editor-fold defaultstate="collapsed" desc="Array Utils">
  1288     public boolean isArray(Type t) {
  1289         while (t.tag == WILDCARD)
  1290             t = upperBound(t);
  1291         return t.tag == ARRAY;
  1294     /**
  1295      * The element type of an array.
  1296      */
  1297     public Type elemtype(Type t) {
  1298         switch (t.tag) {
  1299         case WILDCARD:
  1300             return elemtype(upperBound(t));
  1301         case ARRAY:
  1302             return ((ArrayType)t).elemtype;
  1303         case FORALL:
  1304             return elemtype(((ForAll)t).qtype);
  1305         case ERROR:
  1306             return t;
  1307         default:
  1308             return null;
  1312     /**
  1313      * Mapping to take element type of an arraytype
  1314      */
  1315     private Mapping elemTypeFun = new Mapping ("elemTypeFun") {
  1316         public Type apply(Type t) { return elemtype(t); }
  1317     };
  1319     /**
  1320      * The number of dimensions of an array type.
  1321      */
  1322     public int dimensions(Type t) {
  1323         int result = 0;
  1324         while (t.tag == ARRAY) {
  1325             result++;
  1326             t = elemtype(t);
  1328         return result;
  1330     // </editor-fold>
  1332     // <editor-fold defaultstate="collapsed" desc="asSuper">
  1333     /**
  1334      * Return the (most specific) base type of t that starts with the
  1335      * given symbol.  If none exists, return null.
  1337      * @param t a type
  1338      * @param sym a symbol
  1339      */
  1340     public Type asSuper(Type t, Symbol sym) {
  1341         return asSuper.visit(t, sym);
  1343     // where
  1344         private SimpleVisitor<Type,Symbol> asSuper = new SimpleVisitor<Type,Symbol>() {
  1346             public Type visitType(Type t, Symbol sym) {
  1347                 return null;
  1350             @Override
  1351             public Type visitClassType(ClassType t, Symbol sym) {
  1352                 if (t.tsym == sym)
  1353                     return t;
  1355                 Type st = supertype(t);
  1356                 if (st.tag == CLASS || st.tag == TYPEVAR || st.tag == ERROR) {
  1357                     Type x = asSuper(st, sym);
  1358                     if (x != null)
  1359                         return x;
  1361                 if ((sym.flags() & INTERFACE) != 0) {
  1362                     for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
  1363                         Type x = asSuper(l.head, sym);
  1364                         if (x != null)
  1365                             return x;
  1368                 return null;
  1371             @Override
  1372             public Type visitArrayType(ArrayType t, Symbol sym) {
  1373                 return isSubtype(t, sym.type) ? sym.type : null;
  1376             @Override
  1377             public Type visitTypeVar(TypeVar t, Symbol sym) {
  1378                 if (t.tsym == sym)
  1379                     return t;
  1380                 else
  1381                     return asSuper(t.bound, sym);
  1384             @Override
  1385             public Type visitErrorType(ErrorType t, Symbol sym) {
  1386                 return t;
  1388         };
  1390     /**
  1391      * Return the base type of t or any of its outer types that starts
  1392      * with the given symbol.  If none exists, return null.
  1394      * @param t a type
  1395      * @param sym a symbol
  1396      */
  1397     public Type asOuterSuper(Type t, Symbol sym) {
  1398         switch (t.tag) {
  1399         case CLASS:
  1400             do {
  1401                 Type s = asSuper(t, sym);
  1402                 if (s != null) return s;
  1403                 t = t.getEnclosingType();
  1404             } while (t.tag == CLASS);
  1405             return null;
  1406         case ARRAY:
  1407             return isSubtype(t, sym.type) ? sym.type : null;
  1408         case TYPEVAR:
  1409             return asSuper(t, sym);
  1410         case ERROR:
  1411             return t;
  1412         default:
  1413             return null;
  1417     /**
  1418      * Return the base type of t or any of its enclosing types that
  1419      * starts with the given symbol.  If none exists, return null.
  1421      * @param t a type
  1422      * @param sym a symbol
  1423      */
  1424     public Type asEnclosingSuper(Type t, Symbol sym) {
  1425         switch (t.tag) {
  1426         case CLASS:
  1427             do {
  1428                 Type s = asSuper(t, sym);
  1429                 if (s != null) return s;
  1430                 Type outer = t.getEnclosingType();
  1431                 t = (outer.tag == CLASS) ? outer :
  1432                     (t.tsym.owner.enclClass() != null) ? t.tsym.owner.enclClass().type :
  1433                     Type.noType;
  1434             } while (t.tag == CLASS);
  1435             return null;
  1436         case ARRAY:
  1437             return isSubtype(t, sym.type) ? sym.type : null;
  1438         case TYPEVAR:
  1439             return asSuper(t, sym);
  1440         case ERROR:
  1441             return t;
  1442         default:
  1443             return null;
  1446     // </editor-fold>
  1448     // <editor-fold defaultstate="collapsed" desc="memberType">
  1449     /**
  1450      * The type of given symbol, seen as a member of t.
  1452      * @param t a type
  1453      * @param sym a symbol
  1454      */
  1455     public Type memberType(Type t, Symbol sym) {
  1456         return (sym.flags() & STATIC) != 0
  1457             ? sym.type
  1458             : memberType.visit(t, sym);
  1460     // where
  1461         private SimpleVisitor<Type,Symbol> memberType = new SimpleVisitor<Type,Symbol>() {
  1463             public Type visitType(Type t, Symbol sym) {
  1464                 return sym.type;
  1467             @Override
  1468             public Type visitWildcardType(WildcardType t, Symbol sym) {
  1469                 return memberType(upperBound(t), sym);
  1472             @Override
  1473             public Type visitClassType(ClassType t, Symbol sym) {
  1474                 Symbol owner = sym.owner;
  1475                 long flags = sym.flags();
  1476                 if (((flags & STATIC) == 0) && owner.type.isParameterized()) {
  1477                     Type base = asOuterSuper(t, owner);
  1478                     //if t is an intersection type T = CT & I1 & I2 ... & In
  1479                     //its supertypes CT, I1, ... In might contain wildcards
  1480                     //so we need to go through capture conversion
  1481                     base = t.isCompound() ? capture(base) : base;
  1482                     if (base != null) {
  1483                         List<Type> ownerParams = owner.type.allparams();
  1484                         List<Type> baseParams = base.allparams();
  1485                         if (ownerParams.nonEmpty()) {
  1486                             if (baseParams.isEmpty()) {
  1487                                 // then base is a raw type
  1488                                 return erasure(sym.type);
  1489                             } else {
  1490                                 return subst(sym.type, ownerParams, baseParams);
  1495                 return sym.type;
  1498             @Override
  1499             public Type visitTypeVar(TypeVar t, Symbol sym) {
  1500                 return memberType(t.bound, sym);
  1503             @Override
  1504             public Type visitErrorType(ErrorType t, Symbol sym) {
  1505                 return t;
  1507         };
  1508     // </editor-fold>
  1510     // <editor-fold defaultstate="collapsed" desc="isAssignable">
  1511     public boolean isAssignable(Type t, Type s) {
  1512         return isAssignable(t, s, Warner.noWarnings);
  1515     /**
  1516      * Is t assignable to s?<br>
  1517      * Equivalent to subtype except for constant values and raw
  1518      * types.<br>
  1519      * (not defined for Method and ForAll types)
  1520      */
  1521     public boolean isAssignable(Type t, Type s, Warner warn) {
  1522         if (t.tag == ERROR)
  1523             return true;
  1524         if (t.tag <= INT && t.constValue() != null) {
  1525             int value = ((Number)t.constValue()).intValue();
  1526             switch (s.tag) {
  1527             case BYTE:
  1528                 if (Byte.MIN_VALUE <= value && value <= Byte.MAX_VALUE)
  1529                     return true;
  1530                 break;
  1531             case CHAR:
  1532                 if (Character.MIN_VALUE <= value && value <= Character.MAX_VALUE)
  1533                     return true;
  1534                 break;
  1535             case SHORT:
  1536                 if (Short.MIN_VALUE <= value && value <= Short.MAX_VALUE)
  1537                     return true;
  1538                 break;
  1539             case INT:
  1540                 return true;
  1541             case CLASS:
  1542                 switch (unboxedType(s).tag) {
  1543                 case BYTE:
  1544                 case CHAR:
  1545                 case SHORT:
  1546                     return isAssignable(t, unboxedType(s), warn);
  1548                 break;
  1551         return isConvertible(t, s, warn);
  1553     // </editor-fold>
  1555     // <editor-fold defaultstate="collapsed" desc="erasure">
  1556     /**
  1557      * The erasure of t {@code |t|} -- the type that results when all
  1558      * type parameters in t are deleted.
  1559      */
  1560     public Type erasure(Type t) {
  1561         return erasure(t, false);
  1563     //where
  1564     private Type erasure(Type t, boolean recurse) {
  1565         if (t.tag <= lastBaseTag)
  1566             return t; /* fast special case */
  1567         else
  1568             return erasure.visit(t, recurse);
  1570     // where
  1571         private SimpleVisitor<Type, Boolean> erasure = new SimpleVisitor<Type, Boolean>() {
  1572             public Type visitType(Type t, Boolean recurse) {
  1573                 if (t.tag <= lastBaseTag)
  1574                     return t; /*fast special case*/
  1575                 else
  1576                     return t.map(recurse ? erasureRecFun : erasureFun);
  1579             @Override
  1580             public Type visitWildcardType(WildcardType t, Boolean recurse) {
  1581                 return erasure(upperBound(t), recurse);
  1584             @Override
  1585             public Type visitClassType(ClassType t, Boolean recurse) {
  1586                 Type erased = t.tsym.erasure(Types.this);
  1587                 if (recurse) {
  1588                     erased = new ErasedClassType(erased.getEnclosingType(),erased.tsym);
  1590                 return erased;
  1593             @Override
  1594             public Type visitTypeVar(TypeVar t, Boolean recurse) {
  1595                 return erasure(t.bound, recurse);
  1598             @Override
  1599             public Type visitErrorType(ErrorType t, Boolean recurse) {
  1600                 return t;
  1602         };
  1604     private Mapping erasureFun = new Mapping ("erasure") {
  1605             public Type apply(Type t) { return erasure(t); }
  1606         };
  1608     private Mapping erasureRecFun = new Mapping ("erasureRecursive") {
  1609         public Type apply(Type t) { return erasureRecursive(t); }
  1610     };
  1612     public List<Type> erasure(List<Type> ts) {
  1613         return Type.map(ts, erasureFun);
  1616     public Type erasureRecursive(Type t) {
  1617         return erasure(t, true);
  1620     public List<Type> erasureRecursive(List<Type> ts) {
  1621         return Type.map(ts, erasureRecFun);
  1623     // </editor-fold>
  1625     // <editor-fold defaultstate="collapsed" desc="makeCompoundType">
  1626     /**
  1627      * Make a compound type from non-empty list of types
  1629      * @param bounds            the types from which the compound type is formed
  1630      * @param supertype         is objectType if all bounds are interfaces,
  1631      *                          null otherwise.
  1632      */
  1633     public Type makeCompoundType(List<Type> bounds,
  1634                                  Type supertype) {
  1635         ClassSymbol bc =
  1636             new ClassSymbol(ABSTRACT|PUBLIC|SYNTHETIC|COMPOUND|ACYCLIC,
  1637                             Type.moreInfo
  1638                                 ? names.fromString(bounds.toString())
  1639                                 : names.empty,
  1640                             syms.noSymbol);
  1641         if (bounds.head.tag == TYPEVAR)
  1642             // error condition, recover
  1643                 bc.erasure_field = syms.objectType;
  1644             else
  1645                 bc.erasure_field = erasure(bounds.head);
  1646             bc.members_field = new Scope(bc);
  1647         ClassType bt = (ClassType)bc.type;
  1648         bt.allparams_field = List.nil();
  1649         if (supertype != null) {
  1650             bt.supertype_field = supertype;
  1651             bt.interfaces_field = bounds;
  1652         } else {
  1653             bt.supertype_field = bounds.head;
  1654             bt.interfaces_field = bounds.tail;
  1656         assert bt.supertype_field.tsym.completer != null
  1657             || !bt.supertype_field.isInterface()
  1658             : bt.supertype_field;
  1659         return bt;
  1662     /**
  1663      * Same as {@link #makeCompoundType(List,Type)}, except that the
  1664      * second parameter is computed directly. Note that this might
  1665      * cause a symbol completion.  Hence, this version of
  1666      * makeCompoundType may not be called during a classfile read.
  1667      */
  1668     public Type makeCompoundType(List<Type> bounds) {
  1669         Type supertype = (bounds.head.tsym.flags() & INTERFACE) != 0 ?
  1670             supertype(bounds.head) : null;
  1671         return makeCompoundType(bounds, supertype);
  1674     /**
  1675      * A convenience wrapper for {@link #makeCompoundType(List)}; the
  1676      * arguments are converted to a list and passed to the other
  1677      * method.  Note that this might cause a symbol completion.
  1678      * Hence, this version of makeCompoundType may not be called
  1679      * during a classfile read.
  1680      */
  1681     public Type makeCompoundType(Type bound1, Type bound2) {
  1682         return makeCompoundType(List.of(bound1, bound2));
  1684     // </editor-fold>
  1686     // <editor-fold defaultstate="collapsed" desc="supertype">
  1687     public Type supertype(Type t) {
  1688         return supertype.visit(t);
  1690     // where
  1691         private UnaryVisitor<Type> supertype = new UnaryVisitor<Type>() {
  1693             public Type visitType(Type t, Void ignored) {
  1694                 // A note on wildcards: there is no good way to
  1695                 // determine a supertype for a super bounded wildcard.
  1696                 return null;
  1699             @Override
  1700             public Type visitClassType(ClassType t, Void ignored) {
  1701                 if (t.supertype_field == null) {
  1702                     Type supertype = ((ClassSymbol)t.tsym).getSuperclass();
  1703                     // An interface has no superclass; its supertype is Object.
  1704                     if (t.isInterface())
  1705                         supertype = ((ClassType)t.tsym.type).supertype_field;
  1706                     if (t.supertype_field == null) {
  1707                         List<Type> actuals = classBound(t).allparams();
  1708                         List<Type> formals = t.tsym.type.allparams();
  1709                         if (t.hasErasedSupertypes()) {
  1710                             t.supertype_field = erasureRecursive(supertype);
  1711                         } else if (formals.nonEmpty()) {
  1712                             t.supertype_field = subst(supertype, formals, actuals);
  1714                         else {
  1715                             t.supertype_field = supertype;
  1719                 return t.supertype_field;
  1722             /**
  1723              * The supertype is always a class type. If the type
  1724              * variable's bounds start with a class type, this is also
  1725              * the supertype.  Otherwise, the supertype is
  1726              * java.lang.Object.
  1727              */
  1728             @Override
  1729             public Type visitTypeVar(TypeVar t, Void ignored) {
  1730                 if (t.bound.tag == TYPEVAR ||
  1731                     (!t.bound.isCompound() && !t.bound.isInterface())) {
  1732                     return t.bound;
  1733                 } else {
  1734                     return supertype(t.bound);
  1738             @Override
  1739             public Type visitArrayType(ArrayType t, Void ignored) {
  1740                 if (t.elemtype.isPrimitive() || isSameType(t.elemtype, syms.objectType))
  1741                     return arraySuperType();
  1742                 else
  1743                     return new ArrayType(supertype(t.elemtype), t.tsym);
  1746             @Override
  1747             public Type visitErrorType(ErrorType t, Void ignored) {
  1748                 return t;
  1750         };
  1751     // </editor-fold>
  1753     // <editor-fold defaultstate="collapsed" desc="interfaces">
  1754     /**
  1755      * Return the interfaces implemented by this class.
  1756      */
  1757     public List<Type> interfaces(Type t) {
  1758         return interfaces.visit(t);
  1760     // where
  1761         private UnaryVisitor<List<Type>> interfaces = new UnaryVisitor<List<Type>>() {
  1763             public List<Type> visitType(Type t, Void ignored) {
  1764                 return List.nil();
  1767             @Override
  1768             public List<Type> visitClassType(ClassType t, Void ignored) {
  1769                 if (t.interfaces_field == null) {
  1770                     List<Type> interfaces = ((ClassSymbol)t.tsym).getInterfaces();
  1771                     if (t.interfaces_field == null) {
  1772                         // If t.interfaces_field is null, then t must
  1773                         // be a parameterized type (not to be confused
  1774                         // with a generic type declaration).
  1775                         // Terminology:
  1776                         //    Parameterized type: List<String>
  1777                         //    Generic type declaration: class List<E> { ... }
  1778                         // So t corresponds to List<String> and
  1779                         // t.tsym.type corresponds to List<E>.
  1780                         // The reason t must be parameterized type is
  1781                         // that completion will happen as a side
  1782                         // effect of calling
  1783                         // ClassSymbol.getInterfaces.  Since
  1784                         // t.interfaces_field is null after
  1785                         // completion, we can assume that t is not the
  1786                         // type of a class/interface declaration.
  1787                         assert t != t.tsym.type : t.toString();
  1788                         List<Type> actuals = t.allparams();
  1789                         List<Type> formals = t.tsym.type.allparams();
  1790                         if (t.hasErasedSupertypes()) {
  1791                             t.interfaces_field = erasureRecursive(interfaces);
  1792                         } else if (formals.nonEmpty()) {
  1793                             t.interfaces_field =
  1794                                 upperBounds(subst(interfaces, formals, actuals));
  1796                         else {
  1797                             t.interfaces_field = interfaces;
  1801                 return t.interfaces_field;
  1804             @Override
  1805             public List<Type> visitTypeVar(TypeVar t, Void ignored) {
  1806                 if (t.bound.isCompound())
  1807                     return interfaces(t.bound);
  1809                 if (t.bound.isInterface())
  1810                     return List.of(t.bound);
  1812                 return List.nil();
  1814         };
  1815     // </editor-fold>
  1817     // <editor-fold defaultstate="collapsed" desc="isDerivedRaw">
  1818     Map<Type,Boolean> isDerivedRawCache = new HashMap<Type,Boolean>();
  1820     public boolean isDerivedRaw(Type t) {
  1821         Boolean result = isDerivedRawCache.get(t);
  1822         if (result == null) {
  1823             result = isDerivedRawInternal(t);
  1824             isDerivedRawCache.put(t, result);
  1826         return result;
  1829     public boolean isDerivedRawInternal(Type t) {
  1830         if (t.isErroneous())
  1831             return false;
  1832         return
  1833             t.isRaw() ||
  1834             supertype(t) != null && isDerivedRaw(supertype(t)) ||
  1835             isDerivedRaw(interfaces(t));
  1838     public boolean isDerivedRaw(List<Type> ts) {
  1839         List<Type> l = ts;
  1840         while (l.nonEmpty() && !isDerivedRaw(l.head)) l = l.tail;
  1841         return l.nonEmpty();
  1843     // </editor-fold>
  1845     // <editor-fold defaultstate="collapsed" desc="setBounds">
  1846     /**
  1847      * Set the bounds field of the given type variable to reflect a
  1848      * (possibly multiple) list of bounds.
  1849      * @param t                 a type variable
  1850      * @param bounds            the bounds, must be nonempty
  1851      * @param supertype         is objectType if all bounds are interfaces,
  1852      *                          null otherwise.
  1853      */
  1854     public void setBounds(TypeVar t, List<Type> bounds, Type supertype) {
  1855         if (bounds.tail.isEmpty())
  1856             t.bound = bounds.head;
  1857         else
  1858             t.bound = makeCompoundType(bounds, supertype);
  1859         t.rank_field = -1;
  1862     /**
  1863      * Same as {@link #setBounds(Type.TypeVar,List,Type)}, except that
  1864      * third parameter is computed directly, as follows: if all
  1865      * all bounds are interface types, the computed supertype is Object,
  1866      * otherwise the supertype is simply left null (in this case, the supertype
  1867      * is assumed to be the head of the bound list passed as second argument).
  1868      * Note that this check might cause a symbol completion. Hence, this version of
  1869      * setBounds may not be called during a classfile read.
  1870      */
  1871     public void setBounds(TypeVar t, List<Type> bounds) {
  1872         Type supertype = (bounds.head.tsym.flags() & INTERFACE) != 0 ?
  1873             syms.objectType : null;
  1874         setBounds(t, bounds, supertype);
  1875         t.rank_field = -1;
  1877     // </editor-fold>
  1879     // <editor-fold defaultstate="collapsed" desc="getBounds">
  1880     /**
  1881      * Return list of bounds of the given type variable.
  1882      */
  1883     public List<Type> getBounds(TypeVar t) {
  1884         if (t.bound.isErroneous() || !t.bound.isCompound())
  1885             return List.of(t.bound);
  1886         else if ((erasure(t).tsym.flags() & INTERFACE) == 0)
  1887             return interfaces(t).prepend(supertype(t));
  1888         else
  1889             // No superclass was given in bounds.
  1890             // In this case, supertype is Object, erasure is first interface.
  1891             return interfaces(t);
  1893     // </editor-fold>
  1895     // <editor-fold defaultstate="collapsed" desc="classBound">
  1896     /**
  1897      * If the given type is a (possibly selected) type variable,
  1898      * return the bounding class of this type, otherwise return the
  1899      * type itself.
  1900      */
  1901     public Type classBound(Type t) {
  1902         return classBound.visit(t);
  1904     // where
  1905         private UnaryVisitor<Type> classBound = new UnaryVisitor<Type>() {
  1907             public Type visitType(Type t, Void ignored) {
  1908                 return t;
  1911             @Override
  1912             public Type visitClassType(ClassType t, Void ignored) {
  1913                 Type outer1 = classBound(t.getEnclosingType());
  1914                 if (outer1 != t.getEnclosingType())
  1915                     return new ClassType(outer1, t.getTypeArguments(), t.tsym);
  1916                 else
  1917                     return t;
  1920             @Override
  1921             public Type visitTypeVar(TypeVar t, Void ignored) {
  1922                 return classBound(supertype(t));
  1925             @Override
  1926             public Type visitErrorType(ErrorType t, Void ignored) {
  1927                 return t;
  1929         };
  1930     // </editor-fold>
  1932     // <editor-fold defaultstate="collapsed" desc="sub signature / override equivalence">
  1933     /**
  1934      * Returns true iff the first signature is a <em>sub
  1935      * signature</em> of the other.  This is <b>not</b> an equivalence
  1936      * relation.
  1938      * @see "The Java Language Specification, Third Ed. (8.4.2)."
  1939      * @see #overrideEquivalent(Type t, Type s)
  1940      * @param t first signature (possibly raw).
  1941      * @param s second signature (could be subjected to erasure).
  1942      * @return true if t is a sub signature of s.
  1943      */
  1944     public boolean isSubSignature(Type t, Type s) {
  1945         return hasSameArgs(t, s) || hasSameArgs(t, erasure(s));
  1948     /**
  1949      * Returns true iff these signatures are related by <em>override
  1950      * equivalence</em>.  This is the natural extension of
  1951      * isSubSignature to an equivalence relation.
  1953      * @see "The Java Language Specification, Third Ed. (8.4.2)."
  1954      * @see #isSubSignature(Type t, Type s)
  1955      * @param t a signature (possible raw, could be subjected to
  1956      * erasure).
  1957      * @param s a signature (possible raw, could be subjected to
  1958      * erasure).
  1959      * @return true if either argument is a sub signature of the other.
  1960      */
  1961     public boolean overrideEquivalent(Type t, Type s) {
  1962         return hasSameArgs(t, s) ||
  1963             hasSameArgs(t, erasure(s)) || hasSameArgs(erasure(t), s);
  1966     private WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, MethodSymbol>>> implCache_check =
  1967             new WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, MethodSymbol>>>();
  1969     private WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, MethodSymbol>>> implCache_nocheck =
  1970             new WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, MethodSymbol>>>();
  1972     public MethodSymbol implementation(MethodSymbol ms, TypeSymbol origin, Types types, boolean checkResult) {
  1973         Map<MethodSymbol, SoftReference<Map<TypeSymbol, MethodSymbol>>> implCache = checkResult ?
  1974             implCache_check : implCache_nocheck;
  1975         SoftReference<Map<TypeSymbol, MethodSymbol>> ref_cache = implCache.get(ms);
  1976         Map<TypeSymbol, MethodSymbol> cache = ref_cache != null ? ref_cache.get() : null;
  1977         if (cache == null) {
  1978             cache = new HashMap<TypeSymbol, MethodSymbol>();
  1979             implCache.put(ms, new SoftReference<Map<TypeSymbol, MethodSymbol>>(cache));
  1981         MethodSymbol impl = cache.get(origin);
  1982         if (impl == null) {
  1983             for (Type t = origin.type; t.tag == CLASS || t.tag == TYPEVAR; t = types.supertype(t)) {
  1984                 while (t.tag == TYPEVAR)
  1985                     t = t.getUpperBound();
  1986                 TypeSymbol c = t.tsym;
  1987                 for (Scope.Entry e = c.members().lookup(ms.name);
  1988                      e.scope != null;
  1989                      e = e.next()) {
  1990                     if (e.sym.kind == Kinds.MTH) {
  1991                         MethodSymbol m = (MethodSymbol) e.sym;
  1992                         if (m.overrides(ms, origin, types, checkResult) &&
  1993                             (m.flags() & SYNTHETIC) == 0) {
  1994                             impl = m;
  1995                             cache.put(origin, m);
  1996                             return impl;
  2002         return impl;
  2005     /**
  2006      * Does t have the same arguments as s?  It is assumed that both
  2007      * types are (possibly polymorphic) method types.  Monomorphic
  2008      * method types "have the same arguments", if their argument lists
  2009      * are equal.  Polymorphic method types "have the same arguments",
  2010      * if they have the same arguments after renaming all type
  2011      * variables of one to corresponding type variables in the other,
  2012      * where correspondence is by position in the type parameter list.
  2013      */
  2014     public boolean hasSameArgs(Type t, Type s) {
  2015         return hasSameArgs.visit(t, s);
  2017     // where
  2018         private TypeRelation hasSameArgs = new TypeRelation() {
  2020             public Boolean visitType(Type t, Type s) {
  2021                 throw new AssertionError();
  2024             @Override
  2025             public Boolean visitMethodType(MethodType t, Type s) {
  2026                 return s.tag == METHOD
  2027                     && containsTypeEquivalent(t.argtypes, s.getParameterTypes());
  2030             @Override
  2031             public Boolean visitForAll(ForAll t, Type s) {
  2032                 if (s.tag != FORALL)
  2033                     return false;
  2035                 ForAll forAll = (ForAll)s;
  2036                 return hasSameBounds(t, forAll)
  2037                     && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
  2040             @Override
  2041             public Boolean visitErrorType(ErrorType t, Type s) {
  2042                 return false;
  2044         };
  2045     // </editor-fold>
  2047     // <editor-fold defaultstate="collapsed" desc="subst">
  2048     public List<Type> subst(List<Type> ts,
  2049                             List<Type> from,
  2050                             List<Type> to) {
  2051         return new Subst(from, to).subst(ts);
  2054     /**
  2055      * Substitute all occurrences of a type in `from' with the
  2056      * corresponding type in `to' in 't'. Match lists `from' and `to'
  2057      * from the right: If lists have different length, discard leading
  2058      * elements of the longer list.
  2059      */
  2060     public Type subst(Type t, List<Type> from, List<Type> to) {
  2061         return new Subst(from, to).subst(t);
  2064     private class Subst extends UnaryVisitor<Type> {
  2065         List<Type> from;
  2066         List<Type> to;
  2068         public Subst(List<Type> from, List<Type> to) {
  2069             int fromLength = from.length();
  2070             int toLength = to.length();
  2071             while (fromLength > toLength) {
  2072                 fromLength--;
  2073                 from = from.tail;
  2075             while (fromLength < toLength) {
  2076                 toLength--;
  2077                 to = to.tail;
  2079             this.from = from;
  2080             this.to = to;
  2083         Type subst(Type t) {
  2084             if (from.tail == null)
  2085                 return t;
  2086             else
  2087                 return visit(t);
  2090         List<Type> subst(List<Type> ts) {
  2091             if (from.tail == null)
  2092                 return ts;
  2093             boolean wild = false;
  2094             if (ts.nonEmpty() && from.nonEmpty()) {
  2095                 Type head1 = subst(ts.head);
  2096                 List<Type> tail1 = subst(ts.tail);
  2097                 if (head1 != ts.head || tail1 != ts.tail)
  2098                     return tail1.prepend(head1);
  2100             return ts;
  2103         public Type visitType(Type t, Void ignored) {
  2104             return t;
  2107         @Override
  2108         public Type visitMethodType(MethodType t, Void ignored) {
  2109             List<Type> argtypes = subst(t.argtypes);
  2110             Type restype = subst(t.restype);
  2111             List<Type> thrown = subst(t.thrown);
  2112             if (argtypes == t.argtypes &&
  2113                 restype == t.restype &&
  2114                 thrown == t.thrown)
  2115                 return t;
  2116             else
  2117                 return new MethodType(argtypes, restype, thrown, t.tsym);
  2120         @Override
  2121         public Type visitTypeVar(TypeVar t, Void ignored) {
  2122             for (List<Type> from = this.from, to = this.to;
  2123                  from.nonEmpty();
  2124                  from = from.tail, to = to.tail) {
  2125                 if (t == from.head) {
  2126                     return to.head.withTypeVar(t);
  2129             return t;
  2132         @Override
  2133         public Type visitClassType(ClassType t, Void ignored) {
  2134             if (!t.isCompound()) {
  2135                 List<Type> typarams = t.getTypeArguments();
  2136                 List<Type> typarams1 = subst(typarams);
  2137                 Type outer = t.getEnclosingType();
  2138                 Type outer1 = subst(outer);
  2139                 if (typarams1 == typarams && outer1 == outer)
  2140                     return t;
  2141                 else
  2142                     return new ClassType(outer1, typarams1, t.tsym);
  2143             } else {
  2144                 Type st = subst(supertype(t));
  2145                 List<Type> is = upperBounds(subst(interfaces(t)));
  2146                 if (st == supertype(t) && is == interfaces(t))
  2147                     return t;
  2148                 else
  2149                     return makeCompoundType(is.prepend(st));
  2153         @Override
  2154         public Type visitWildcardType(WildcardType t, Void ignored) {
  2155             Type bound = t.type;
  2156             if (t.kind != BoundKind.UNBOUND)
  2157                 bound = subst(bound);
  2158             if (bound == t.type) {
  2159                 return t;
  2160             } else {
  2161                 if (t.isExtendsBound() && bound.isExtendsBound())
  2162                     bound = upperBound(bound);
  2163                 return new WildcardType(bound, t.kind, syms.boundClass, t.bound);
  2167         @Override
  2168         public Type visitArrayType(ArrayType t, Void ignored) {
  2169             Type elemtype = subst(t.elemtype);
  2170             if (elemtype == t.elemtype)
  2171                 return t;
  2172             else
  2173                 return new ArrayType(upperBound(elemtype), t.tsym);
  2176         @Override
  2177         public Type visitForAll(ForAll t, Void ignored) {
  2178             List<Type> tvars1 = substBounds(t.tvars, from, to);
  2179             Type qtype1 = subst(t.qtype);
  2180             if (tvars1 == t.tvars && qtype1 == t.qtype) {
  2181                 return t;
  2182             } else if (tvars1 == t.tvars) {
  2183                 return new ForAll(tvars1, qtype1);
  2184             } else {
  2185                 return new ForAll(tvars1, Types.this.subst(qtype1, t.tvars, tvars1));
  2189         @Override
  2190         public Type visitErrorType(ErrorType t, Void ignored) {
  2191             return t;
  2195     public List<Type> substBounds(List<Type> tvars,
  2196                                   List<Type> from,
  2197                                   List<Type> to) {
  2198         if (tvars.isEmpty())
  2199             return tvars;
  2200         ListBuffer<Type> newBoundsBuf = lb();
  2201         boolean changed = false;
  2202         // calculate new bounds
  2203         for (Type t : tvars) {
  2204             TypeVar tv = (TypeVar) t;
  2205             Type bound = subst(tv.bound, from, to);
  2206             if (bound != tv.bound)
  2207                 changed = true;
  2208             newBoundsBuf.append(bound);
  2210         if (!changed)
  2211             return tvars;
  2212         ListBuffer<Type> newTvars = lb();
  2213         // create new type variables without bounds
  2214         for (Type t : tvars) {
  2215             newTvars.append(new TypeVar(t.tsym, null, syms.botType));
  2217         // the new bounds should use the new type variables in place
  2218         // of the old
  2219         List<Type> newBounds = newBoundsBuf.toList();
  2220         from = tvars;
  2221         to = newTvars.toList();
  2222         for (; !newBounds.isEmpty(); newBounds = newBounds.tail) {
  2223             newBounds.head = subst(newBounds.head, from, to);
  2225         newBounds = newBoundsBuf.toList();
  2226         // set the bounds of new type variables to the new bounds
  2227         for (Type t : newTvars.toList()) {
  2228             TypeVar tv = (TypeVar) t;
  2229             tv.bound = newBounds.head;
  2230             newBounds = newBounds.tail;
  2232         return newTvars.toList();
  2235     public TypeVar substBound(TypeVar t, List<Type> from, List<Type> to) {
  2236         Type bound1 = subst(t.bound, from, to);
  2237         if (bound1 == t.bound)
  2238             return t;
  2239         else {
  2240             // create new type variable without bounds
  2241             TypeVar tv = new TypeVar(t.tsym, null, syms.botType);
  2242             // the new bound should use the new type variable in place
  2243             // of the old
  2244             tv.bound = subst(bound1, List.<Type>of(t), List.<Type>of(tv));
  2245             return tv;
  2248     // </editor-fold>
  2250     // <editor-fold defaultstate="collapsed" desc="hasSameBounds">
  2251     /**
  2252      * Does t have the same bounds for quantified variables as s?
  2253      */
  2254     boolean hasSameBounds(ForAll t, ForAll s) {
  2255         List<Type> l1 = t.tvars;
  2256         List<Type> l2 = s.tvars;
  2257         while (l1.nonEmpty() && l2.nonEmpty() &&
  2258                isSameType(l1.head.getUpperBound(),
  2259                           subst(l2.head.getUpperBound(),
  2260                                 s.tvars,
  2261                                 t.tvars))) {
  2262             l1 = l1.tail;
  2263             l2 = l2.tail;
  2265         return l1.isEmpty() && l2.isEmpty();
  2267     // </editor-fold>
  2269     // <editor-fold defaultstate="collapsed" desc="newInstances">
  2270     /** Create new vector of type variables from list of variables
  2271      *  changing all recursive bounds from old to new list.
  2272      */
  2273     public List<Type> newInstances(List<Type> tvars) {
  2274         List<Type> tvars1 = Type.map(tvars, newInstanceFun);
  2275         for (List<Type> l = tvars1; l.nonEmpty(); l = l.tail) {
  2276             TypeVar tv = (TypeVar) l.head;
  2277             tv.bound = subst(tv.bound, tvars, tvars1);
  2279         return tvars1;
  2281     static private Mapping newInstanceFun = new Mapping("newInstanceFun") {
  2282             public Type apply(Type t) { return new TypeVar(t.tsym, t.getUpperBound(), t.getLowerBound()); }
  2283         };
  2284     // </editor-fold>
  2286     // <editor-fold defaultstate="collapsed" desc="createErrorType">
  2287     public Type createErrorType(Type originalType) {
  2288         return new ErrorType(originalType, syms.errSymbol);
  2291     public Type createErrorType(ClassSymbol c, Type originalType) {
  2292         return new ErrorType(c, originalType);
  2295     public Type createErrorType(Name name, TypeSymbol container, Type originalType) {
  2296         return new ErrorType(name, container, originalType);
  2298     // </editor-fold>
  2300     // <editor-fold defaultstate="collapsed" desc="rank">
  2301     /**
  2302      * The rank of a class is the length of the longest path between
  2303      * the class and java.lang.Object in the class inheritance
  2304      * graph. Undefined for all but reference types.
  2305      */
  2306     public int rank(Type t) {
  2307         switch(t.tag) {
  2308         case CLASS: {
  2309             ClassType cls = (ClassType)t;
  2310             if (cls.rank_field < 0) {
  2311                 Name fullname = cls.tsym.getQualifiedName();
  2312                 if (fullname == names.java_lang_Object)
  2313                     cls.rank_field = 0;
  2314                 else {
  2315                     int r = rank(supertype(cls));
  2316                     for (List<Type> l = interfaces(cls);
  2317                          l.nonEmpty();
  2318                          l = l.tail) {
  2319                         if (rank(l.head) > r)
  2320                             r = rank(l.head);
  2322                     cls.rank_field = r + 1;
  2325             return cls.rank_field;
  2327         case TYPEVAR: {
  2328             TypeVar tvar = (TypeVar)t;
  2329             if (tvar.rank_field < 0) {
  2330                 int r = rank(supertype(tvar));
  2331                 for (List<Type> l = interfaces(tvar);
  2332                      l.nonEmpty();
  2333                      l = l.tail) {
  2334                     if (rank(l.head) > r) r = rank(l.head);
  2336                 tvar.rank_field = r + 1;
  2338             return tvar.rank_field;
  2340         case ERROR:
  2341             return 0;
  2342         default:
  2343             throw new AssertionError();
  2346     // </editor-fold>
  2348     /**
  2349      * Helper method for generating a string representation of a given type
  2350      * accordingly to a given locale
  2351      */
  2352     public String toString(Type t, Locale locale) {
  2353         return Printer.createStandardPrinter(messages).visit(t, locale);
  2356     /**
  2357      * Helper method for generating a string representation of a given type
  2358      * accordingly to a given locale
  2359      */
  2360     public String toString(Symbol t, Locale locale) {
  2361         return Printer.createStandardPrinter(messages).visit(t, locale);
  2364     // <editor-fold defaultstate="collapsed" desc="toString">
  2365     /**
  2366      * This toString is slightly more descriptive than the one on Type.
  2368      * @deprecated Types.toString(Type t, Locale l) provides better support
  2369      * for localization
  2370      */
  2371     @Deprecated
  2372     public String toString(Type t) {
  2373         if (t.tag == FORALL) {
  2374             ForAll forAll = (ForAll)t;
  2375             return typaramsString(forAll.tvars) + forAll.qtype;
  2377         return "" + t;
  2379     // where
  2380         private String typaramsString(List<Type> tvars) {
  2381             StringBuffer s = new StringBuffer();
  2382             s.append('<');
  2383             boolean first = true;
  2384             for (Type t : tvars) {
  2385                 if (!first) s.append(", ");
  2386                 first = false;
  2387                 appendTyparamString(((TypeVar)t), s);
  2389             s.append('>');
  2390             return s.toString();
  2392         private void appendTyparamString(TypeVar t, StringBuffer buf) {
  2393             buf.append(t);
  2394             if (t.bound == null ||
  2395                 t.bound.tsym.getQualifiedName() == names.java_lang_Object)
  2396                 return;
  2397             buf.append(" extends "); // Java syntax; no need for i18n
  2398             Type bound = t.bound;
  2399             if (!bound.isCompound()) {
  2400                 buf.append(bound);
  2401             } else if ((erasure(t).tsym.flags() & INTERFACE) == 0) {
  2402                 buf.append(supertype(t));
  2403                 for (Type intf : interfaces(t)) {
  2404                     buf.append('&');
  2405                     buf.append(intf);
  2407             } else {
  2408                 // No superclass was given in bounds.
  2409                 // In this case, supertype is Object, erasure is first interface.
  2410                 boolean first = true;
  2411                 for (Type intf : interfaces(t)) {
  2412                     if (!first) buf.append('&');
  2413                     first = false;
  2414                     buf.append(intf);
  2418     // </editor-fold>
  2420     // <editor-fold defaultstate="collapsed" desc="Determining least upper bounds of types">
  2421     /**
  2422      * A cache for closures.
  2424      * <p>A closure is a list of all the supertypes and interfaces of
  2425      * a class or interface type, ordered by ClassSymbol.precedes
  2426      * (that is, subclasses come first, arbitrary but fixed
  2427      * otherwise).
  2428      */
  2429     private Map<Type,List<Type>> closureCache = new HashMap<Type,List<Type>>();
  2431     /**
  2432      * Returns the closure of a class or interface type.
  2433      */
  2434     public List<Type> closure(Type t) {
  2435         List<Type> cl = closureCache.get(t);
  2436         if (cl == null) {
  2437             Type st = supertype(t);
  2438             if (!t.isCompound()) {
  2439                 if (st.tag == CLASS) {
  2440                     cl = insert(closure(st), t);
  2441                 } else if (st.tag == TYPEVAR) {
  2442                     cl = closure(st).prepend(t);
  2443                 } else {
  2444                     cl = List.of(t);
  2446             } else {
  2447                 cl = closure(supertype(t));
  2449             for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail)
  2450                 cl = union(cl, closure(l.head));
  2451             closureCache.put(t, cl);
  2453         return cl;
  2456     /**
  2457      * Insert a type in a closure
  2458      */
  2459     public List<Type> insert(List<Type> cl, Type t) {
  2460         if (cl.isEmpty() || t.tsym.precedes(cl.head.tsym, this)) {
  2461             return cl.prepend(t);
  2462         } else if (cl.head.tsym.precedes(t.tsym, this)) {
  2463             return insert(cl.tail, t).prepend(cl.head);
  2464         } else {
  2465             return cl;
  2469     /**
  2470      * Form the union of two closures
  2471      */
  2472     public List<Type> union(List<Type> cl1, List<Type> cl2) {
  2473         if (cl1.isEmpty()) {
  2474             return cl2;
  2475         } else if (cl2.isEmpty()) {
  2476             return cl1;
  2477         } else if (cl1.head.tsym.precedes(cl2.head.tsym, this)) {
  2478             return union(cl1.tail, cl2).prepend(cl1.head);
  2479         } else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) {
  2480             return union(cl1, cl2.tail).prepend(cl2.head);
  2481         } else {
  2482             return union(cl1.tail, cl2.tail).prepend(cl1.head);
  2486     /**
  2487      * Intersect two closures
  2488      */
  2489     public List<Type> intersect(List<Type> cl1, List<Type> cl2) {
  2490         if (cl1 == cl2)
  2491             return cl1;
  2492         if (cl1.isEmpty() || cl2.isEmpty())
  2493             return List.nil();
  2494         if (cl1.head.tsym.precedes(cl2.head.tsym, this))
  2495             return intersect(cl1.tail, cl2);
  2496         if (cl2.head.tsym.precedes(cl1.head.tsym, this))
  2497             return intersect(cl1, cl2.tail);
  2498         if (isSameType(cl1.head, cl2.head))
  2499             return intersect(cl1.tail, cl2.tail).prepend(cl1.head);
  2500         if (cl1.head.tsym == cl2.head.tsym &&
  2501             cl1.head.tag == CLASS && cl2.head.tag == CLASS) {
  2502             if (cl1.head.isParameterized() && cl2.head.isParameterized()) {
  2503                 Type merge = merge(cl1.head,cl2.head);
  2504                 return intersect(cl1.tail, cl2.tail).prepend(merge);
  2506             if (cl1.head.isRaw() || cl2.head.isRaw())
  2507                 return intersect(cl1.tail, cl2.tail).prepend(erasure(cl1.head));
  2509         return intersect(cl1.tail, cl2.tail);
  2511     // where
  2512         class TypePair {
  2513             final Type t1;
  2514             final Type t2;
  2515             TypePair(Type t1, Type t2) {
  2516                 this.t1 = t1;
  2517                 this.t2 = t2;
  2519             @Override
  2520             public int hashCode() {
  2521                 return 127 * Types.hashCode(t1) + Types.hashCode(t2);
  2523             @Override
  2524             public boolean equals(Object obj) {
  2525                 if (!(obj instanceof TypePair))
  2526                     return false;
  2527                 TypePair typePair = (TypePair)obj;
  2528                 return isSameType(t1, typePair.t1)
  2529                     && isSameType(t2, typePair.t2);
  2532         Set<TypePair> mergeCache = new HashSet<TypePair>();
  2533         private Type merge(Type c1, Type c2) {
  2534             ClassType class1 = (ClassType) c1;
  2535             List<Type> act1 = class1.getTypeArguments();
  2536             ClassType class2 = (ClassType) c2;
  2537             List<Type> act2 = class2.getTypeArguments();
  2538             ListBuffer<Type> merged = new ListBuffer<Type>();
  2539             List<Type> typarams = class1.tsym.type.getTypeArguments();
  2541             while (act1.nonEmpty() && act2.nonEmpty() && typarams.nonEmpty()) {
  2542                 if (containsType(act1.head, act2.head)) {
  2543                     merged.append(act1.head);
  2544                 } else if (containsType(act2.head, act1.head)) {
  2545                     merged.append(act2.head);
  2546                 } else {
  2547                     TypePair pair = new TypePair(c1, c2);
  2548                     Type m;
  2549                     if (mergeCache.add(pair)) {
  2550                         m = new WildcardType(lub(upperBound(act1.head),
  2551                                                  upperBound(act2.head)),
  2552                                              BoundKind.EXTENDS,
  2553                                              syms.boundClass);
  2554                         mergeCache.remove(pair);
  2555                     } else {
  2556                         m = new WildcardType(syms.objectType,
  2557                                              BoundKind.UNBOUND,
  2558                                              syms.boundClass);
  2560                     merged.append(m.withTypeVar(typarams.head));
  2562                 act1 = act1.tail;
  2563                 act2 = act2.tail;
  2564                 typarams = typarams.tail;
  2566             assert(act1.isEmpty() && act2.isEmpty() && typarams.isEmpty());
  2567             return new ClassType(class1.getEnclosingType(), merged.toList(), class1.tsym);
  2570     /**
  2571      * Return the minimum type of a closure, a compound type if no
  2572      * unique minimum exists.
  2573      */
  2574     private Type compoundMin(List<Type> cl) {
  2575         if (cl.isEmpty()) return syms.objectType;
  2576         List<Type> compound = closureMin(cl);
  2577         if (compound.isEmpty())
  2578             return null;
  2579         else if (compound.tail.isEmpty())
  2580             return compound.head;
  2581         else
  2582             return makeCompoundType(compound);
  2585     /**
  2586      * Return the minimum types of a closure, suitable for computing
  2587      * compoundMin or glb.
  2588      */
  2589     private List<Type> closureMin(List<Type> cl) {
  2590         ListBuffer<Type> classes = lb();
  2591         ListBuffer<Type> interfaces = lb();
  2592         while (!cl.isEmpty()) {
  2593             Type current = cl.head;
  2594             if (current.isInterface())
  2595                 interfaces.append(current);
  2596             else
  2597                 classes.append(current);
  2598             ListBuffer<Type> candidates = lb();
  2599             for (Type t : cl.tail) {
  2600                 if (!isSubtypeNoCapture(current, t))
  2601                     candidates.append(t);
  2603             cl = candidates.toList();
  2605         return classes.appendList(interfaces).toList();
  2608     /**
  2609      * Return the least upper bound of pair of types.  if the lub does
  2610      * not exist return null.
  2611      */
  2612     public Type lub(Type t1, Type t2) {
  2613         return lub(List.of(t1, t2));
  2616     /**
  2617      * Return the least upper bound (lub) of set of types.  If the lub
  2618      * does not exist return the type of null (bottom).
  2619      */
  2620     public Type lub(List<Type> ts) {
  2621         final int ARRAY_BOUND = 1;
  2622         final int CLASS_BOUND = 2;
  2623         int boundkind = 0;
  2624         for (Type t : ts) {
  2625             switch (t.tag) {
  2626             case CLASS:
  2627                 boundkind |= CLASS_BOUND;
  2628                 break;
  2629             case ARRAY:
  2630                 boundkind |= ARRAY_BOUND;
  2631                 break;
  2632             case  TYPEVAR:
  2633                 do {
  2634                     t = t.getUpperBound();
  2635                 } while (t.tag == TYPEVAR);
  2636                 if (t.tag == ARRAY) {
  2637                     boundkind |= ARRAY_BOUND;
  2638                 } else {
  2639                     boundkind |= CLASS_BOUND;
  2641                 break;
  2642             default:
  2643                 if (t.isPrimitive())
  2644                     return syms.errType;
  2647         switch (boundkind) {
  2648         case 0:
  2649             return syms.botType;
  2651         case ARRAY_BOUND:
  2652             // calculate lub(A[], B[])
  2653             List<Type> elements = Type.map(ts, elemTypeFun);
  2654             for (Type t : elements) {
  2655                 if (t.isPrimitive()) {
  2656                     // if a primitive type is found, then return
  2657                     // arraySuperType unless all the types are the
  2658                     // same
  2659                     Type first = ts.head;
  2660                     for (Type s : ts.tail) {
  2661                         if (!isSameType(first, s)) {
  2662                              // lub(int[], B[]) is Cloneable & Serializable
  2663                             return arraySuperType();
  2666                     // all the array types are the same, return one
  2667                     // lub(int[], int[]) is int[]
  2668                     return first;
  2671             // lub(A[], B[]) is lub(A, B)[]
  2672             return new ArrayType(lub(elements), syms.arrayClass);
  2674         case CLASS_BOUND:
  2675             // calculate lub(A, B)
  2676             while (ts.head.tag != CLASS && ts.head.tag != TYPEVAR)
  2677                 ts = ts.tail;
  2678             assert !ts.isEmpty();
  2679             List<Type> cl = closure(ts.head);
  2680             for (Type t : ts.tail) {
  2681                 if (t.tag == CLASS || t.tag == TYPEVAR)
  2682                     cl = intersect(cl, closure(t));
  2684             return compoundMin(cl);
  2686         default:
  2687             // calculate lub(A, B[])
  2688             List<Type> classes = List.of(arraySuperType());
  2689             for (Type t : ts) {
  2690                 if (t.tag != ARRAY) // Filter out any arrays
  2691                     classes = classes.prepend(t);
  2693             // lub(A, B[]) is lub(A, arraySuperType)
  2694             return lub(classes);
  2697     // where
  2698         private Type arraySuperType = null;
  2699         private Type arraySuperType() {
  2700             // initialized lazily to avoid problems during compiler startup
  2701             if (arraySuperType == null) {
  2702                 synchronized (this) {
  2703                     if (arraySuperType == null) {
  2704                         // JLS 10.8: all arrays implement Cloneable and Serializable.
  2705                         arraySuperType = makeCompoundType(List.of(syms.serializableType,
  2706                                                                   syms.cloneableType),
  2707                                                           syms.objectType);
  2711             return arraySuperType;
  2713     // </editor-fold>
  2715     // <editor-fold defaultstate="collapsed" desc="Greatest lower bound">
  2716     public Type glb(List<Type> ts) {
  2717         Type t1 = ts.head;
  2718         for (Type t2 : ts.tail) {
  2719             if (t1.isErroneous())
  2720                 return t1;
  2721             t1 = glb(t1, t2);
  2723         return t1;
  2725     //where
  2726     public Type glb(Type t, Type s) {
  2727         if (s == null)
  2728             return t;
  2729         else if (isSubtypeNoCapture(t, s))
  2730             return t;
  2731         else if (isSubtypeNoCapture(s, t))
  2732             return s;
  2734         List<Type> closure = union(closure(t), closure(s));
  2735         List<Type> bounds = closureMin(closure);
  2737         if (bounds.isEmpty()) {             // length == 0
  2738             return syms.objectType;
  2739         } else if (bounds.tail.isEmpty()) { // length == 1
  2740             return bounds.head;
  2741         } else {                            // length > 1
  2742             int classCount = 0;
  2743             for (Type bound : bounds)
  2744                 if (!bound.isInterface())
  2745                     classCount++;
  2746             if (classCount > 1)
  2747                 return createErrorType(t);
  2749         return makeCompoundType(bounds);
  2751     // </editor-fold>
  2753     // <editor-fold defaultstate="collapsed" desc="hashCode">
  2754     /**
  2755      * Compute a hash code on a type.
  2756      */
  2757     public static int hashCode(Type t) {
  2758         return hashCode.visit(t);
  2760     // where
  2761         private static final UnaryVisitor<Integer> hashCode = new UnaryVisitor<Integer>() {
  2763             public Integer visitType(Type t, Void ignored) {
  2764                 return t.tag;
  2767             @Override
  2768             public Integer visitClassType(ClassType t, Void ignored) {
  2769                 int result = visit(t.getEnclosingType());
  2770                 result *= 127;
  2771                 result += t.tsym.flatName().hashCode();
  2772                 for (Type s : t.getTypeArguments()) {
  2773                     result *= 127;
  2774                     result += visit(s);
  2776                 return result;
  2779             @Override
  2780             public Integer visitWildcardType(WildcardType t, Void ignored) {
  2781                 int result = t.kind.hashCode();
  2782                 if (t.type != null) {
  2783                     result *= 127;
  2784                     result += visit(t.type);
  2786                 return result;
  2789             @Override
  2790             public Integer visitArrayType(ArrayType t, Void ignored) {
  2791                 return visit(t.elemtype) + 12;
  2794             @Override
  2795             public Integer visitTypeVar(TypeVar t, Void ignored) {
  2796                 return System.identityHashCode(t.tsym);
  2799             @Override
  2800             public Integer visitUndetVar(UndetVar t, Void ignored) {
  2801                 return System.identityHashCode(t);
  2804             @Override
  2805             public Integer visitErrorType(ErrorType t, Void ignored) {
  2806                 return 0;
  2808         };
  2809     // </editor-fold>
  2811     // <editor-fold defaultstate="collapsed" desc="Return-Type-Substitutable">
  2812     /**
  2813      * Does t have a result that is a subtype of the result type of s,
  2814      * suitable for covariant returns?  It is assumed that both types
  2815      * are (possibly polymorphic) method types.  Monomorphic method
  2816      * types are handled in the obvious way.  Polymorphic method types
  2817      * require renaming all type variables of one to corresponding
  2818      * type variables in the other, where correspondence is by
  2819      * position in the type parameter list. */
  2820     public boolean resultSubtype(Type t, Type s, Warner warner) {
  2821         List<Type> tvars = t.getTypeArguments();
  2822         List<Type> svars = s.getTypeArguments();
  2823         Type tres = t.getReturnType();
  2824         Type sres = subst(s.getReturnType(), svars, tvars);
  2825         return covariantReturnType(tres, sres, warner);
  2828     /**
  2829      * Return-Type-Substitutable.
  2830      * @see <a href="http://java.sun.com/docs/books/jls/">The Java
  2831      * Language Specification, Third Ed. (8.4.5)</a>
  2832      */
  2833     public boolean returnTypeSubstitutable(Type r1, Type r2) {
  2834         if (hasSameArgs(r1, r2))
  2835             return resultSubtype(r1, r2, Warner.noWarnings);
  2836         else
  2837             return covariantReturnType(r1.getReturnType(),
  2838                                        erasure(r2.getReturnType()),
  2839                                        Warner.noWarnings);
  2842     public boolean returnTypeSubstitutable(Type r1,
  2843                                            Type r2, Type r2res,
  2844                                            Warner warner) {
  2845         if (isSameType(r1.getReturnType(), r2res))
  2846             return true;
  2847         if (r1.getReturnType().isPrimitive() || r2res.isPrimitive())
  2848             return false;
  2850         if (hasSameArgs(r1, r2))
  2851             return covariantReturnType(r1.getReturnType(), r2res, warner);
  2852         if (!source.allowCovariantReturns())
  2853             return false;
  2854         if (isSubtypeUnchecked(r1.getReturnType(), r2res, warner))
  2855             return true;
  2856         if (!isSubtype(r1.getReturnType(), erasure(r2res)))
  2857             return false;
  2858         warner.warnUnchecked();
  2859         return true;
  2862     /**
  2863      * Is t an appropriate return type in an overrider for a
  2864      * method that returns s?
  2865      */
  2866     public boolean covariantReturnType(Type t, Type s, Warner warner) {
  2867         return
  2868             isSameType(t, s) ||
  2869             source.allowCovariantReturns() &&
  2870             !t.isPrimitive() &&
  2871             !s.isPrimitive() &&
  2872             isAssignable(t, s, warner);
  2874     // </editor-fold>
  2876     // <editor-fold defaultstate="collapsed" desc="Box/unbox support">
  2877     /**
  2878      * Return the class that boxes the given primitive.
  2879      */
  2880     public ClassSymbol boxedClass(Type t) {
  2881         return reader.enterClass(syms.boxedName[t.tag]);
  2884     /**
  2885      * Return the primitive type corresponding to a boxed type.
  2886      */
  2887     public Type unboxedType(Type t) {
  2888         if (allowBoxing) {
  2889             for (int i=0; i<syms.boxedName.length; i++) {
  2890                 Name box = syms.boxedName[i];
  2891                 if (box != null &&
  2892                     asSuper(t, reader.enterClass(box)) != null)
  2893                     return syms.typeOfTag[i];
  2896         return Type.noType;
  2898     // </editor-fold>
  2900     // <editor-fold defaultstate="collapsed" desc="Capture conversion">
  2901     /*
  2902      * JLS 3rd Ed. 5.1.10 Capture Conversion:
  2904      * Let G name a generic type declaration with n formal type
  2905      * parameters A1 ... An with corresponding bounds U1 ... Un. There
  2906      * exists a capture conversion from G<T1 ... Tn> to G<S1 ... Sn>,
  2907      * where, for 1 <= i <= n:
  2909      * + If Ti is a wildcard type argument (4.5.1) of the form ? then
  2910      *   Si is a fresh type variable whose upper bound is
  2911      *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is the null
  2912      *   type.
  2914      * + If Ti is a wildcard type argument of the form ? extends Bi,
  2915      *   then Si is a fresh type variable whose upper bound is
  2916      *   glb(Bi, Ui[A1 := S1, ..., An := Sn]) and whose lower bound is
  2917      *   the null type, where glb(V1,... ,Vm) is V1 & ... & Vm. It is
  2918      *   a compile-time error if for any two classes (not interfaces)
  2919      *   Vi and Vj,Vi is not a subclass of Vj or vice versa.
  2921      * + If Ti is a wildcard type argument of the form ? super Bi,
  2922      *   then Si is a fresh type variable whose upper bound is
  2923      *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is Bi.
  2925      * + Otherwise, Si = Ti.
  2927      * Capture conversion on any type other than a parameterized type
  2928      * (4.5) acts as an identity conversion (5.1.1). Capture
  2929      * conversions never require a special action at run time and
  2930      * therefore never throw an exception at run time.
  2932      * Capture conversion is not applied recursively.
  2933      */
  2934     /**
  2935      * Capture conversion as specified by JLS 3rd Ed.
  2936      */
  2938     public List<Type> capture(List<Type> ts) {
  2939         List<Type> buf = List.nil();
  2940         for (Type t : ts) {
  2941             buf = buf.prepend(capture(t));
  2943         return buf.reverse();
  2945     public Type capture(Type t) {
  2946         if (t.tag != CLASS)
  2947             return t;
  2948         ClassType cls = (ClassType)t;
  2949         if (cls.isRaw() || !cls.isParameterized())
  2950             return cls;
  2952         ClassType G = (ClassType)cls.asElement().asType();
  2953         List<Type> A = G.getTypeArguments();
  2954         List<Type> T = cls.getTypeArguments();
  2955         List<Type> S = freshTypeVariables(T);
  2957         List<Type> currentA = A;
  2958         List<Type> currentT = T;
  2959         List<Type> currentS = S;
  2960         boolean captured = false;
  2961         while (!currentA.isEmpty() &&
  2962                !currentT.isEmpty() &&
  2963                !currentS.isEmpty()) {
  2964             if (currentS.head != currentT.head) {
  2965                 captured = true;
  2966                 WildcardType Ti = (WildcardType)currentT.head;
  2967                 Type Ui = currentA.head.getUpperBound();
  2968                 CapturedType Si = (CapturedType)currentS.head;
  2969                 if (Ui == null)
  2970                     Ui = syms.objectType;
  2971                 switch (Ti.kind) {
  2972                 case UNBOUND:
  2973                     Si.bound = subst(Ui, A, S);
  2974                     Si.lower = syms.botType;
  2975                     break;
  2976                 case EXTENDS:
  2977                     Si.bound = glb(Ti.getExtendsBound(), subst(Ui, A, S));
  2978                     Si.lower = syms.botType;
  2979                     break;
  2980                 case SUPER:
  2981                     Si.bound = subst(Ui, A, S);
  2982                     Si.lower = Ti.getSuperBound();
  2983                     break;
  2985                 if (Si.bound == Si.lower)
  2986                     currentS.head = Si.bound;
  2988             currentA = currentA.tail;
  2989             currentT = currentT.tail;
  2990             currentS = currentS.tail;
  2992         if (!currentA.isEmpty() || !currentT.isEmpty() || !currentS.isEmpty())
  2993             return erasure(t); // some "rare" type involved
  2995         if (captured)
  2996             return new ClassType(cls.getEnclosingType(), S, cls.tsym);
  2997         else
  2998             return t;
  3000     // where
  3001         public List<Type> freshTypeVariables(List<Type> types) {
  3002             ListBuffer<Type> result = lb();
  3003             for (Type t : types) {
  3004                 if (t.tag == WILDCARD) {
  3005                     Type bound = ((WildcardType)t).getExtendsBound();
  3006                     if (bound == null)
  3007                         bound = syms.objectType;
  3008                     result.append(new CapturedType(capturedName,
  3009                                                    syms.noSymbol,
  3010                                                    bound,
  3011                                                    syms.botType,
  3012                                                    (WildcardType)t));
  3013                 } else {
  3014                     result.append(t);
  3017             return result.toList();
  3019     // </editor-fold>
  3021     // <editor-fold defaultstate="collapsed" desc="Internal utility methods">
  3022     private List<Type> upperBounds(List<Type> ss) {
  3023         if (ss.isEmpty()) return ss;
  3024         Type head = upperBound(ss.head);
  3025         List<Type> tail = upperBounds(ss.tail);
  3026         if (head != ss.head || tail != ss.tail)
  3027             return tail.prepend(head);
  3028         else
  3029             return ss;
  3032     private boolean sideCast(Type from, Type to, Warner warn) {
  3033         // We are casting from type $from$ to type $to$, which are
  3034         // non-final unrelated types.  This method
  3035         // tries to reject a cast by transferring type parameters
  3036         // from $to$ to $from$ by common superinterfaces.
  3037         boolean reverse = false;
  3038         Type target = to;
  3039         if ((to.tsym.flags() & INTERFACE) == 0) {
  3040             assert (from.tsym.flags() & INTERFACE) != 0;
  3041             reverse = true;
  3042             to = from;
  3043             from = target;
  3045         List<Type> commonSupers = superClosure(to, erasure(from));
  3046         boolean giveWarning = commonSupers.isEmpty();
  3047         // The arguments to the supers could be unified here to
  3048         // get a more accurate analysis
  3049         while (commonSupers.nonEmpty()) {
  3050             Type t1 = asSuper(from, commonSupers.head.tsym);
  3051             Type t2 = commonSupers.head; // same as asSuper(to, commonSupers.head.tsym);
  3052             if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
  3053                 return false;
  3054             giveWarning = giveWarning || (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2));
  3055             commonSupers = commonSupers.tail;
  3057         if (giveWarning && !isReifiable(reverse ? from : to))
  3058             warn.warnUnchecked();
  3059         if (!source.allowCovariantReturns())
  3060             // reject if there is a common method signature with
  3061             // incompatible return types.
  3062             chk.checkCompatibleAbstracts(warn.pos(), from, to);
  3063         return true;
  3066     private boolean sideCastFinal(Type from, Type to, Warner warn) {
  3067         // We are casting from type $from$ to type $to$, which are
  3068         // unrelated types one of which is final and the other of
  3069         // which is an interface.  This method
  3070         // tries to reject a cast by transferring type parameters
  3071         // from the final class to the interface.
  3072         boolean reverse = false;
  3073         Type target = to;
  3074         if ((to.tsym.flags() & INTERFACE) == 0) {
  3075             assert (from.tsym.flags() & INTERFACE) != 0;
  3076             reverse = true;
  3077             to = from;
  3078             from = target;
  3080         assert (from.tsym.flags() & FINAL) != 0;
  3081         Type t1 = asSuper(from, to.tsym);
  3082         if (t1 == null) return false;
  3083         Type t2 = to;
  3084         if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
  3085             return false;
  3086         if (!source.allowCovariantReturns())
  3087             // reject if there is a common method signature with
  3088             // incompatible return types.
  3089             chk.checkCompatibleAbstracts(warn.pos(), from, to);
  3090         if (!isReifiable(target) &&
  3091             (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2)))
  3092             warn.warnUnchecked();
  3093         return true;
  3096     private boolean giveWarning(Type from, Type to) {
  3097         Type subFrom = asSub(from, to.tsym);
  3098         return to.isParameterized() &&
  3099                 (!(isUnbounded(to) ||
  3100                 isSubtype(from, to) ||
  3101                 ((subFrom != null) && isSameType(subFrom, to))));
  3104     private List<Type> superClosure(Type t, Type s) {
  3105         List<Type> cl = List.nil();
  3106         for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
  3107             if (isSubtype(s, erasure(l.head))) {
  3108                 cl = insert(cl, l.head);
  3109             } else {
  3110                 cl = union(cl, superClosure(l.head, s));
  3113         return cl;
  3116     private boolean containsTypeEquivalent(Type t, Type s) {
  3117         return
  3118             isSameType(t, s) || // shortcut
  3119             containsType(t, s) && containsType(s, t);
  3122     // <editor-fold defaultstate="collapsed" desc="adapt">
  3123     /**
  3124      * Adapt a type by computing a substitution which maps a source
  3125      * type to a target type.
  3127      * @param source    the source type
  3128      * @param target    the target type
  3129      * @param from      the type variables of the computed substitution
  3130      * @param to        the types of the computed substitution.
  3131      */
  3132     public void adapt(Type source,
  3133                        Type target,
  3134                        ListBuffer<Type> from,
  3135                        ListBuffer<Type> to) throws AdaptFailure {
  3136         new Adapter(from, to).adapt(source, target);
  3139     class Adapter extends SimpleVisitor<Void, Type> {
  3141         ListBuffer<Type> from;
  3142         ListBuffer<Type> to;
  3143         Map<Symbol,Type> mapping;
  3145         Adapter(ListBuffer<Type> from, ListBuffer<Type> to) {
  3146             this.from = from;
  3147             this.to = to;
  3148             mapping = new HashMap<Symbol,Type>();
  3151         public void adapt(Type source, Type target) throws AdaptFailure {
  3152             visit(source, target);
  3153             List<Type> fromList = from.toList();
  3154             List<Type> toList = to.toList();
  3155             while (!fromList.isEmpty()) {
  3156                 Type val = mapping.get(fromList.head.tsym);
  3157                 if (toList.head != val)
  3158                     toList.head = val;
  3159                 fromList = fromList.tail;
  3160                 toList = toList.tail;
  3164         @Override
  3165         public Void visitClassType(ClassType source, Type target) throws AdaptFailure {
  3166             if (target.tag == CLASS)
  3167                 adaptRecursive(source.allparams(), target.allparams());
  3168             return null;
  3171         @Override
  3172         public Void visitArrayType(ArrayType source, Type target) throws AdaptFailure {
  3173             if (target.tag == ARRAY)
  3174                 adaptRecursive(elemtype(source), elemtype(target));
  3175             return null;
  3178         @Override
  3179         public Void visitWildcardType(WildcardType source, Type target) throws AdaptFailure {
  3180             if (source.isExtendsBound())
  3181                 adaptRecursive(upperBound(source), upperBound(target));
  3182             else if (source.isSuperBound())
  3183                 adaptRecursive(lowerBound(source), lowerBound(target));
  3184             return null;
  3187         @Override
  3188         public Void visitTypeVar(TypeVar source, Type target) throws AdaptFailure {
  3189             // Check to see if there is
  3190             // already a mapping for $source$, in which case
  3191             // the old mapping will be merged with the new
  3192             Type val = mapping.get(source.tsym);
  3193             if (val != null) {
  3194                 if (val.isSuperBound() && target.isSuperBound()) {
  3195                     val = isSubtype(lowerBound(val), lowerBound(target))
  3196                         ? target : val;
  3197                 } else if (val.isExtendsBound() && target.isExtendsBound()) {
  3198                     val = isSubtype(upperBound(val), upperBound(target))
  3199                         ? val : target;
  3200                 } else if (!isSameType(val, target)) {
  3201                     throw new AdaptFailure();
  3203             } else {
  3204                 val = target;
  3205                 from.append(source);
  3206                 to.append(target);
  3208             mapping.put(source.tsym, val);
  3209             return null;
  3212         @Override
  3213         public Void visitType(Type source, Type target) {
  3214             return null;
  3217         private Set<TypePair> cache = new HashSet<TypePair>();
  3219         private void adaptRecursive(Type source, Type target) {
  3220             TypePair pair = new TypePair(source, target);
  3221             if (cache.add(pair)) {
  3222                 try {
  3223                     visit(source, target);
  3224                 } finally {
  3225                     cache.remove(pair);
  3230         private void adaptRecursive(List<Type> source, List<Type> target) {
  3231             if (source.length() == target.length()) {
  3232                 while (source.nonEmpty()) {
  3233                     adaptRecursive(source.head, target.head);
  3234                     source = source.tail;
  3235                     target = target.tail;
  3241     public static class AdaptFailure extends RuntimeException {
  3242         static final long serialVersionUID = -7490231548272701566L;
  3245     private void adaptSelf(Type t,
  3246                            ListBuffer<Type> from,
  3247                            ListBuffer<Type> to) {
  3248         try {
  3249             //if (t.tsym.type != t)
  3250                 adapt(t.tsym.type, t, from, to);
  3251         } catch (AdaptFailure ex) {
  3252             // Adapt should never fail calculating a mapping from
  3253             // t.tsym.type to t as there can be no merge problem.
  3254             throw new AssertionError(ex);
  3257     // </editor-fold>
  3259     /**
  3260      * Rewrite all type variables (universal quantifiers) in the given
  3261      * type to wildcards (existential quantifiers).  This is used to
  3262      * determine if a cast is allowed.  For example, if high is true
  3263      * and {@code T <: Number}, then {@code List<T>} is rewritten to
  3264      * {@code List<?  extends Number>}.  Since {@code List<Integer> <:
  3265      * List<? extends Number>} a {@code List<T>} can be cast to {@code
  3266      * List<Integer>} with a warning.
  3267      * @param t a type
  3268      * @param high if true return an upper bound; otherwise a lower
  3269      * bound
  3270      * @param rewriteTypeVars only rewrite captured wildcards if false;
  3271      * otherwise rewrite all type variables
  3272      * @return the type rewritten with wildcards (existential
  3273      * quantifiers) only
  3274      */
  3275     private Type rewriteQuantifiers(Type t, boolean high, boolean rewriteTypeVars) {
  3276         return new Rewriter(high, rewriteTypeVars).rewrite(t);
  3279     class Rewriter extends UnaryVisitor<Type> {
  3281         boolean high;
  3282         boolean rewriteTypeVars;
  3284         Rewriter(boolean high, boolean rewriteTypeVars) {
  3285             this.high = high;
  3286             this.rewriteTypeVars = rewriteTypeVars;
  3289         Type rewrite(Type t) {
  3290             ListBuffer<Type> from = new ListBuffer<Type>();
  3291             ListBuffer<Type> to = new ListBuffer<Type>();
  3292             adaptSelf(t, from, to);
  3293             ListBuffer<Type> rewritten = new ListBuffer<Type>();
  3294             List<Type> formals = from.toList();
  3295             boolean changed = false;
  3296             for (Type arg : to.toList()) {
  3297                 Type bound = visit(arg);
  3298                 if (arg != bound) {
  3299                     changed = true;
  3300                     bound = high ? makeExtendsWildcard(bound, (TypeVar)formals.head)
  3301                               : makeSuperWildcard(bound, (TypeVar)formals.head);
  3303                 rewritten.append(bound);
  3304                 formals = formals.tail;
  3306             if (changed)
  3307                 return subst(t.tsym.type, from.toList(), rewritten.toList());
  3308             else
  3309                 return t;
  3312         public Type visitType(Type t, Void s) {
  3313             return high ? upperBound(t) : lowerBound(t);
  3316         @Override
  3317         public Type visitCapturedType(CapturedType t, Void s) {
  3318             return visitWildcardType(t.wildcard, null);
  3321         @Override
  3322         public Type visitTypeVar(TypeVar t, Void s) {
  3323             if (rewriteTypeVars)
  3324                 return high ? t.bound : syms.botType;
  3325             else
  3326                 return t;
  3329         @Override
  3330         public Type visitWildcardType(WildcardType t, Void s) {
  3331             Type bound = high ? t.getExtendsBound() :
  3332                                 t.getSuperBound();
  3333             if (bound == null)
  3334                 bound = high ? syms.objectType : syms.botType;
  3335             return bound;
  3339     /**
  3340      * Create a wildcard with the given upper (extends) bound; create
  3341      * an unbounded wildcard if bound is Object.
  3343      * @param bound the upper bound
  3344      * @param formal the formal type parameter that will be
  3345      * substituted by the wildcard
  3346      */
  3347     private WildcardType makeExtendsWildcard(Type bound, TypeVar formal) {
  3348         if (bound == syms.objectType) {
  3349             return new WildcardType(syms.objectType,
  3350                                     BoundKind.UNBOUND,
  3351                                     syms.boundClass,
  3352                                     formal);
  3353         } else {
  3354             return new WildcardType(bound,
  3355                                     BoundKind.EXTENDS,
  3356                                     syms.boundClass,
  3357                                     formal);
  3361     /**
  3362      * Create a wildcard with the given lower (super) bound; create an
  3363      * unbounded wildcard if bound is bottom (type of {@code null}).
  3365      * @param bound the lower bound
  3366      * @param formal the formal type parameter that will be
  3367      * substituted by the wildcard
  3368      */
  3369     private WildcardType makeSuperWildcard(Type bound, TypeVar formal) {
  3370         if (bound.tag == BOT) {
  3371             return new WildcardType(syms.objectType,
  3372                                     BoundKind.UNBOUND,
  3373                                     syms.boundClass,
  3374                                     formal);
  3375         } else {
  3376             return new WildcardType(bound,
  3377                                     BoundKind.SUPER,
  3378                                     syms.boundClass,
  3379                                     formal);
  3383     /**
  3384      * A wrapper for a type that allows use in sets.
  3385      */
  3386     class SingletonType {
  3387         final Type t;
  3388         SingletonType(Type t) {
  3389             this.t = t;
  3391         public int hashCode() {
  3392             return Types.hashCode(t);
  3394         public boolean equals(Object obj) {
  3395             return (obj instanceof SingletonType) &&
  3396                 isSameType(t, ((SingletonType)obj).t);
  3398         public String toString() {
  3399             return t.toString();
  3402     // </editor-fold>
  3404     // <editor-fold defaultstate="collapsed" desc="Visitors">
  3405     /**
  3406      * A default visitor for types.  All visitor methods except
  3407      * visitType are implemented by delegating to visitType.  Concrete
  3408      * subclasses must provide an implementation of visitType and can
  3409      * override other methods as needed.
  3411      * @param <R> the return type of the operation implemented by this
  3412      * visitor; use Void if no return type is needed.
  3413      * @param <S> the type of the second argument (the first being the
  3414      * type itself) of the operation implemented by this visitor; use
  3415      * Void if a second argument is not needed.
  3416      */
  3417     public static abstract class DefaultTypeVisitor<R,S> implements Type.Visitor<R,S> {
  3418         final public R visit(Type t, S s)               { return t.accept(this, s); }
  3419         public R visitClassType(ClassType t, S s)       { return visitType(t, s); }
  3420         public R visitWildcardType(WildcardType t, S s) { return visitType(t, s); }
  3421         public R visitArrayType(ArrayType t, S s)       { return visitType(t, s); }
  3422         public R visitMethodType(MethodType t, S s)     { return visitType(t, s); }
  3423         public R visitPackageType(PackageType t, S s)   { return visitType(t, s); }
  3424         public R visitTypeVar(TypeVar t, S s)           { return visitType(t, s); }
  3425         public R visitCapturedType(CapturedType t, S s) { return visitType(t, s); }
  3426         public R visitForAll(ForAll t, S s)             { return visitType(t, s); }
  3427         public R visitUndetVar(UndetVar t, S s)         { return visitType(t, s); }
  3428         public R visitErrorType(ErrorType t, S s)       { return visitType(t, s); }
  3431     /**
  3432      * A default visitor for symbols.  All visitor methods except
  3433      * visitSymbol are implemented by delegating to visitSymbol.  Concrete
  3434      * subclasses must provide an implementation of visitSymbol and can
  3435      * override other methods as needed.
  3437      * @param <R> the return type of the operation implemented by this
  3438      * visitor; use Void if no return type is needed.
  3439      * @param <S> the type of the second argument (the first being the
  3440      * symbol itself) of the operation implemented by this visitor; use
  3441      * Void if a second argument is not needed.
  3442      */
  3443     public static abstract class DefaultSymbolVisitor<R,S> implements Symbol.Visitor<R,S> {
  3444         final public R visit(Symbol s, S arg)                   { return s.accept(this, arg); }
  3445         public R visitClassSymbol(ClassSymbol s, S arg)         { return visitSymbol(s, arg); }
  3446         public R visitMethodSymbol(MethodSymbol s, S arg)       { return visitSymbol(s, arg); }
  3447         public R visitOperatorSymbol(OperatorSymbol s, S arg)   { return visitSymbol(s, arg); }
  3448         public R visitPackageSymbol(PackageSymbol s, S arg)     { return visitSymbol(s, arg); }
  3449         public R visitTypeSymbol(TypeSymbol s, S arg)           { return visitSymbol(s, arg); }
  3450         public R visitVarSymbol(VarSymbol s, S arg)             { return visitSymbol(s, arg); }
  3453     /**
  3454      * A <em>simple</em> visitor for types.  This visitor is simple as
  3455      * captured wildcards, for-all types (generic methods), and
  3456      * undetermined type variables (part of inference) are hidden.
  3457      * Captured wildcards are hidden by treating them as type
  3458      * variables and the rest are hidden by visiting their qtypes.
  3460      * @param <R> the return type of the operation implemented by this
  3461      * visitor; use Void if no return type is needed.
  3462      * @param <S> the type of the second argument (the first being the
  3463      * type itself) of the operation implemented by this visitor; use
  3464      * Void if a second argument is not needed.
  3465      */
  3466     public static abstract class SimpleVisitor<R,S> extends DefaultTypeVisitor<R,S> {
  3467         @Override
  3468         public R visitCapturedType(CapturedType t, S s) {
  3469             return visitTypeVar(t, s);
  3471         @Override
  3472         public R visitForAll(ForAll t, S s) {
  3473             return visit(t.qtype, s);
  3475         @Override
  3476         public R visitUndetVar(UndetVar t, S s) {
  3477             return visit(t.qtype, s);
  3481     /**
  3482      * A plain relation on types.  That is a 2-ary function on the
  3483      * form Type&nbsp;&times;&nbsp;Type&nbsp;&rarr;&nbsp;Boolean.
  3484      * <!-- In plain text: Type x Type -> Boolean -->
  3485      */
  3486     public static abstract class TypeRelation extends SimpleVisitor<Boolean,Type> {}
  3488     /**
  3489      * A convenience visitor for implementing operations that only
  3490      * require one argument (the type itself), that is, unary
  3491      * operations.
  3493      * @param <R> the return type of the operation implemented by this
  3494      * visitor; use Void if no return type is needed.
  3495      */
  3496     public static abstract class UnaryVisitor<R> extends SimpleVisitor<R,Void> {
  3497         final public R visit(Type t) { return t.accept(this, null); }
  3500     /**
  3501      * A visitor for implementing a mapping from types to types.  The
  3502      * default behavior of this class is to implement the identity
  3503      * mapping (mapping a type to itself).  This can be overridden in
  3504      * subclasses.
  3506      * @param <S> the type of the second argument (the first being the
  3507      * type itself) of this mapping; use Void if a second argument is
  3508      * not needed.
  3509      */
  3510     public static class MapVisitor<S> extends DefaultTypeVisitor<Type,S> {
  3511         final public Type visit(Type t) { return t.accept(this, null); }
  3512         public Type visitType(Type t, S s) { return t; }
  3514     // </editor-fold>

mercurial