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

Thu, 03 Mar 2011 17:34:58 +0000

author
mcimadamore
date
Thu, 03 Mar 2011 17:34:58 +0000
changeset 907
32565546784b
parent 904
4baab658f357
child 950
f5b5112ee1cc
permissions
-rw-r--r--

7022054: Invalid compiler error on covariant overriding methods with the same erasure
Summary: Rules for method clash use notion of subsignature, which is sometimes too strict and incompatible with JDK 6
Reviewed-by: jjg

     1 /*
     2  * Copyright (c) 2003, 2011, 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.code.Attribute.RetentionPolicy;
    36 import com.sun.tools.javac.code.Lint.LintCategory;
    37 import com.sun.tools.javac.comp.Check;
    39 import static com.sun.tools.javac.code.Scope.*;
    40 import static com.sun.tools.javac.code.Type.*;
    41 import static com.sun.tools.javac.code.TypeTags.*;
    42 import static com.sun.tools.javac.code.Symbol.*;
    43 import static com.sun.tools.javac.code.Flags.*;
    44 import static com.sun.tools.javac.code.BoundKind.*;
    45 import static com.sun.tools.javac.util.ListBuffer.lb;
    47 /**
    48  * Utility class containing various operations on types.
    49  *
    50  * <p>Unless other names are more illustrative, the following naming
    51  * conventions should be observed in this file:
    52  *
    53  * <dl>
    54  * <dt>t</dt>
    55  * <dd>If the first argument to an operation is a type, it should be named t.</dd>
    56  * <dt>s</dt>
    57  * <dd>Similarly, if the second argument to an operation is a type, it should be named s.</dd>
    58  * <dt>ts</dt>
    59  * <dd>If an operations takes a list of types, the first should be named ts.</dd>
    60  * <dt>ss</dt>
    61  * <dd>A second list of types should be named ss.</dd>
    62  * </dl>
    63  *
    64  * <p><b>This is NOT part of any supported API.
    65  * If you write code that depends on this, you do so at your own risk.
    66  * This code and its internal interfaces are subject to change or
    67  * deletion without notice.</b>
    68  */
    69 public class Types {
    70     protected static final Context.Key<Types> typesKey =
    71         new Context.Key<Types>();
    73     final Symtab syms;
    74     final JavacMessages messages;
    75     final Names names;
    76     final boolean allowBoxing;
    77     final ClassReader reader;
    78     final Source source;
    79     final Check chk;
    80     List<Warner> warnStack = List.nil();
    81     final Name capturedName;
    83     // <editor-fold defaultstate="collapsed" desc="Instantiating">
    84     public static Types instance(Context context) {
    85         Types instance = context.get(typesKey);
    86         if (instance == null)
    87             instance = new Types(context);
    88         return instance;
    89     }
    91     protected Types(Context context) {
    92         context.put(typesKey, this);
    93         syms = Symtab.instance(context);
    94         names = Names.instance(context);
    95         allowBoxing = Source.instance(context).allowBoxing();
    96         reader = ClassReader.instance(context);
    97         source = Source.instance(context);
    98         chk = Check.instance(context);
    99         capturedName = names.fromString("<captured wildcard>");
   100         messages = JavacMessages.instance(context);
   101     }
   102     // </editor-fold>
   104     // <editor-fold defaultstate="collapsed" desc="upperBound">
   105     /**
   106      * The "rvalue conversion".<br>
   107      * The upper bound of most types is the type
   108      * itself.  Wildcards, on the other hand have upper
   109      * and lower bounds.
   110      * @param t a type
   111      * @return the upper bound of the given type
   112      */
   113     public Type upperBound(Type t) {
   114         return upperBound.visit(t);
   115     }
   116     // where
   117         private final MapVisitor<Void> upperBound = new MapVisitor<Void>() {
   119             @Override
   120             public Type visitWildcardType(WildcardType t, Void ignored) {
   121                 if (t.isSuperBound())
   122                     return t.bound == null ? syms.objectType : t.bound.bound;
   123                 else
   124                     return visit(t.type);
   125             }
   127             @Override
   128             public Type visitCapturedType(CapturedType t, Void ignored) {
   129                 return visit(t.bound);
   130             }
   131         };
   132     // </editor-fold>
   134     // <editor-fold defaultstate="collapsed" desc="lowerBound">
   135     /**
   136      * The "lvalue conversion".<br>
   137      * The lower bound of most types is the type
   138      * itself.  Wildcards, on the other hand have upper
   139      * and lower bounds.
   140      * @param t a type
   141      * @return the lower bound of the given type
   142      */
   143     public Type lowerBound(Type t) {
   144         return lowerBound.visit(t);
   145     }
   146     // where
   147         private final MapVisitor<Void> lowerBound = new MapVisitor<Void>() {
   149             @Override
   150             public Type visitWildcardType(WildcardType t, Void ignored) {
   151                 return t.isExtendsBound() ? syms.botType : visit(t.type);
   152             }
   154             @Override
   155             public Type visitCapturedType(CapturedType t, Void ignored) {
   156                 return visit(t.getLowerBound());
   157             }
   158         };
   159     // </editor-fold>
   161     // <editor-fold defaultstate="collapsed" desc="isUnbounded">
   162     /**
   163      * Checks that all the arguments to a class are unbounded
   164      * wildcards or something else that doesn't make any restrictions
   165      * on the arguments. If a class isUnbounded, a raw super- or
   166      * subclass can be cast to it without a warning.
   167      * @param t a type
   168      * @return true iff the given type is unbounded or raw
   169      */
   170     public boolean isUnbounded(Type t) {
   171         return isUnbounded.visit(t);
   172     }
   173     // where
   174         private final UnaryVisitor<Boolean> isUnbounded = new UnaryVisitor<Boolean>() {
   176             public Boolean visitType(Type t, Void ignored) {
   177                 return true;
   178             }
   180             @Override
   181             public Boolean visitClassType(ClassType t, Void ignored) {
   182                 List<Type> parms = t.tsym.type.allparams();
   183                 List<Type> args = t.allparams();
   184                 while (parms.nonEmpty()) {
   185                     WildcardType unb = new WildcardType(syms.objectType,
   186                                                         BoundKind.UNBOUND,
   187                                                         syms.boundClass,
   188                                                         (TypeVar)parms.head);
   189                     if (!containsType(args.head, unb))
   190                         return false;
   191                     parms = parms.tail;
   192                     args = args.tail;
   193                 }
   194                 return true;
   195             }
   196         };
   197     // </editor-fold>
   199     // <editor-fold defaultstate="collapsed" desc="asSub">
   200     /**
   201      * Return the least specific subtype of t that starts with symbol
   202      * sym.  If none exists, return null.  The least specific subtype
   203      * is determined as follows:
   204      *
   205      * <p>If there is exactly one parameterized instance of sym that is a
   206      * subtype of t, that parameterized instance is returned.<br>
   207      * Otherwise, if the plain type or raw type `sym' is a subtype of
   208      * type t, the type `sym' itself is returned.  Otherwise, null is
   209      * returned.
   210      */
   211     public Type asSub(Type t, Symbol sym) {
   212         return asSub.visit(t, sym);
   213     }
   214     // where
   215         private final SimpleVisitor<Type,Symbol> asSub = new SimpleVisitor<Type,Symbol>() {
   217             public Type visitType(Type t, Symbol sym) {
   218                 return null;
   219             }
   221             @Override
   222             public Type visitClassType(ClassType t, Symbol sym) {
   223                 if (t.tsym == sym)
   224                     return t;
   225                 Type base = asSuper(sym.type, t.tsym);
   226                 if (base == null)
   227                     return null;
   228                 ListBuffer<Type> from = new ListBuffer<Type>();
   229                 ListBuffer<Type> to = new ListBuffer<Type>();
   230                 try {
   231                     adapt(base, t, from, to);
   232                 } catch (AdaptFailure ex) {
   233                     return null;
   234                 }
   235                 Type res = subst(sym.type, from.toList(), to.toList());
   236                 if (!isSubtype(res, t))
   237                     return null;
   238                 ListBuffer<Type> openVars = new ListBuffer<Type>();
   239                 for (List<Type> l = sym.type.allparams();
   240                      l.nonEmpty(); l = l.tail)
   241                     if (res.contains(l.head) && !t.contains(l.head))
   242                         openVars.append(l.head);
   243                 if (openVars.nonEmpty()) {
   244                     if (t.isRaw()) {
   245                         // The subtype of a raw type is raw
   246                         res = erasure(res);
   247                     } else {
   248                         // Unbound type arguments default to ?
   249                         List<Type> opens = openVars.toList();
   250                         ListBuffer<Type> qs = new ListBuffer<Type>();
   251                         for (List<Type> iter = opens; iter.nonEmpty(); iter = iter.tail) {
   252                             qs.append(new WildcardType(syms.objectType, BoundKind.UNBOUND, syms.boundClass, (TypeVar) iter.head));
   253                         }
   254                         res = subst(res, opens, qs.toList());
   255                     }
   256                 }
   257                 return res;
   258             }
   260             @Override
   261             public Type visitErrorType(ErrorType t, Symbol sym) {
   262                 return t;
   263             }
   264         };
   265     // </editor-fold>
   267     // <editor-fold defaultstate="collapsed" desc="isConvertible">
   268     /**
   269      * Is t a subtype of or convertiable via boxing/unboxing
   270      * convertions to s?
   271      */
   272     public boolean isConvertible(Type t, Type s, Warner warn) {
   273         boolean tPrimitive = t.isPrimitive();
   274         boolean sPrimitive = s.isPrimitive();
   275         if (tPrimitive == sPrimitive) {
   276             checkUnsafeVarargsConversion(t, s, warn);
   277             return isSubtypeUnchecked(t, s, warn);
   278         }
   279         if (!allowBoxing) return false;
   280         return tPrimitive
   281             ? isSubtype(boxedClass(t).type, s)
   282             : isSubtype(unboxedType(t), s);
   283     }
   284     //where
   285     private void checkUnsafeVarargsConversion(Type t, Type s, Warner warn) {
   286         if (t.tag != ARRAY || isReifiable(t)) return;
   287         ArrayType from = (ArrayType)t;
   288         boolean shouldWarn = false;
   289         switch (s.tag) {
   290             case ARRAY:
   291                 ArrayType to = (ArrayType)s;
   292                 shouldWarn = from.isVarargs() &&
   293                         !to.isVarargs() &&
   294                         !isReifiable(from);
   295                 break;
   296             case CLASS:
   297                 shouldWarn = from.isVarargs() &&
   298                         isSubtype(from, s);
   299                 break;
   300         }
   301         if (shouldWarn) {
   302             warn.warn(LintCategory.VARARGS);
   303         }
   304     }
   306     /**
   307      * Is t a subtype of or convertiable via boxing/unboxing
   308      * convertions to s?
   309      */
   310     public boolean isConvertible(Type t, Type s) {
   311         return isConvertible(t, s, Warner.noWarnings);
   312     }
   313     // </editor-fold>
   315     // <editor-fold defaultstate="collapsed" desc="isSubtype">
   316     /**
   317      * Is t an unchecked subtype of s?
   318      */
   319     public boolean isSubtypeUnchecked(Type t, Type s) {
   320         return isSubtypeUnchecked(t, s, Warner.noWarnings);
   321     }
   322     /**
   323      * Is t an unchecked subtype of s?
   324      */
   325     public boolean isSubtypeUnchecked(Type t, Type s, Warner warn) {
   326         if (t.tag == ARRAY && s.tag == ARRAY) {
   327             if (((ArrayType)t).elemtype.tag <= lastBaseTag) {
   328                 return isSameType(elemtype(t), elemtype(s));
   329             } else {
   330                 ArrayType from = (ArrayType)t;
   331                 ArrayType to = (ArrayType)s;
   332                 if (from.isVarargs() &&
   333                         !to.isVarargs() &&
   334                         !isReifiable(from)) {
   335                     warn.warn(LintCategory.VARARGS);
   336                 }
   337                 return isSubtypeUnchecked(elemtype(t), elemtype(s), warn);
   338             }
   339         } else if (isSubtype(t, s)) {
   340             return true;
   341         }
   342         else if (t.tag == TYPEVAR) {
   343             return isSubtypeUnchecked(t.getUpperBound(), s, warn);
   344         }
   345         else if (s.tag == UNDETVAR) {
   346             UndetVar uv = (UndetVar)s;
   347             if (uv.inst != null)
   348                 return isSubtypeUnchecked(t, uv.inst, warn);
   349         }
   350         else if (!s.isRaw()) {
   351             Type t2 = asSuper(t, s.tsym);
   352             if (t2 != null && t2.isRaw()) {
   353                 if (isReifiable(s))
   354                     warn.silentWarn(LintCategory.UNCHECKED);
   355                 else
   356                     warn.warn(LintCategory.UNCHECKED);
   357                 return true;
   358             }
   359         }
   360         return false;
   361     }
   363     /**
   364      * Is t a subtype of s?<br>
   365      * (not defined for Method and ForAll types)
   366      */
   367     final public boolean isSubtype(Type t, Type s) {
   368         return isSubtype(t, s, true);
   369     }
   370     final public boolean isSubtypeNoCapture(Type t, Type s) {
   371         return isSubtype(t, s, false);
   372     }
   373     public boolean isSubtype(Type t, Type s, boolean capture) {
   374         if (t == s)
   375             return true;
   377         if (s.tag >= firstPartialTag)
   378             return isSuperType(s, t);
   380         if (s.isCompound()) {
   381             for (Type s2 : interfaces(s).prepend(supertype(s))) {
   382                 if (!isSubtype(t, s2, capture))
   383                     return false;
   384             }
   385             return true;
   386         }
   388         Type lower = lowerBound(s);
   389         if (s != lower)
   390             return isSubtype(capture ? capture(t) : t, lower, false);
   392         return isSubtype.visit(capture ? capture(t) : t, s);
   393     }
   394     // where
   395         private TypeRelation isSubtype = new TypeRelation()
   396         {
   397             public Boolean visitType(Type t, Type s) {
   398                 switch (t.tag) {
   399                 case BYTE: case CHAR:
   400                     return (t.tag == s.tag ||
   401                               t.tag + 2 <= s.tag && s.tag <= DOUBLE);
   402                 case SHORT: case INT: case LONG: case FLOAT: case DOUBLE:
   403                     return t.tag <= s.tag && s.tag <= DOUBLE;
   404                 case BOOLEAN: case VOID:
   405                     return t.tag == s.tag;
   406                 case TYPEVAR:
   407                     return isSubtypeNoCapture(t.getUpperBound(), s);
   408                 case BOT:
   409                     return
   410                         s.tag == BOT || s.tag == CLASS ||
   411                         s.tag == ARRAY || s.tag == TYPEVAR;
   412                 case NONE:
   413                     return false;
   414                 default:
   415                     throw new AssertionError("isSubtype " + t.tag);
   416                 }
   417             }
   419             private Set<TypePair> cache = new HashSet<TypePair>();
   421             private boolean containsTypeRecursive(Type t, Type s) {
   422                 TypePair pair = new TypePair(t, s);
   423                 if (cache.add(pair)) {
   424                     try {
   425                         return containsType(t.getTypeArguments(),
   426                                             s.getTypeArguments());
   427                     } finally {
   428                         cache.remove(pair);
   429                     }
   430                 } else {
   431                     return containsType(t.getTypeArguments(),
   432                                         rewriteSupers(s).getTypeArguments());
   433                 }
   434             }
   436             private Type rewriteSupers(Type t) {
   437                 if (!t.isParameterized())
   438                     return t;
   439                 ListBuffer<Type> from = lb();
   440                 ListBuffer<Type> to = lb();
   441                 adaptSelf(t, from, to);
   442                 if (from.isEmpty())
   443                     return t;
   444                 ListBuffer<Type> rewrite = lb();
   445                 boolean changed = false;
   446                 for (Type orig : to.toList()) {
   447                     Type s = rewriteSupers(orig);
   448                     if (s.isSuperBound() && !s.isExtendsBound()) {
   449                         s = new WildcardType(syms.objectType,
   450                                              BoundKind.UNBOUND,
   451                                              syms.boundClass);
   452                         changed = true;
   453                     } else if (s != orig) {
   454                         s = new WildcardType(upperBound(s),
   455                                              BoundKind.EXTENDS,
   456                                              syms.boundClass);
   457                         changed = true;
   458                     }
   459                     rewrite.append(s);
   460                 }
   461                 if (changed)
   462                     return subst(t.tsym.type, from.toList(), rewrite.toList());
   463                 else
   464                     return t;
   465             }
   467             @Override
   468             public Boolean visitClassType(ClassType t, Type s) {
   469                 Type sup = asSuper(t, s.tsym);
   470                 return sup != null
   471                     && sup.tsym == s.tsym
   472                     // You're not allowed to write
   473                     //     Vector<Object> vec = new Vector<String>();
   474                     // But with wildcards you can write
   475                     //     Vector<? extends Object> vec = new Vector<String>();
   476                     // which means that subtype checking must be done
   477                     // here instead of same-type checking (via containsType).
   478                     && (!s.isParameterized() || containsTypeRecursive(s, sup))
   479                     && isSubtypeNoCapture(sup.getEnclosingType(),
   480                                           s.getEnclosingType());
   481             }
   483             @Override
   484             public Boolean visitArrayType(ArrayType t, Type s) {
   485                 if (s.tag == ARRAY) {
   486                     if (t.elemtype.tag <= lastBaseTag)
   487                         return isSameType(t.elemtype, elemtype(s));
   488                     else
   489                         return isSubtypeNoCapture(t.elemtype, elemtype(s));
   490                 }
   492                 if (s.tag == CLASS) {
   493                     Name sname = s.tsym.getQualifiedName();
   494                     return sname == names.java_lang_Object
   495                         || sname == names.java_lang_Cloneable
   496                         || sname == names.java_io_Serializable;
   497                 }
   499                 return false;
   500             }
   502             @Override
   503             public Boolean visitUndetVar(UndetVar t, Type s) {
   504                 //todo: test against origin needed? or replace with substitution?
   505                 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN)
   506                     return true;
   508                 if (t.inst != null)
   509                     return isSubtypeNoCapture(t.inst, s); // TODO: ", warn"?
   511                 t.hibounds = t.hibounds.prepend(s);
   512                 return true;
   513             }
   515             @Override
   516             public Boolean visitErrorType(ErrorType t, Type s) {
   517                 return true;
   518             }
   519         };
   521     /**
   522      * Is t a subtype of every type in given list `ts'?<br>
   523      * (not defined for Method and ForAll types)<br>
   524      * Allows unchecked conversions.
   525      */
   526     public boolean isSubtypeUnchecked(Type t, List<Type> ts, Warner warn) {
   527         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
   528             if (!isSubtypeUnchecked(t, l.head, warn))
   529                 return false;
   530         return true;
   531     }
   533     /**
   534      * Are corresponding elements of ts subtypes of ss?  If lists are
   535      * of different length, return false.
   536      */
   537     public boolean isSubtypes(List<Type> ts, List<Type> ss) {
   538         while (ts.tail != null && ss.tail != null
   539                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   540                isSubtype(ts.head, ss.head)) {
   541             ts = ts.tail;
   542             ss = ss.tail;
   543         }
   544         return ts.tail == null && ss.tail == null;
   545         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   546     }
   548     /**
   549      * Are corresponding elements of ts subtypes of ss, allowing
   550      * unchecked conversions?  If lists are of different length,
   551      * return false.
   552      **/
   553     public boolean isSubtypesUnchecked(List<Type> ts, List<Type> ss, Warner warn) {
   554         while (ts.tail != null && ss.tail != null
   555                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   556                isSubtypeUnchecked(ts.head, ss.head, warn)) {
   557             ts = ts.tail;
   558             ss = ss.tail;
   559         }
   560         return ts.tail == null && ss.tail == null;
   561         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   562     }
   563     // </editor-fold>
   565     // <editor-fold defaultstate="collapsed" desc="isSuperType">
   566     /**
   567      * Is t a supertype of s?
   568      */
   569     public boolean isSuperType(Type t, Type s) {
   570         switch (t.tag) {
   571         case ERROR:
   572             return true;
   573         case UNDETVAR: {
   574             UndetVar undet = (UndetVar)t;
   575             if (t == s ||
   576                 undet.qtype == s ||
   577                 s.tag == ERROR ||
   578                 s.tag == BOT) return true;
   579             if (undet.inst != null)
   580                 return isSubtype(s, undet.inst);
   581             undet.lobounds = undet.lobounds.prepend(s);
   582             return true;
   583         }
   584         default:
   585             return isSubtype(s, t);
   586         }
   587     }
   588     // </editor-fold>
   590     // <editor-fold defaultstate="collapsed" desc="isSameType">
   591     /**
   592      * Are corresponding elements of the lists the same type?  If
   593      * lists are of different length, return false.
   594      */
   595     public boolean isSameTypes(List<Type> ts, List<Type> ss) {
   596         while (ts.tail != null && ss.tail != null
   597                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   598                isSameType(ts.head, ss.head)) {
   599             ts = ts.tail;
   600             ss = ss.tail;
   601         }
   602         return ts.tail == null && ss.tail == null;
   603         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   604     }
   606     /**
   607      * Is t the same type as s?
   608      */
   609     public boolean isSameType(Type t, Type s) {
   610         return isSameType.visit(t, s);
   611     }
   612     // where
   613         private TypeRelation isSameType = new TypeRelation() {
   615             public Boolean visitType(Type t, Type s) {
   616                 if (t == s)
   617                     return true;
   619                 if (s.tag >= firstPartialTag)
   620                     return visit(s, t);
   622                 switch (t.tag) {
   623                 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
   624                 case DOUBLE: case BOOLEAN: case VOID: case BOT: case NONE:
   625                     return t.tag == s.tag;
   626                 case TYPEVAR: {
   627                     if (s.tag == TYPEVAR) {
   628                         //type-substitution does not preserve type-var types
   629                         //check that type var symbols and bounds are indeed the same
   630                         return t.tsym == s.tsym &&
   631                                 visit(t.getUpperBound(), s.getUpperBound());
   632                     }
   633                     else {
   634                         //special case for s == ? super X, where upper(s) = u
   635                         //check that u == t, where u has been set by Type.withTypeVar
   636                         return s.isSuperBound() &&
   637                                 !s.isExtendsBound() &&
   638                                 visit(t, upperBound(s));
   639                     }
   640                 }
   641                 default:
   642                     throw new AssertionError("isSameType " + t.tag);
   643                 }
   644             }
   646             @Override
   647             public Boolean visitWildcardType(WildcardType t, Type s) {
   648                 if (s.tag >= firstPartialTag)
   649                     return visit(s, t);
   650                 else
   651                     return false;
   652             }
   654             @Override
   655             public Boolean visitClassType(ClassType t, Type s) {
   656                 if (t == s)
   657                     return true;
   659                 if (s.tag >= firstPartialTag)
   660                     return visit(s, t);
   662                 if (s.isSuperBound() && !s.isExtendsBound())
   663                     return visit(t, upperBound(s)) && visit(t, lowerBound(s));
   665                 if (t.isCompound() && s.isCompound()) {
   666                     if (!visit(supertype(t), supertype(s)))
   667                         return false;
   669                     HashSet<SingletonType> set = new HashSet<SingletonType>();
   670                     for (Type x : interfaces(t))
   671                         set.add(new SingletonType(x));
   672                     for (Type x : interfaces(s)) {
   673                         if (!set.remove(new SingletonType(x)))
   674                             return false;
   675                     }
   676                     return (set.isEmpty());
   677                 }
   678                 return t.tsym == s.tsym
   679                     && visit(t.getEnclosingType(), s.getEnclosingType())
   680                     && containsTypeEquivalent(t.getTypeArguments(), s.getTypeArguments());
   681             }
   683             @Override
   684             public Boolean visitArrayType(ArrayType t, Type s) {
   685                 if (t == s)
   686                     return true;
   688                 if (s.tag >= firstPartialTag)
   689                     return visit(s, t);
   691                 return s.tag == ARRAY
   692                     && containsTypeEquivalent(t.elemtype, elemtype(s));
   693             }
   695             @Override
   696             public Boolean visitMethodType(MethodType t, Type s) {
   697                 // isSameType for methods does not take thrown
   698                 // exceptions into account!
   699                 return hasSameArgs(t, s) && visit(t.getReturnType(), s.getReturnType());
   700             }
   702             @Override
   703             public Boolean visitPackageType(PackageType t, Type s) {
   704                 return t == s;
   705             }
   707             @Override
   708             public Boolean visitForAll(ForAll t, Type s) {
   709                 if (s.tag != FORALL)
   710                     return false;
   712                 ForAll forAll = (ForAll)s;
   713                 return hasSameBounds(t, forAll)
   714                     && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
   715             }
   717             @Override
   718             public Boolean visitUndetVar(UndetVar t, Type s) {
   719                 if (s.tag == WILDCARD)
   720                     // FIXME, this might be leftovers from before capture conversion
   721                     return false;
   723                 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN)
   724                     return true;
   726                 if (t.inst != null)
   727                     return visit(t.inst, s);
   729                 t.inst = fromUnknownFun.apply(s);
   730                 for (List<Type> l = t.lobounds; l.nonEmpty(); l = l.tail) {
   731                     if (!isSubtype(l.head, t.inst))
   732                         return false;
   733                 }
   734                 for (List<Type> l = t.hibounds; l.nonEmpty(); l = l.tail) {
   735                     if (!isSubtype(t.inst, l.head))
   736                         return false;
   737                 }
   738                 return true;
   739             }
   741             @Override
   742             public Boolean visitErrorType(ErrorType t, Type s) {
   743                 return true;
   744             }
   745         };
   746     // </editor-fold>
   748     // <editor-fold defaultstate="collapsed" desc="fromUnknownFun">
   749     /**
   750      * A mapping that turns all unknown types in this type to fresh
   751      * unknown variables.
   752      */
   753     public Mapping fromUnknownFun = new Mapping("fromUnknownFun") {
   754             public Type apply(Type t) {
   755                 if (t.tag == UNKNOWN) return new UndetVar(t);
   756                 else return t.map(this);
   757             }
   758         };
   759     // </editor-fold>
   761     // <editor-fold defaultstate="collapsed" desc="Contains Type">
   762     public boolean containedBy(Type t, Type s) {
   763         switch (t.tag) {
   764         case UNDETVAR:
   765             if (s.tag == WILDCARD) {
   766                 UndetVar undetvar = (UndetVar)t;
   767                 WildcardType wt = (WildcardType)s;
   768                 switch(wt.kind) {
   769                     case UNBOUND: //similar to ? extends Object
   770                     case EXTENDS: {
   771                         Type bound = upperBound(s);
   772                         // We should check the new upper bound against any of the
   773                         // undetvar's lower bounds.
   774                         for (Type t2 : undetvar.lobounds) {
   775                             if (!isSubtype(t2, bound))
   776                                 return false;
   777                         }
   778                         undetvar.hibounds = undetvar.hibounds.prepend(bound);
   779                         break;
   780                     }
   781                     case SUPER: {
   782                         Type bound = lowerBound(s);
   783                         // We should check the new lower bound against any of the
   784                         // undetvar's lower bounds.
   785                         for (Type t2 : undetvar.hibounds) {
   786                             if (!isSubtype(bound, t2))
   787                                 return false;
   788                         }
   789                         undetvar.lobounds = undetvar.lobounds.prepend(bound);
   790                         break;
   791                     }
   792                 }
   793                 return true;
   794             } else {
   795                 return isSameType(t, s);
   796             }
   797         case ERROR:
   798             return true;
   799         default:
   800             return containsType(s, t);
   801         }
   802     }
   804     boolean containsType(List<Type> ts, List<Type> ss) {
   805         while (ts.nonEmpty() && ss.nonEmpty()
   806                && containsType(ts.head, ss.head)) {
   807             ts = ts.tail;
   808             ss = ss.tail;
   809         }
   810         return ts.isEmpty() && ss.isEmpty();
   811     }
   813     /**
   814      * Check if t contains s.
   815      *
   816      * <p>T contains S if:
   817      *
   818      * <p>{@code L(T) <: L(S) && U(S) <: U(T)}
   819      *
   820      * <p>This relation is only used by ClassType.isSubtype(), that
   821      * is,
   822      *
   823      * <p>{@code C<S> <: C<T> if T contains S.}
   824      *
   825      * <p>Because of F-bounds, this relation can lead to infinite
   826      * recursion.  Thus we must somehow break that recursion.  Notice
   827      * that containsType() is only called from ClassType.isSubtype().
   828      * Since the arguments have already been checked against their
   829      * bounds, we know:
   830      *
   831      * <p>{@code U(S) <: U(T) if T is "super" bound (U(T) *is* the bound)}
   832      *
   833      * <p>{@code L(T) <: L(S) if T is "extends" bound (L(T) is bottom)}
   834      *
   835      * @param t a type
   836      * @param s a type
   837      */
   838     public boolean containsType(Type t, Type s) {
   839         return containsType.visit(t, s);
   840     }
   841     // where
   842         private TypeRelation containsType = new TypeRelation() {
   844             private Type U(Type t) {
   845                 while (t.tag == WILDCARD) {
   846                     WildcardType w = (WildcardType)t;
   847                     if (w.isSuperBound())
   848                         return w.bound == null ? syms.objectType : w.bound.bound;
   849                     else
   850                         t = w.type;
   851                 }
   852                 return t;
   853             }
   855             private Type L(Type t) {
   856                 while (t.tag == WILDCARD) {
   857                     WildcardType w = (WildcardType)t;
   858                     if (w.isExtendsBound())
   859                         return syms.botType;
   860                     else
   861                         t = w.type;
   862                 }
   863                 return t;
   864             }
   866             public Boolean visitType(Type t, Type s) {
   867                 if (s.tag >= firstPartialTag)
   868                     return containedBy(s, t);
   869                 else
   870                     return isSameType(t, s);
   871             }
   873 //            void debugContainsType(WildcardType t, Type s) {
   874 //                System.err.println();
   875 //                System.err.format(" does %s contain %s?%n", t, s);
   876 //                System.err.format(" %s U(%s) <: U(%s) %s = %s%n",
   877 //                                  upperBound(s), s, t, U(t),
   878 //                                  t.isSuperBound()
   879 //                                  || isSubtypeNoCapture(upperBound(s), U(t)));
   880 //                System.err.format(" %s L(%s) <: L(%s) %s = %s%n",
   881 //                                  L(t), t, s, lowerBound(s),
   882 //                                  t.isExtendsBound()
   883 //                                  || isSubtypeNoCapture(L(t), lowerBound(s)));
   884 //                System.err.println();
   885 //            }
   887             @Override
   888             public Boolean visitWildcardType(WildcardType t, Type s) {
   889                 if (s.tag >= firstPartialTag)
   890                     return containedBy(s, t);
   891                 else {
   892 //                    debugContainsType(t, s);
   893                     return isSameWildcard(t, s)
   894                         || isCaptureOf(s, t)
   895                         || ((t.isExtendsBound() || isSubtypeNoCapture(L(t), lowerBound(s))) &&
   896                             (t.isSuperBound() || isSubtypeNoCapture(upperBound(s), U(t))));
   897                 }
   898             }
   900             @Override
   901             public Boolean visitUndetVar(UndetVar t, Type s) {
   902                 if (s.tag != WILDCARD)
   903                     return isSameType(t, s);
   904                 else
   905                     return false;
   906             }
   908             @Override
   909             public Boolean visitErrorType(ErrorType t, Type s) {
   910                 return true;
   911             }
   912         };
   914     public boolean isCaptureOf(Type s, WildcardType t) {
   915         if (s.tag != TYPEVAR || !((TypeVar)s).isCaptured())
   916             return false;
   917         return isSameWildcard(t, ((CapturedType)s).wildcard);
   918     }
   920     public boolean isSameWildcard(WildcardType t, Type s) {
   921         if (s.tag != WILDCARD)
   922             return false;
   923         WildcardType w = (WildcardType)s;
   924         return w.kind == t.kind && w.type == t.type;
   925     }
   927     public boolean containsTypeEquivalent(List<Type> ts, List<Type> ss) {
   928         while (ts.nonEmpty() && ss.nonEmpty()
   929                && containsTypeEquivalent(ts.head, ss.head)) {
   930             ts = ts.tail;
   931             ss = ss.tail;
   932         }
   933         return ts.isEmpty() && ss.isEmpty();
   934     }
   935     // </editor-fold>
   937     // <editor-fold defaultstate="collapsed" desc="isCastable">
   938     public boolean isCastable(Type t, Type s) {
   939         return isCastable(t, s, Warner.noWarnings);
   940     }
   942     /**
   943      * Is t is castable to s?<br>
   944      * s is assumed to be an erased type.<br>
   945      * (not defined for Method and ForAll types).
   946      */
   947     public boolean isCastable(Type t, Type s, Warner warn) {
   948         if (t == s)
   949             return true;
   951         if (t.isPrimitive() != s.isPrimitive())
   952             return allowBoxing && (isConvertible(t, s, warn) || isConvertible(s, t, warn));
   954         if (warn != warnStack.head) {
   955             try {
   956                 warnStack = warnStack.prepend(warn);
   957                 checkUnsafeVarargsConversion(t, s, warn);
   958                 return isCastable.visit(t,s);
   959             } finally {
   960                 warnStack = warnStack.tail;
   961             }
   962         } else {
   963             return isCastable.visit(t,s);
   964         }
   965     }
   966     // where
   967         private TypeRelation isCastable = new TypeRelation() {
   969             public Boolean visitType(Type t, Type s) {
   970                 if (s.tag == ERROR)
   971                     return true;
   973                 switch (t.tag) {
   974                 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
   975                 case DOUBLE:
   976                     return s.tag <= DOUBLE;
   977                 case BOOLEAN:
   978                     return s.tag == BOOLEAN;
   979                 case VOID:
   980                     return false;
   981                 case BOT:
   982                     return isSubtype(t, s);
   983                 default:
   984                     throw new AssertionError();
   985                 }
   986             }
   988             @Override
   989             public Boolean visitWildcardType(WildcardType t, Type s) {
   990                 return isCastable(upperBound(t), s, warnStack.head);
   991             }
   993             @Override
   994             public Boolean visitClassType(ClassType t, Type s) {
   995                 if (s.tag == ERROR || s.tag == BOT)
   996                     return true;
   998                 if (s.tag == TYPEVAR) {
   999                     if (isCastable(t, s.getUpperBound(), Warner.noWarnings)) {
  1000                         warnStack.head.warn(LintCategory.UNCHECKED);
  1001                         return true;
  1002                     } else {
  1003                         return false;
  1007                 if (t.isCompound()) {
  1008                     Warner oldWarner = warnStack.head;
  1009                     warnStack.head = Warner.noWarnings;
  1010                     if (!visit(supertype(t), s))
  1011                         return false;
  1012                     for (Type intf : interfaces(t)) {
  1013                         if (!visit(intf, s))
  1014                             return false;
  1016                     if (warnStack.head.hasLint(LintCategory.UNCHECKED))
  1017                         oldWarner.warn(LintCategory.UNCHECKED);
  1018                     return true;
  1021                 if (s.isCompound()) {
  1022                     // call recursively to reuse the above code
  1023                     return visitClassType((ClassType)s, t);
  1026                 if (s.tag == CLASS || s.tag == ARRAY) {
  1027                     boolean upcast;
  1028                     if ((upcast = isSubtype(erasure(t), erasure(s)))
  1029                         || isSubtype(erasure(s), erasure(t))) {
  1030                         if (!upcast && s.tag == ARRAY) {
  1031                             if (!isReifiable(s))
  1032                                 warnStack.head.warn(LintCategory.UNCHECKED);
  1033                             return true;
  1034                         } else if (s.isRaw()) {
  1035                             return true;
  1036                         } else if (t.isRaw()) {
  1037                             if (!isUnbounded(s))
  1038                                 warnStack.head.warn(LintCategory.UNCHECKED);
  1039                             return true;
  1041                         // Assume |a| <: |b|
  1042                         final Type a = upcast ? t : s;
  1043                         final Type b = upcast ? s : t;
  1044                         final boolean HIGH = true;
  1045                         final boolean LOW = false;
  1046                         final boolean DONT_REWRITE_TYPEVARS = false;
  1047                         Type aHigh = rewriteQuantifiers(a, HIGH, DONT_REWRITE_TYPEVARS);
  1048                         Type aLow  = rewriteQuantifiers(a, LOW,  DONT_REWRITE_TYPEVARS);
  1049                         Type bHigh = rewriteQuantifiers(b, HIGH, DONT_REWRITE_TYPEVARS);
  1050                         Type bLow  = rewriteQuantifiers(b, LOW,  DONT_REWRITE_TYPEVARS);
  1051                         Type lowSub = asSub(bLow, aLow.tsym);
  1052                         Type highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
  1053                         if (highSub == null) {
  1054                             final boolean REWRITE_TYPEVARS = true;
  1055                             aHigh = rewriteQuantifiers(a, HIGH, REWRITE_TYPEVARS);
  1056                             aLow  = rewriteQuantifiers(a, LOW,  REWRITE_TYPEVARS);
  1057                             bHigh = rewriteQuantifiers(b, HIGH, REWRITE_TYPEVARS);
  1058                             bLow  = rewriteQuantifiers(b, LOW,  REWRITE_TYPEVARS);
  1059                             lowSub = asSub(bLow, aLow.tsym);
  1060                             highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
  1062                         if (highSub != null) {
  1063                             if (!(a.tsym == highSub.tsym && a.tsym == lowSub.tsym)) {
  1064                                 Assert.error(a.tsym + " != " + highSub.tsym + " != " + lowSub.tsym);
  1066                             if (!disjointTypes(aHigh.allparams(), highSub.allparams())
  1067                                 && !disjointTypes(aHigh.allparams(), lowSub.allparams())
  1068                                 && !disjointTypes(aLow.allparams(), highSub.allparams())
  1069                                 && !disjointTypes(aLow.allparams(), lowSub.allparams())) {
  1070                                 if (upcast ? giveWarning(a, b) :
  1071                                     giveWarning(b, a))
  1072                                     warnStack.head.warn(LintCategory.UNCHECKED);
  1073                                 return true;
  1076                         if (isReifiable(s))
  1077                             return isSubtypeUnchecked(a, b);
  1078                         else
  1079                             return isSubtypeUnchecked(a, b, warnStack.head);
  1082                     // Sidecast
  1083                     if (s.tag == CLASS) {
  1084                         if ((s.tsym.flags() & INTERFACE) != 0) {
  1085                             return ((t.tsym.flags() & FINAL) == 0)
  1086                                 ? sideCast(t, s, warnStack.head)
  1087                                 : sideCastFinal(t, s, warnStack.head);
  1088                         } else if ((t.tsym.flags() & INTERFACE) != 0) {
  1089                             return ((s.tsym.flags() & FINAL) == 0)
  1090                                 ? sideCast(t, s, warnStack.head)
  1091                                 : sideCastFinal(t, s, warnStack.head);
  1092                         } else {
  1093                             // unrelated class types
  1094                             return false;
  1098                 return false;
  1101             @Override
  1102             public Boolean visitArrayType(ArrayType t, Type s) {
  1103                 switch (s.tag) {
  1104                 case ERROR:
  1105                 case BOT:
  1106                     return true;
  1107                 case TYPEVAR:
  1108                     if (isCastable(s, t, Warner.noWarnings)) {
  1109                         warnStack.head.warn(LintCategory.UNCHECKED);
  1110                         return true;
  1111                     } else {
  1112                         return false;
  1114                 case CLASS:
  1115                     return isSubtype(t, s);
  1116                 case ARRAY:
  1117                     if (elemtype(t).tag <= lastBaseTag ||
  1118                             elemtype(s).tag <= lastBaseTag) {
  1119                         return elemtype(t).tag == elemtype(s).tag;
  1120                     } else {
  1121                         return visit(elemtype(t), elemtype(s));
  1123                 default:
  1124                     return false;
  1128             @Override
  1129             public Boolean visitTypeVar(TypeVar t, Type s) {
  1130                 switch (s.tag) {
  1131                 case ERROR:
  1132                 case BOT:
  1133                     return true;
  1134                 case TYPEVAR:
  1135                     if (isSubtype(t, s)) {
  1136                         return true;
  1137                     } else if (isCastable(t.bound, s, Warner.noWarnings)) {
  1138                         warnStack.head.warn(LintCategory.UNCHECKED);
  1139                         return true;
  1140                     } else {
  1141                         return false;
  1143                 default:
  1144                     return isCastable(t.bound, s, warnStack.head);
  1148             @Override
  1149             public Boolean visitErrorType(ErrorType t, Type s) {
  1150                 return true;
  1152         };
  1153     // </editor-fold>
  1155     // <editor-fold defaultstate="collapsed" desc="disjointTypes">
  1156     public boolean disjointTypes(List<Type> ts, List<Type> ss) {
  1157         while (ts.tail != null && ss.tail != null) {
  1158             if (disjointType(ts.head, ss.head)) return true;
  1159             ts = ts.tail;
  1160             ss = ss.tail;
  1162         return false;
  1165     /**
  1166      * Two types or wildcards are considered disjoint if it can be
  1167      * proven that no type can be contained in both. It is
  1168      * conservative in that it is allowed to say that two types are
  1169      * not disjoint, even though they actually are.
  1171      * The type C<X> is castable to C<Y> exactly if X and Y are not
  1172      * disjoint.
  1173      */
  1174     public boolean disjointType(Type t, Type s) {
  1175         return disjointType.visit(t, s);
  1177     // where
  1178         private TypeRelation disjointType = new TypeRelation() {
  1180             private Set<TypePair> cache = new HashSet<TypePair>();
  1182             public Boolean visitType(Type t, Type s) {
  1183                 if (s.tag == WILDCARD)
  1184                     return visit(s, t);
  1185                 else
  1186                     return notSoftSubtypeRecursive(t, s) || notSoftSubtypeRecursive(s, t);
  1189             private boolean isCastableRecursive(Type t, Type s) {
  1190                 TypePair pair = new TypePair(t, s);
  1191                 if (cache.add(pair)) {
  1192                     try {
  1193                         return Types.this.isCastable(t, s);
  1194                     } finally {
  1195                         cache.remove(pair);
  1197                 } else {
  1198                     return true;
  1202             private boolean notSoftSubtypeRecursive(Type t, Type s) {
  1203                 TypePair pair = new TypePair(t, s);
  1204                 if (cache.add(pair)) {
  1205                     try {
  1206                         return Types.this.notSoftSubtype(t, s);
  1207                     } finally {
  1208                         cache.remove(pair);
  1210                 } else {
  1211                     return false;
  1215             @Override
  1216             public Boolean visitWildcardType(WildcardType t, Type s) {
  1217                 if (t.isUnbound())
  1218                     return false;
  1220                 if (s.tag != WILDCARD) {
  1221                     if (t.isExtendsBound())
  1222                         return notSoftSubtypeRecursive(s, t.type);
  1223                     else // isSuperBound()
  1224                         return notSoftSubtypeRecursive(t.type, s);
  1227                 if (s.isUnbound())
  1228                     return false;
  1230                 if (t.isExtendsBound()) {
  1231                     if (s.isExtendsBound())
  1232                         return !isCastableRecursive(t.type, upperBound(s));
  1233                     else if (s.isSuperBound())
  1234                         return notSoftSubtypeRecursive(lowerBound(s), t.type);
  1235                 } else if (t.isSuperBound()) {
  1236                     if (s.isExtendsBound())
  1237                         return notSoftSubtypeRecursive(t.type, upperBound(s));
  1239                 return false;
  1241         };
  1242     // </editor-fold>
  1244     // <editor-fold defaultstate="collapsed" desc="lowerBoundArgtypes">
  1245     /**
  1246      * Returns the lower bounds of the formals of a method.
  1247      */
  1248     public List<Type> lowerBoundArgtypes(Type t) {
  1249         return map(t.getParameterTypes(), lowerBoundMapping);
  1251     private final Mapping lowerBoundMapping = new Mapping("lowerBound") {
  1252             public Type apply(Type t) {
  1253                 return lowerBound(t);
  1255         };
  1256     // </editor-fold>
  1258     // <editor-fold defaultstate="collapsed" desc="notSoftSubtype">
  1259     /**
  1260      * This relation answers the question: is impossible that
  1261      * something of type `t' can be a subtype of `s'? This is
  1262      * different from the question "is `t' not a subtype of `s'?"
  1263      * when type variables are involved: Integer is not a subtype of T
  1264      * where <T extends Number> but it is not true that Integer cannot
  1265      * possibly be a subtype of T.
  1266      */
  1267     public boolean notSoftSubtype(Type t, Type s) {
  1268         if (t == s) return false;
  1269         if (t.tag == TYPEVAR) {
  1270             TypeVar tv = (TypeVar) t;
  1271             return !isCastable(tv.bound,
  1272                                relaxBound(s),
  1273                                Warner.noWarnings);
  1275         if (s.tag != WILDCARD)
  1276             s = upperBound(s);
  1278         return !isSubtype(t, relaxBound(s));
  1281     private Type relaxBound(Type t) {
  1282         if (t.tag == TYPEVAR) {
  1283             while (t.tag == TYPEVAR)
  1284                 t = t.getUpperBound();
  1285             t = rewriteQuantifiers(t, true, true);
  1287         return t;
  1289     // </editor-fold>
  1291     // <editor-fold defaultstate="collapsed" desc="isReifiable">
  1292     public boolean isReifiable(Type t) {
  1293         return isReifiable.visit(t);
  1295     // where
  1296         private UnaryVisitor<Boolean> isReifiable = new UnaryVisitor<Boolean>() {
  1298             public Boolean visitType(Type t, Void ignored) {
  1299                 return true;
  1302             @Override
  1303             public Boolean visitClassType(ClassType t, Void ignored) {
  1304                 if (t.isCompound())
  1305                     return false;
  1306                 else {
  1307                     if (!t.isParameterized())
  1308                         return true;
  1310                     for (Type param : t.allparams()) {
  1311                         if (!param.isUnbound())
  1312                             return false;
  1314                     return true;
  1318             @Override
  1319             public Boolean visitArrayType(ArrayType t, Void ignored) {
  1320                 return visit(t.elemtype);
  1323             @Override
  1324             public Boolean visitTypeVar(TypeVar t, Void ignored) {
  1325                 return false;
  1327         };
  1328     // </editor-fold>
  1330     // <editor-fold defaultstate="collapsed" desc="Array Utils">
  1331     public boolean isArray(Type t) {
  1332         while (t.tag == WILDCARD)
  1333             t = upperBound(t);
  1334         return t.tag == ARRAY;
  1337     /**
  1338      * The element type of an array.
  1339      */
  1340     public Type elemtype(Type t) {
  1341         switch (t.tag) {
  1342         case WILDCARD:
  1343             return elemtype(upperBound(t));
  1344         case ARRAY:
  1345             return ((ArrayType)t).elemtype;
  1346         case FORALL:
  1347             return elemtype(((ForAll)t).qtype);
  1348         case ERROR:
  1349             return t;
  1350         default:
  1351             return null;
  1355     public Type elemtypeOrType(Type t) {
  1356         Type elemtype = elemtype(t);
  1357         return elemtype != null ?
  1358             elemtype :
  1359             t;
  1362     /**
  1363      * Mapping to take element type of an arraytype
  1364      */
  1365     private Mapping elemTypeFun = new Mapping ("elemTypeFun") {
  1366         public Type apply(Type t) { return elemtype(t); }
  1367     };
  1369     /**
  1370      * The number of dimensions of an array type.
  1371      */
  1372     public int dimensions(Type t) {
  1373         int result = 0;
  1374         while (t.tag == ARRAY) {
  1375             result++;
  1376             t = elemtype(t);
  1378         return result;
  1380     // </editor-fold>
  1382     // <editor-fold defaultstate="collapsed" desc="asSuper">
  1383     /**
  1384      * Return the (most specific) base type of t that starts with the
  1385      * given symbol.  If none exists, return null.
  1387      * @param t a type
  1388      * @param sym a symbol
  1389      */
  1390     public Type asSuper(Type t, Symbol sym) {
  1391         return asSuper.visit(t, sym);
  1393     // where
  1394         private SimpleVisitor<Type,Symbol> asSuper = new SimpleVisitor<Type,Symbol>() {
  1396             public Type visitType(Type t, Symbol sym) {
  1397                 return null;
  1400             @Override
  1401             public Type visitClassType(ClassType t, Symbol sym) {
  1402                 if (t.tsym == sym)
  1403                     return t;
  1405                 Type st = supertype(t);
  1406                 if (st.tag == CLASS || st.tag == TYPEVAR || st.tag == ERROR) {
  1407                     Type x = asSuper(st, sym);
  1408                     if (x != null)
  1409                         return x;
  1411                 if ((sym.flags() & INTERFACE) != 0) {
  1412                     for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
  1413                         Type x = asSuper(l.head, sym);
  1414                         if (x != null)
  1415                             return x;
  1418                 return null;
  1421             @Override
  1422             public Type visitArrayType(ArrayType t, Symbol sym) {
  1423                 return isSubtype(t, sym.type) ? sym.type : null;
  1426             @Override
  1427             public Type visitTypeVar(TypeVar t, Symbol sym) {
  1428                 if (t.tsym == sym)
  1429                     return t;
  1430                 else
  1431                     return asSuper(t.bound, sym);
  1434             @Override
  1435             public Type visitErrorType(ErrorType t, Symbol sym) {
  1436                 return t;
  1438         };
  1440     /**
  1441      * Return the base type of t or any of its outer types that starts
  1442      * with the given symbol.  If none exists, return null.
  1444      * @param t a type
  1445      * @param sym a symbol
  1446      */
  1447     public Type asOuterSuper(Type t, Symbol sym) {
  1448         switch (t.tag) {
  1449         case CLASS:
  1450             do {
  1451                 Type s = asSuper(t, sym);
  1452                 if (s != null) return s;
  1453                 t = t.getEnclosingType();
  1454             } while (t.tag == CLASS);
  1455             return null;
  1456         case ARRAY:
  1457             return isSubtype(t, sym.type) ? sym.type : null;
  1458         case TYPEVAR:
  1459             return asSuper(t, sym);
  1460         case ERROR:
  1461             return t;
  1462         default:
  1463             return null;
  1467     /**
  1468      * Return the base type of t or any of its enclosing types that
  1469      * starts with the given symbol.  If none exists, return null.
  1471      * @param t a type
  1472      * @param sym a symbol
  1473      */
  1474     public Type asEnclosingSuper(Type t, Symbol sym) {
  1475         switch (t.tag) {
  1476         case CLASS:
  1477             do {
  1478                 Type s = asSuper(t, sym);
  1479                 if (s != null) return s;
  1480                 Type outer = t.getEnclosingType();
  1481                 t = (outer.tag == CLASS) ? outer :
  1482                     (t.tsym.owner.enclClass() != null) ? t.tsym.owner.enclClass().type :
  1483                     Type.noType;
  1484             } while (t.tag == CLASS);
  1485             return null;
  1486         case ARRAY:
  1487             return isSubtype(t, sym.type) ? sym.type : null;
  1488         case TYPEVAR:
  1489             return asSuper(t, sym);
  1490         case ERROR:
  1491             return t;
  1492         default:
  1493             return null;
  1496     // </editor-fold>
  1498     // <editor-fold defaultstate="collapsed" desc="memberType">
  1499     /**
  1500      * The type of given symbol, seen as a member of t.
  1502      * @param t a type
  1503      * @param sym a symbol
  1504      */
  1505     public Type memberType(Type t, Symbol sym) {
  1506         return (sym.flags() & STATIC) != 0
  1507             ? sym.type
  1508             : memberType.visit(t, sym);
  1510     // where
  1511         private SimpleVisitor<Type,Symbol> memberType = new SimpleVisitor<Type,Symbol>() {
  1513             public Type visitType(Type t, Symbol sym) {
  1514                 return sym.type;
  1517             @Override
  1518             public Type visitWildcardType(WildcardType t, Symbol sym) {
  1519                 return memberType(upperBound(t), sym);
  1522             @Override
  1523             public Type visitClassType(ClassType t, Symbol sym) {
  1524                 Symbol owner = sym.owner;
  1525                 long flags = sym.flags();
  1526                 if (((flags & STATIC) == 0) && owner.type.isParameterized()) {
  1527                     Type base = asOuterSuper(t, owner);
  1528                     //if t is an intersection type T = CT & I1 & I2 ... & In
  1529                     //its supertypes CT, I1, ... In might contain wildcards
  1530                     //so we need to go through capture conversion
  1531                     base = t.isCompound() ? capture(base) : base;
  1532                     if (base != null) {
  1533                         List<Type> ownerParams = owner.type.allparams();
  1534                         List<Type> baseParams = base.allparams();
  1535                         if (ownerParams.nonEmpty()) {
  1536                             if (baseParams.isEmpty()) {
  1537                                 // then base is a raw type
  1538                                 return erasure(sym.type);
  1539                             } else {
  1540                                 return subst(sym.type, ownerParams, baseParams);
  1545                 return sym.type;
  1548             @Override
  1549             public Type visitTypeVar(TypeVar t, Symbol sym) {
  1550                 return memberType(t.bound, sym);
  1553             @Override
  1554             public Type visitErrorType(ErrorType t, Symbol sym) {
  1555                 return t;
  1557         };
  1558     // </editor-fold>
  1560     // <editor-fold defaultstate="collapsed" desc="isAssignable">
  1561     public boolean isAssignable(Type t, Type s) {
  1562         return isAssignable(t, s, Warner.noWarnings);
  1565     /**
  1566      * Is t assignable to s?<br>
  1567      * Equivalent to subtype except for constant values and raw
  1568      * types.<br>
  1569      * (not defined for Method and ForAll types)
  1570      */
  1571     public boolean isAssignable(Type t, Type s, Warner warn) {
  1572         if (t.tag == ERROR)
  1573             return true;
  1574         if (t.tag <= INT && t.constValue() != null) {
  1575             int value = ((Number)t.constValue()).intValue();
  1576             switch (s.tag) {
  1577             case BYTE:
  1578                 if (Byte.MIN_VALUE <= value && value <= Byte.MAX_VALUE)
  1579                     return true;
  1580                 break;
  1581             case CHAR:
  1582                 if (Character.MIN_VALUE <= value && value <= Character.MAX_VALUE)
  1583                     return true;
  1584                 break;
  1585             case SHORT:
  1586                 if (Short.MIN_VALUE <= value && value <= Short.MAX_VALUE)
  1587                     return true;
  1588                 break;
  1589             case INT:
  1590                 return true;
  1591             case CLASS:
  1592                 switch (unboxedType(s).tag) {
  1593                 case BYTE:
  1594                 case CHAR:
  1595                 case SHORT:
  1596                     return isAssignable(t, unboxedType(s), warn);
  1598                 break;
  1601         return isConvertible(t, s, warn);
  1603     // </editor-fold>
  1605     // <editor-fold defaultstate="collapsed" desc="erasure">
  1606     /**
  1607      * The erasure of t {@code |t|} -- the type that results when all
  1608      * type parameters in t are deleted.
  1609      */
  1610     public Type erasure(Type t) {
  1611         return erasure(t, false);
  1613     //where
  1614     private Type erasure(Type t, boolean recurse) {
  1615         if (t.tag <= lastBaseTag)
  1616             return t; /* fast special case */
  1617         else
  1618             return erasure.visit(t, recurse);
  1620     // where
  1621         private SimpleVisitor<Type, Boolean> erasure = new SimpleVisitor<Type, Boolean>() {
  1622             public Type visitType(Type t, Boolean recurse) {
  1623                 if (t.tag <= lastBaseTag)
  1624                     return t; /*fast special case*/
  1625                 else
  1626                     return t.map(recurse ? erasureRecFun : erasureFun);
  1629             @Override
  1630             public Type visitWildcardType(WildcardType t, Boolean recurse) {
  1631                 return erasure(upperBound(t), recurse);
  1634             @Override
  1635             public Type visitClassType(ClassType t, Boolean recurse) {
  1636                 Type erased = t.tsym.erasure(Types.this);
  1637                 if (recurse) {
  1638                     erased = new ErasedClassType(erased.getEnclosingType(),erased.tsym);
  1640                 return erased;
  1643             @Override
  1644             public Type visitTypeVar(TypeVar t, Boolean recurse) {
  1645                 return erasure(t.bound, recurse);
  1648             @Override
  1649             public Type visitErrorType(ErrorType t, Boolean recurse) {
  1650                 return t;
  1652         };
  1654     private Mapping erasureFun = new Mapping ("erasure") {
  1655             public Type apply(Type t) { return erasure(t); }
  1656         };
  1658     private Mapping erasureRecFun = new Mapping ("erasureRecursive") {
  1659         public Type apply(Type t) { return erasureRecursive(t); }
  1660     };
  1662     public List<Type> erasure(List<Type> ts) {
  1663         return Type.map(ts, erasureFun);
  1666     public Type erasureRecursive(Type t) {
  1667         return erasure(t, true);
  1670     public List<Type> erasureRecursive(List<Type> ts) {
  1671         return Type.map(ts, erasureRecFun);
  1673     // </editor-fold>
  1675     // <editor-fold defaultstate="collapsed" desc="makeCompoundType">
  1676     /**
  1677      * Make a compound type from non-empty list of types
  1679      * @param bounds            the types from which the compound type is formed
  1680      * @param supertype         is objectType if all bounds are interfaces,
  1681      *                          null otherwise.
  1682      */
  1683     public Type makeCompoundType(List<Type> bounds,
  1684                                  Type supertype) {
  1685         ClassSymbol bc =
  1686             new ClassSymbol(ABSTRACT|PUBLIC|SYNTHETIC|COMPOUND|ACYCLIC,
  1687                             Type.moreInfo
  1688                                 ? names.fromString(bounds.toString())
  1689                                 : names.empty,
  1690                             syms.noSymbol);
  1691         if (bounds.head.tag == TYPEVAR)
  1692             // error condition, recover
  1693                 bc.erasure_field = syms.objectType;
  1694             else
  1695                 bc.erasure_field = erasure(bounds.head);
  1696             bc.members_field = new Scope(bc);
  1697         ClassType bt = (ClassType)bc.type;
  1698         bt.allparams_field = List.nil();
  1699         if (supertype != null) {
  1700             bt.supertype_field = supertype;
  1701             bt.interfaces_field = bounds;
  1702         } else {
  1703             bt.supertype_field = bounds.head;
  1704             bt.interfaces_field = bounds.tail;
  1706         Assert.check(bt.supertype_field.tsym.completer != null
  1707                 || !bt.supertype_field.isInterface(),
  1708             bt.supertype_field);
  1709         return bt;
  1712     /**
  1713      * Same as {@link #makeCompoundType(List,Type)}, except that the
  1714      * second parameter is computed directly. Note that this might
  1715      * cause a symbol completion.  Hence, this version of
  1716      * makeCompoundType may not be called during a classfile read.
  1717      */
  1718     public Type makeCompoundType(List<Type> bounds) {
  1719         Type supertype = (bounds.head.tsym.flags() & INTERFACE) != 0 ?
  1720             supertype(bounds.head) : null;
  1721         return makeCompoundType(bounds, supertype);
  1724     /**
  1725      * A convenience wrapper for {@link #makeCompoundType(List)}; the
  1726      * arguments are converted to a list and passed to the other
  1727      * method.  Note that this might cause a symbol completion.
  1728      * Hence, this version of makeCompoundType may not be called
  1729      * during a classfile read.
  1730      */
  1731     public Type makeCompoundType(Type bound1, Type bound2) {
  1732         return makeCompoundType(List.of(bound1, bound2));
  1734     // </editor-fold>
  1736     // <editor-fold defaultstate="collapsed" desc="supertype">
  1737     public Type supertype(Type t) {
  1738         return supertype.visit(t);
  1740     // where
  1741         private UnaryVisitor<Type> supertype = new UnaryVisitor<Type>() {
  1743             public Type visitType(Type t, Void ignored) {
  1744                 // A note on wildcards: there is no good way to
  1745                 // determine a supertype for a super bounded wildcard.
  1746                 return null;
  1749             @Override
  1750             public Type visitClassType(ClassType t, Void ignored) {
  1751                 if (t.supertype_field == null) {
  1752                     Type supertype = ((ClassSymbol)t.tsym).getSuperclass();
  1753                     // An interface has no superclass; its supertype is Object.
  1754                     if (t.isInterface())
  1755                         supertype = ((ClassType)t.tsym.type).supertype_field;
  1756                     if (t.supertype_field == null) {
  1757                         List<Type> actuals = classBound(t).allparams();
  1758                         List<Type> formals = t.tsym.type.allparams();
  1759                         if (t.hasErasedSupertypes()) {
  1760                             t.supertype_field = erasureRecursive(supertype);
  1761                         } else if (formals.nonEmpty()) {
  1762                             t.supertype_field = subst(supertype, formals, actuals);
  1764                         else {
  1765                             t.supertype_field = supertype;
  1769                 return t.supertype_field;
  1772             /**
  1773              * The supertype is always a class type. If the type
  1774              * variable's bounds start with a class type, this is also
  1775              * the supertype.  Otherwise, the supertype is
  1776              * java.lang.Object.
  1777              */
  1778             @Override
  1779             public Type visitTypeVar(TypeVar t, Void ignored) {
  1780                 if (t.bound.tag == TYPEVAR ||
  1781                     (!t.bound.isCompound() && !t.bound.isInterface())) {
  1782                     return t.bound;
  1783                 } else {
  1784                     return supertype(t.bound);
  1788             @Override
  1789             public Type visitArrayType(ArrayType t, Void ignored) {
  1790                 if (t.elemtype.isPrimitive() || isSameType(t.elemtype, syms.objectType))
  1791                     return arraySuperType();
  1792                 else
  1793                     return new ArrayType(supertype(t.elemtype), t.tsym);
  1796             @Override
  1797             public Type visitErrorType(ErrorType t, Void ignored) {
  1798                 return t;
  1800         };
  1801     // </editor-fold>
  1803     // <editor-fold defaultstate="collapsed" desc="interfaces">
  1804     /**
  1805      * Return the interfaces implemented by this class.
  1806      */
  1807     public List<Type> interfaces(Type t) {
  1808         return interfaces.visit(t);
  1810     // where
  1811         private UnaryVisitor<List<Type>> interfaces = new UnaryVisitor<List<Type>>() {
  1813             public List<Type> visitType(Type t, Void ignored) {
  1814                 return List.nil();
  1817             @Override
  1818             public List<Type> visitClassType(ClassType t, Void ignored) {
  1819                 if (t.interfaces_field == null) {
  1820                     List<Type> interfaces = ((ClassSymbol)t.tsym).getInterfaces();
  1821                     if (t.interfaces_field == null) {
  1822                         // If t.interfaces_field is null, then t must
  1823                         // be a parameterized type (not to be confused
  1824                         // with a generic type declaration).
  1825                         // Terminology:
  1826                         //    Parameterized type: List<String>
  1827                         //    Generic type declaration: class List<E> { ... }
  1828                         // So t corresponds to List<String> and
  1829                         // t.tsym.type corresponds to List<E>.
  1830                         // The reason t must be parameterized type is
  1831                         // that completion will happen as a side
  1832                         // effect of calling
  1833                         // ClassSymbol.getInterfaces.  Since
  1834                         // t.interfaces_field is null after
  1835                         // completion, we can assume that t is not the
  1836                         // type of a class/interface declaration.
  1837                         Assert.check(t != t.tsym.type, t);
  1838                         List<Type> actuals = t.allparams();
  1839                         List<Type> formals = t.tsym.type.allparams();
  1840                         if (t.hasErasedSupertypes()) {
  1841                             t.interfaces_field = erasureRecursive(interfaces);
  1842                         } else if (formals.nonEmpty()) {
  1843                             t.interfaces_field =
  1844                                 upperBounds(subst(interfaces, formals, actuals));
  1846                         else {
  1847                             t.interfaces_field = interfaces;
  1851                 return t.interfaces_field;
  1854             @Override
  1855             public List<Type> visitTypeVar(TypeVar t, Void ignored) {
  1856                 if (t.bound.isCompound())
  1857                     return interfaces(t.bound);
  1859                 if (t.bound.isInterface())
  1860                     return List.of(t.bound);
  1862                 return List.nil();
  1864         };
  1865     // </editor-fold>
  1867     // <editor-fold defaultstate="collapsed" desc="isDerivedRaw">
  1868     Map<Type,Boolean> isDerivedRawCache = new HashMap<Type,Boolean>();
  1870     public boolean isDerivedRaw(Type t) {
  1871         Boolean result = isDerivedRawCache.get(t);
  1872         if (result == null) {
  1873             result = isDerivedRawInternal(t);
  1874             isDerivedRawCache.put(t, result);
  1876         return result;
  1879     public boolean isDerivedRawInternal(Type t) {
  1880         if (t.isErroneous())
  1881             return false;
  1882         return
  1883             t.isRaw() ||
  1884             supertype(t) != null && isDerivedRaw(supertype(t)) ||
  1885             isDerivedRaw(interfaces(t));
  1888     public boolean isDerivedRaw(List<Type> ts) {
  1889         List<Type> l = ts;
  1890         while (l.nonEmpty() && !isDerivedRaw(l.head)) l = l.tail;
  1891         return l.nonEmpty();
  1893     // </editor-fold>
  1895     // <editor-fold defaultstate="collapsed" desc="setBounds">
  1896     /**
  1897      * Set the bounds field of the given type variable to reflect a
  1898      * (possibly multiple) list of bounds.
  1899      * @param t                 a type variable
  1900      * @param bounds            the bounds, must be nonempty
  1901      * @param supertype         is objectType if all bounds are interfaces,
  1902      *                          null otherwise.
  1903      */
  1904     public void setBounds(TypeVar t, List<Type> bounds, Type supertype) {
  1905         if (bounds.tail.isEmpty())
  1906             t.bound = bounds.head;
  1907         else
  1908             t.bound = makeCompoundType(bounds, supertype);
  1909         t.rank_field = -1;
  1912     /**
  1913      * Same as {@link #setBounds(Type.TypeVar,List,Type)}, except that
  1914      * third parameter is computed directly, as follows: if all
  1915      * all bounds are interface types, the computed supertype is Object,
  1916      * otherwise the supertype is simply left null (in this case, the supertype
  1917      * is assumed to be the head of the bound list passed as second argument).
  1918      * Note that this check might cause a symbol completion. Hence, this version of
  1919      * setBounds may not be called during a classfile read.
  1920      */
  1921     public void setBounds(TypeVar t, List<Type> bounds) {
  1922         Type supertype = (bounds.head.tsym.flags() & INTERFACE) != 0 ?
  1923             syms.objectType : null;
  1924         setBounds(t, bounds, supertype);
  1925         t.rank_field = -1;
  1927     // </editor-fold>
  1929     // <editor-fold defaultstate="collapsed" desc="getBounds">
  1930     /**
  1931      * Return list of bounds of the given type variable.
  1932      */
  1933     public List<Type> getBounds(TypeVar t) {
  1934         if (t.bound.isErroneous() || !t.bound.isCompound())
  1935             return List.of(t.bound);
  1936         else if ((erasure(t).tsym.flags() & INTERFACE) == 0)
  1937             return interfaces(t).prepend(supertype(t));
  1938         else
  1939             // No superclass was given in bounds.
  1940             // In this case, supertype is Object, erasure is first interface.
  1941             return interfaces(t);
  1943     // </editor-fold>
  1945     // <editor-fold defaultstate="collapsed" desc="classBound">
  1946     /**
  1947      * If the given type is a (possibly selected) type variable,
  1948      * return the bounding class of this type, otherwise return the
  1949      * type itself.
  1950      */
  1951     public Type classBound(Type t) {
  1952         return classBound.visit(t);
  1954     // where
  1955         private UnaryVisitor<Type> classBound = new UnaryVisitor<Type>() {
  1957             public Type visitType(Type t, Void ignored) {
  1958                 return t;
  1961             @Override
  1962             public Type visitClassType(ClassType t, Void ignored) {
  1963                 Type outer1 = classBound(t.getEnclosingType());
  1964                 if (outer1 != t.getEnclosingType())
  1965                     return new ClassType(outer1, t.getTypeArguments(), t.tsym);
  1966                 else
  1967                     return t;
  1970             @Override
  1971             public Type visitTypeVar(TypeVar t, Void ignored) {
  1972                 return classBound(supertype(t));
  1975             @Override
  1976             public Type visitErrorType(ErrorType t, Void ignored) {
  1977                 return t;
  1979         };
  1980     // </editor-fold>
  1982     // <editor-fold defaultstate="collapsed" desc="sub signature / override equivalence">
  1983     /**
  1984      * Returns true iff the first signature is a <em>sub
  1985      * signature</em> of the other.  This is <b>not</b> an equivalence
  1986      * relation.
  1988      * @see "The Java Language Specification, Third Ed. (8.4.2)."
  1989      * @see #overrideEquivalent(Type t, Type s)
  1990      * @param t first signature (possibly raw).
  1991      * @param s second signature (could be subjected to erasure).
  1992      * @return true if t is a sub signature of s.
  1993      */
  1994     public boolean isSubSignature(Type t, Type s) {
  1995         return isSubSignature(t, s, true);
  1998     public boolean isSubSignature(Type t, Type s, boolean strict) {
  1999         return hasSameArgs(t, s, strict) || hasSameArgs(t, erasure(s), strict);
  2002     /**
  2003      * Returns true iff these signatures are related by <em>override
  2004      * equivalence</em>.  This is the natural extension of
  2005      * isSubSignature to an equivalence relation.
  2007      * @see "The Java Language Specification, Third Ed. (8.4.2)."
  2008      * @see #isSubSignature(Type t, Type s)
  2009      * @param t a signature (possible raw, could be subjected to
  2010      * erasure).
  2011      * @param s a signature (possible raw, could be subjected to
  2012      * erasure).
  2013      * @return true if either argument is a sub signature of the other.
  2014      */
  2015     public boolean overrideEquivalent(Type t, Type s) {
  2016         return hasSameArgs(t, s) ||
  2017             hasSameArgs(t, erasure(s)) || hasSameArgs(erasure(t), s);
  2020     // <editor-fold defaultstate="collapsed" desc="Determining method implementation in given site">
  2021     class ImplementationCache {
  2023         private WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>> _map =
  2024                 new WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>>();
  2026         class Entry {
  2027             final MethodSymbol cachedImpl;
  2028             final Filter<Symbol> implFilter;
  2029             final boolean checkResult;
  2030             final int prevMark;
  2032             public Entry(MethodSymbol cachedImpl,
  2033                     Filter<Symbol> scopeFilter,
  2034                     boolean checkResult,
  2035                     int prevMark) {
  2036                 this.cachedImpl = cachedImpl;
  2037                 this.implFilter = scopeFilter;
  2038                 this.checkResult = checkResult;
  2039                 this.prevMark = prevMark;
  2042             boolean matches(Filter<Symbol> scopeFilter, boolean checkResult, int mark) {
  2043                 return this.implFilter == scopeFilter &&
  2044                         this.checkResult == checkResult &&
  2045                         this.prevMark == mark;
  2049         MethodSymbol get(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
  2050             SoftReference<Map<TypeSymbol, Entry>> ref_cache = _map.get(ms);
  2051             Map<TypeSymbol, Entry> cache = ref_cache != null ? ref_cache.get() : null;
  2052             if (cache == null) {
  2053                 cache = new HashMap<TypeSymbol, Entry>();
  2054                 _map.put(ms, new SoftReference<Map<TypeSymbol, Entry>>(cache));
  2056             Entry e = cache.get(origin);
  2057             CompoundScope members = membersClosure(origin.type);
  2058             if (e == null ||
  2059                     !e.matches(implFilter, checkResult, members.getMark())) {
  2060                 MethodSymbol impl = implementationInternal(ms, origin, checkResult, implFilter);
  2061                 cache.put(origin, new Entry(impl, implFilter, checkResult, members.getMark()));
  2062                 return impl;
  2064             else {
  2065                 return e.cachedImpl;
  2069         private MethodSymbol implementationInternal(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
  2070             for (Type t = origin.type; t.tag == CLASS || t.tag == TYPEVAR; t = supertype(t)) {
  2071                 while (t.tag == TYPEVAR)
  2072                     t = t.getUpperBound();
  2073                 TypeSymbol c = t.tsym;
  2074                 for (Scope.Entry e = c.members().lookup(ms.name, implFilter);
  2075                      e.scope != null;
  2076                      e = e.next(implFilter)) {
  2077                     if (e.sym != null &&
  2078                              e.sym.overrides(ms, origin, Types.this, checkResult))
  2079                         return (MethodSymbol)e.sym;
  2082             return null;
  2086     private ImplementationCache implCache = new ImplementationCache();
  2088     public MethodSymbol implementation(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
  2089         return implCache.get(ms, origin, checkResult, implFilter);
  2091     // </editor-fold>
  2093     // <editor-fold defaultstate="collapsed" desc="compute transitive closure of all members in given site">
  2094     public CompoundScope membersClosure(Type site) {
  2095         return membersClosure.visit(site);
  2098     UnaryVisitor<CompoundScope> membersClosure = new UnaryVisitor<CompoundScope>() {
  2100         public CompoundScope visitType(Type t, Void s) {
  2101             return null;
  2104         @Override
  2105         public CompoundScope visitClassType(ClassType t, Void s) {
  2106             ClassSymbol csym = (ClassSymbol)t.tsym;
  2107             if (csym.membersClosure == null) {
  2108                 CompoundScope membersClosure = new CompoundScope(csym);
  2109                 for (Type i : interfaces(t)) {
  2110                     membersClosure.addSubScope(visit(i));
  2112                 membersClosure.addSubScope(visit(supertype(t)));
  2113                 membersClosure.addSubScope(csym.members());
  2114                 csym.membersClosure = membersClosure;
  2116             return csym.membersClosure;
  2119         @Override
  2120         public CompoundScope visitTypeVar(TypeVar t, Void s) {
  2121             return visit(t.getUpperBound());
  2123     };
  2124     // </editor-fold>
  2126     /**
  2127      * Does t have the same arguments as s?  It is assumed that both
  2128      * types are (possibly polymorphic) method types.  Monomorphic
  2129      * method types "have the same arguments", if their argument lists
  2130      * are equal.  Polymorphic method types "have the same arguments",
  2131      * if they have the same arguments after renaming all type
  2132      * variables of one to corresponding type variables in the other,
  2133      * where correspondence is by position in the type parameter list.
  2134      */
  2135     public boolean hasSameArgs(Type t, Type s) {
  2136         return hasSameArgs(t, s, true);
  2139     public boolean hasSameArgs(Type t, Type s, boolean strict) {
  2140         return hasSameArgs(t, s, strict ? hasSameArgs_strict : hasSameArgs_nonstrict);
  2143     private boolean hasSameArgs(Type t, Type s, TypeRelation hasSameArgs) {
  2144         return hasSameArgs.visit(t, s);
  2146     // where
  2147         private class HasSameArgs extends TypeRelation {
  2149             boolean strict;
  2151             public HasSameArgs(boolean strict) {
  2152                 this.strict = strict;
  2155             public Boolean visitType(Type t, Type s) {
  2156                 throw new AssertionError();
  2159             @Override
  2160             public Boolean visitMethodType(MethodType t, Type s) {
  2161                 return s.tag == METHOD
  2162                     && containsTypeEquivalent(t.argtypes, s.getParameterTypes());
  2165             @Override
  2166             public Boolean visitForAll(ForAll t, Type s) {
  2167                 if (s.tag != FORALL)
  2168                     return strict ? false : visitMethodType(t.asMethodType(), s);
  2170                 ForAll forAll = (ForAll)s;
  2171                 return hasSameBounds(t, forAll)
  2172                     && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
  2175             @Override
  2176             public Boolean visitErrorType(ErrorType t, Type s) {
  2177                 return false;
  2179         };
  2181         TypeRelation hasSameArgs_strict = new HasSameArgs(true);
  2182         TypeRelation hasSameArgs_nonstrict = new HasSameArgs(false);
  2184     // </editor-fold>
  2186     // <editor-fold defaultstate="collapsed" desc="subst">
  2187     public List<Type> subst(List<Type> ts,
  2188                             List<Type> from,
  2189                             List<Type> to) {
  2190         return new Subst(from, to).subst(ts);
  2193     /**
  2194      * Substitute all occurrences of a type in `from' with the
  2195      * corresponding type in `to' in 't'. Match lists `from' and `to'
  2196      * from the right: If lists have different length, discard leading
  2197      * elements of the longer list.
  2198      */
  2199     public Type subst(Type t, List<Type> from, List<Type> to) {
  2200         return new Subst(from, to).subst(t);
  2203     private class Subst extends UnaryVisitor<Type> {
  2204         List<Type> from;
  2205         List<Type> to;
  2207         public Subst(List<Type> from, List<Type> to) {
  2208             int fromLength = from.length();
  2209             int toLength = to.length();
  2210             while (fromLength > toLength) {
  2211                 fromLength--;
  2212                 from = from.tail;
  2214             while (fromLength < toLength) {
  2215                 toLength--;
  2216                 to = to.tail;
  2218             this.from = from;
  2219             this.to = to;
  2222         Type subst(Type t) {
  2223             if (from.tail == null)
  2224                 return t;
  2225             else
  2226                 return visit(t);
  2229         List<Type> subst(List<Type> ts) {
  2230             if (from.tail == null)
  2231                 return ts;
  2232             boolean wild = false;
  2233             if (ts.nonEmpty() && from.nonEmpty()) {
  2234                 Type head1 = subst(ts.head);
  2235                 List<Type> tail1 = subst(ts.tail);
  2236                 if (head1 != ts.head || tail1 != ts.tail)
  2237                     return tail1.prepend(head1);
  2239             return ts;
  2242         public Type visitType(Type t, Void ignored) {
  2243             return t;
  2246         @Override
  2247         public Type visitMethodType(MethodType t, Void ignored) {
  2248             List<Type> argtypes = subst(t.argtypes);
  2249             Type restype = subst(t.restype);
  2250             List<Type> thrown = subst(t.thrown);
  2251             if (argtypes == t.argtypes &&
  2252                 restype == t.restype &&
  2253                 thrown == t.thrown)
  2254                 return t;
  2255             else
  2256                 return new MethodType(argtypes, restype, thrown, t.tsym);
  2259         @Override
  2260         public Type visitTypeVar(TypeVar t, Void ignored) {
  2261             for (List<Type> from = this.from, to = this.to;
  2262                  from.nonEmpty();
  2263                  from = from.tail, to = to.tail) {
  2264                 if (t == from.head) {
  2265                     return to.head.withTypeVar(t);
  2268             return t;
  2271         @Override
  2272         public Type visitClassType(ClassType t, Void ignored) {
  2273             if (!t.isCompound()) {
  2274                 List<Type> typarams = t.getTypeArguments();
  2275                 List<Type> typarams1 = subst(typarams);
  2276                 Type outer = t.getEnclosingType();
  2277                 Type outer1 = subst(outer);
  2278                 if (typarams1 == typarams && outer1 == outer)
  2279                     return t;
  2280                 else
  2281                     return new ClassType(outer1, typarams1, t.tsym);
  2282             } else {
  2283                 Type st = subst(supertype(t));
  2284                 List<Type> is = upperBounds(subst(interfaces(t)));
  2285                 if (st == supertype(t) && is == interfaces(t))
  2286                     return t;
  2287                 else
  2288                     return makeCompoundType(is.prepend(st));
  2292         @Override
  2293         public Type visitWildcardType(WildcardType t, Void ignored) {
  2294             Type bound = t.type;
  2295             if (t.kind != BoundKind.UNBOUND)
  2296                 bound = subst(bound);
  2297             if (bound == t.type) {
  2298                 return t;
  2299             } else {
  2300                 if (t.isExtendsBound() && bound.isExtendsBound())
  2301                     bound = upperBound(bound);
  2302                 return new WildcardType(bound, t.kind, syms.boundClass, t.bound);
  2306         @Override
  2307         public Type visitArrayType(ArrayType t, Void ignored) {
  2308             Type elemtype = subst(t.elemtype);
  2309             if (elemtype == t.elemtype)
  2310                 return t;
  2311             else
  2312                 return new ArrayType(upperBound(elemtype), t.tsym);
  2315         @Override
  2316         public Type visitForAll(ForAll t, Void ignored) {
  2317             if (Type.containsAny(to, t.tvars)) {
  2318                 //perform alpha-renaming of free-variables in 't'
  2319                 //if 'to' types contain variables that are free in 't'
  2320                 List<Type> freevars = newInstances(t.tvars);
  2321                 t = new ForAll(freevars,
  2322                         Types.this.subst(t.qtype, t.tvars, freevars));
  2324             List<Type> tvars1 = substBounds(t.tvars, from, to);
  2325             Type qtype1 = subst(t.qtype);
  2326             if (tvars1 == t.tvars && qtype1 == t.qtype) {
  2327                 return t;
  2328             } else if (tvars1 == t.tvars) {
  2329                 return new ForAll(tvars1, qtype1);
  2330             } else {
  2331                 return new ForAll(tvars1, Types.this.subst(qtype1, t.tvars, tvars1));
  2335         @Override
  2336         public Type visitErrorType(ErrorType t, Void ignored) {
  2337             return t;
  2341     public List<Type> substBounds(List<Type> tvars,
  2342                                   List<Type> from,
  2343                                   List<Type> to) {
  2344         if (tvars.isEmpty())
  2345             return tvars;
  2346         ListBuffer<Type> newBoundsBuf = lb();
  2347         boolean changed = false;
  2348         // calculate new bounds
  2349         for (Type t : tvars) {
  2350             TypeVar tv = (TypeVar) t;
  2351             Type bound = subst(tv.bound, from, to);
  2352             if (bound != tv.bound)
  2353                 changed = true;
  2354             newBoundsBuf.append(bound);
  2356         if (!changed)
  2357             return tvars;
  2358         ListBuffer<Type> newTvars = lb();
  2359         // create new type variables without bounds
  2360         for (Type t : tvars) {
  2361             newTvars.append(new TypeVar(t.tsym, null, syms.botType));
  2363         // the new bounds should use the new type variables in place
  2364         // of the old
  2365         List<Type> newBounds = newBoundsBuf.toList();
  2366         from = tvars;
  2367         to = newTvars.toList();
  2368         for (; !newBounds.isEmpty(); newBounds = newBounds.tail) {
  2369             newBounds.head = subst(newBounds.head, from, to);
  2371         newBounds = newBoundsBuf.toList();
  2372         // set the bounds of new type variables to the new bounds
  2373         for (Type t : newTvars.toList()) {
  2374             TypeVar tv = (TypeVar) t;
  2375             tv.bound = newBounds.head;
  2376             newBounds = newBounds.tail;
  2378         return newTvars.toList();
  2381     public TypeVar substBound(TypeVar t, List<Type> from, List<Type> to) {
  2382         Type bound1 = subst(t.bound, from, to);
  2383         if (bound1 == t.bound)
  2384             return t;
  2385         else {
  2386             // create new type variable without bounds
  2387             TypeVar tv = new TypeVar(t.tsym, null, syms.botType);
  2388             // the new bound should use the new type variable in place
  2389             // of the old
  2390             tv.bound = subst(bound1, List.<Type>of(t), List.<Type>of(tv));
  2391             return tv;
  2394     // </editor-fold>
  2396     // <editor-fold defaultstate="collapsed" desc="hasSameBounds">
  2397     /**
  2398      * Does t have the same bounds for quantified variables as s?
  2399      */
  2400     boolean hasSameBounds(ForAll t, ForAll s) {
  2401         List<Type> l1 = t.tvars;
  2402         List<Type> l2 = s.tvars;
  2403         while (l1.nonEmpty() && l2.nonEmpty() &&
  2404                isSameType(l1.head.getUpperBound(),
  2405                           subst(l2.head.getUpperBound(),
  2406                                 s.tvars,
  2407                                 t.tvars))) {
  2408             l1 = l1.tail;
  2409             l2 = l2.tail;
  2411         return l1.isEmpty() && l2.isEmpty();
  2413     // </editor-fold>
  2415     // <editor-fold defaultstate="collapsed" desc="newInstances">
  2416     /** Create new vector of type variables from list of variables
  2417      *  changing all recursive bounds from old to new list.
  2418      */
  2419     public List<Type> newInstances(List<Type> tvars) {
  2420         List<Type> tvars1 = Type.map(tvars, newInstanceFun);
  2421         for (List<Type> l = tvars1; l.nonEmpty(); l = l.tail) {
  2422             TypeVar tv = (TypeVar) l.head;
  2423             tv.bound = subst(tv.bound, tvars, tvars1);
  2425         return tvars1;
  2427     static private Mapping newInstanceFun = new Mapping("newInstanceFun") {
  2428             public Type apply(Type t) { return new TypeVar(t.tsym, t.getUpperBound(), t.getLowerBound()); }
  2429         };
  2430     // </editor-fold>
  2432     public Type createMethodTypeWithParameters(Type original, List<Type> newParams) {
  2433         return original.accept(methodWithParameters, newParams);
  2435     // where
  2436         private final MapVisitor<List<Type>> methodWithParameters = new MapVisitor<List<Type>>() {
  2437             public Type visitType(Type t, List<Type> newParams) {
  2438                 throw new IllegalArgumentException("Not a method type: " + t);
  2440             public Type visitMethodType(MethodType t, List<Type> newParams) {
  2441                 return new MethodType(newParams, t.restype, t.thrown, t.tsym);
  2443             public Type visitForAll(ForAll t, List<Type> newParams) {
  2444                 return new ForAll(t.tvars, t.qtype.accept(this, newParams));
  2446         };
  2448     public Type createMethodTypeWithThrown(Type original, List<Type> newThrown) {
  2449         return original.accept(methodWithThrown, newThrown);
  2451     // where
  2452         private final MapVisitor<List<Type>> methodWithThrown = new MapVisitor<List<Type>>() {
  2453             public Type visitType(Type t, List<Type> newThrown) {
  2454                 throw new IllegalArgumentException("Not a method type: " + t);
  2456             public Type visitMethodType(MethodType t, List<Type> newThrown) {
  2457                 return new MethodType(t.argtypes, t.restype, newThrown, t.tsym);
  2459             public Type visitForAll(ForAll t, List<Type> newThrown) {
  2460                 return new ForAll(t.tvars, t.qtype.accept(this, newThrown));
  2462         };
  2464     // <editor-fold defaultstate="collapsed" desc="createErrorType">
  2465     public Type createErrorType(Type originalType) {
  2466         return new ErrorType(originalType, syms.errSymbol);
  2469     public Type createErrorType(ClassSymbol c, Type originalType) {
  2470         return new ErrorType(c, originalType);
  2473     public Type createErrorType(Name name, TypeSymbol container, Type originalType) {
  2474         return new ErrorType(name, container, originalType);
  2476     // </editor-fold>
  2478     // <editor-fold defaultstate="collapsed" desc="rank">
  2479     /**
  2480      * The rank of a class is the length of the longest path between
  2481      * the class and java.lang.Object in the class inheritance
  2482      * graph. Undefined for all but reference types.
  2483      */
  2484     public int rank(Type t) {
  2485         switch(t.tag) {
  2486         case CLASS: {
  2487             ClassType cls = (ClassType)t;
  2488             if (cls.rank_field < 0) {
  2489                 Name fullname = cls.tsym.getQualifiedName();
  2490                 if (fullname == names.java_lang_Object)
  2491                     cls.rank_field = 0;
  2492                 else {
  2493                     int r = rank(supertype(cls));
  2494                     for (List<Type> l = interfaces(cls);
  2495                          l.nonEmpty();
  2496                          l = l.tail) {
  2497                         if (rank(l.head) > r)
  2498                             r = rank(l.head);
  2500                     cls.rank_field = r + 1;
  2503             return cls.rank_field;
  2505         case TYPEVAR: {
  2506             TypeVar tvar = (TypeVar)t;
  2507             if (tvar.rank_field < 0) {
  2508                 int r = rank(supertype(tvar));
  2509                 for (List<Type> l = interfaces(tvar);
  2510                      l.nonEmpty();
  2511                      l = l.tail) {
  2512                     if (rank(l.head) > r) r = rank(l.head);
  2514                 tvar.rank_field = r + 1;
  2516             return tvar.rank_field;
  2518         case ERROR:
  2519             return 0;
  2520         default:
  2521             throw new AssertionError();
  2524     // </editor-fold>
  2526     /**
  2527      * Helper method for generating a string representation of a given type
  2528      * accordingly to a given locale
  2529      */
  2530     public String toString(Type t, Locale locale) {
  2531         return Printer.createStandardPrinter(messages).visit(t, locale);
  2534     /**
  2535      * Helper method for generating a string representation of a given type
  2536      * accordingly to a given locale
  2537      */
  2538     public String toString(Symbol t, Locale locale) {
  2539         return Printer.createStandardPrinter(messages).visit(t, locale);
  2542     // <editor-fold defaultstate="collapsed" desc="toString">
  2543     /**
  2544      * This toString is slightly more descriptive than the one on Type.
  2546      * @deprecated Types.toString(Type t, Locale l) provides better support
  2547      * for localization
  2548      */
  2549     @Deprecated
  2550     public String toString(Type t) {
  2551         if (t.tag == FORALL) {
  2552             ForAll forAll = (ForAll)t;
  2553             return typaramsString(forAll.tvars) + forAll.qtype;
  2555         return "" + t;
  2557     // where
  2558         private String typaramsString(List<Type> tvars) {
  2559             StringBuilder s = new StringBuilder();
  2560             s.append('<');
  2561             boolean first = true;
  2562             for (Type t : tvars) {
  2563                 if (!first) s.append(", ");
  2564                 first = false;
  2565                 appendTyparamString(((TypeVar)t), s);
  2567             s.append('>');
  2568             return s.toString();
  2570         private void appendTyparamString(TypeVar t, StringBuilder buf) {
  2571             buf.append(t);
  2572             if (t.bound == null ||
  2573                 t.bound.tsym.getQualifiedName() == names.java_lang_Object)
  2574                 return;
  2575             buf.append(" extends "); // Java syntax; no need for i18n
  2576             Type bound = t.bound;
  2577             if (!bound.isCompound()) {
  2578                 buf.append(bound);
  2579             } else if ((erasure(t).tsym.flags() & INTERFACE) == 0) {
  2580                 buf.append(supertype(t));
  2581                 for (Type intf : interfaces(t)) {
  2582                     buf.append('&');
  2583                     buf.append(intf);
  2585             } else {
  2586                 // No superclass was given in bounds.
  2587                 // In this case, supertype is Object, erasure is first interface.
  2588                 boolean first = true;
  2589                 for (Type intf : interfaces(t)) {
  2590                     if (!first) buf.append('&');
  2591                     first = false;
  2592                     buf.append(intf);
  2596     // </editor-fold>
  2598     // <editor-fold defaultstate="collapsed" desc="Determining least upper bounds of types">
  2599     /**
  2600      * A cache for closures.
  2602      * <p>A closure is a list of all the supertypes and interfaces of
  2603      * a class or interface type, ordered by ClassSymbol.precedes
  2604      * (that is, subclasses come first, arbitrary but fixed
  2605      * otherwise).
  2606      */
  2607     private Map<Type,List<Type>> closureCache = new HashMap<Type,List<Type>>();
  2609     /**
  2610      * Returns the closure of a class or interface type.
  2611      */
  2612     public List<Type> closure(Type t) {
  2613         List<Type> cl = closureCache.get(t);
  2614         if (cl == null) {
  2615             Type st = supertype(t);
  2616             if (!t.isCompound()) {
  2617                 if (st.tag == CLASS) {
  2618                     cl = insert(closure(st), t);
  2619                 } else if (st.tag == TYPEVAR) {
  2620                     cl = closure(st).prepend(t);
  2621                 } else {
  2622                     cl = List.of(t);
  2624             } else {
  2625                 cl = closure(supertype(t));
  2627             for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail)
  2628                 cl = union(cl, closure(l.head));
  2629             closureCache.put(t, cl);
  2631         return cl;
  2634     /**
  2635      * Insert a type in a closure
  2636      */
  2637     public List<Type> insert(List<Type> cl, Type t) {
  2638         if (cl.isEmpty() || t.tsym.precedes(cl.head.tsym, this)) {
  2639             return cl.prepend(t);
  2640         } else if (cl.head.tsym.precedes(t.tsym, this)) {
  2641             return insert(cl.tail, t).prepend(cl.head);
  2642         } else {
  2643             return cl;
  2647     /**
  2648      * Form the union of two closures
  2649      */
  2650     public List<Type> union(List<Type> cl1, List<Type> cl2) {
  2651         if (cl1.isEmpty()) {
  2652             return cl2;
  2653         } else if (cl2.isEmpty()) {
  2654             return cl1;
  2655         } else if (cl1.head.tsym.precedes(cl2.head.tsym, this)) {
  2656             return union(cl1.tail, cl2).prepend(cl1.head);
  2657         } else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) {
  2658             return union(cl1, cl2.tail).prepend(cl2.head);
  2659         } else {
  2660             return union(cl1.tail, cl2.tail).prepend(cl1.head);
  2664     /**
  2665      * Intersect two closures
  2666      */
  2667     public List<Type> intersect(List<Type> cl1, List<Type> cl2) {
  2668         if (cl1 == cl2)
  2669             return cl1;
  2670         if (cl1.isEmpty() || cl2.isEmpty())
  2671             return List.nil();
  2672         if (cl1.head.tsym.precedes(cl2.head.tsym, this))
  2673             return intersect(cl1.tail, cl2);
  2674         if (cl2.head.tsym.precedes(cl1.head.tsym, this))
  2675             return intersect(cl1, cl2.tail);
  2676         if (isSameType(cl1.head, cl2.head))
  2677             return intersect(cl1.tail, cl2.tail).prepend(cl1.head);
  2678         if (cl1.head.tsym == cl2.head.tsym &&
  2679             cl1.head.tag == CLASS && cl2.head.tag == CLASS) {
  2680             if (cl1.head.isParameterized() && cl2.head.isParameterized()) {
  2681                 Type merge = merge(cl1.head,cl2.head);
  2682                 return intersect(cl1.tail, cl2.tail).prepend(merge);
  2684             if (cl1.head.isRaw() || cl2.head.isRaw())
  2685                 return intersect(cl1.tail, cl2.tail).prepend(erasure(cl1.head));
  2687         return intersect(cl1.tail, cl2.tail);
  2689     // where
  2690         class TypePair {
  2691             final Type t1;
  2692             final Type t2;
  2693             TypePair(Type t1, Type t2) {
  2694                 this.t1 = t1;
  2695                 this.t2 = t2;
  2697             @Override
  2698             public int hashCode() {
  2699                 return 127 * Types.hashCode(t1) + Types.hashCode(t2);
  2701             @Override
  2702             public boolean equals(Object obj) {
  2703                 if (!(obj instanceof TypePair))
  2704                     return false;
  2705                 TypePair typePair = (TypePair)obj;
  2706                 return isSameType(t1, typePair.t1)
  2707                     && isSameType(t2, typePair.t2);
  2710         Set<TypePair> mergeCache = new HashSet<TypePair>();
  2711         private Type merge(Type c1, Type c2) {
  2712             ClassType class1 = (ClassType) c1;
  2713             List<Type> act1 = class1.getTypeArguments();
  2714             ClassType class2 = (ClassType) c2;
  2715             List<Type> act2 = class2.getTypeArguments();
  2716             ListBuffer<Type> merged = new ListBuffer<Type>();
  2717             List<Type> typarams = class1.tsym.type.getTypeArguments();
  2719             while (act1.nonEmpty() && act2.nonEmpty() && typarams.nonEmpty()) {
  2720                 if (containsType(act1.head, act2.head)) {
  2721                     merged.append(act1.head);
  2722                 } else if (containsType(act2.head, act1.head)) {
  2723                     merged.append(act2.head);
  2724                 } else {
  2725                     TypePair pair = new TypePair(c1, c2);
  2726                     Type m;
  2727                     if (mergeCache.add(pair)) {
  2728                         m = new WildcardType(lub(upperBound(act1.head),
  2729                                                  upperBound(act2.head)),
  2730                                              BoundKind.EXTENDS,
  2731                                              syms.boundClass);
  2732                         mergeCache.remove(pair);
  2733                     } else {
  2734                         m = new WildcardType(syms.objectType,
  2735                                              BoundKind.UNBOUND,
  2736                                              syms.boundClass);
  2738                     merged.append(m.withTypeVar(typarams.head));
  2740                 act1 = act1.tail;
  2741                 act2 = act2.tail;
  2742                 typarams = typarams.tail;
  2744             Assert.check(act1.isEmpty() && act2.isEmpty() && typarams.isEmpty());
  2745             return new ClassType(class1.getEnclosingType(), merged.toList(), class1.tsym);
  2748     /**
  2749      * Return the minimum type of a closure, a compound type if no
  2750      * unique minimum exists.
  2751      */
  2752     private Type compoundMin(List<Type> cl) {
  2753         if (cl.isEmpty()) return syms.objectType;
  2754         List<Type> compound = closureMin(cl);
  2755         if (compound.isEmpty())
  2756             return null;
  2757         else if (compound.tail.isEmpty())
  2758             return compound.head;
  2759         else
  2760             return makeCompoundType(compound);
  2763     /**
  2764      * Return the minimum types of a closure, suitable for computing
  2765      * compoundMin or glb.
  2766      */
  2767     private List<Type> closureMin(List<Type> cl) {
  2768         ListBuffer<Type> classes = lb();
  2769         ListBuffer<Type> interfaces = lb();
  2770         while (!cl.isEmpty()) {
  2771             Type current = cl.head;
  2772             if (current.isInterface())
  2773                 interfaces.append(current);
  2774             else
  2775                 classes.append(current);
  2776             ListBuffer<Type> candidates = lb();
  2777             for (Type t : cl.tail) {
  2778                 if (!isSubtypeNoCapture(current, t))
  2779                     candidates.append(t);
  2781             cl = candidates.toList();
  2783         return classes.appendList(interfaces).toList();
  2786     /**
  2787      * Return the least upper bound of pair of types.  if the lub does
  2788      * not exist return null.
  2789      */
  2790     public Type lub(Type t1, Type t2) {
  2791         return lub(List.of(t1, t2));
  2794     /**
  2795      * Return the least upper bound (lub) of set of types.  If the lub
  2796      * does not exist return the type of null (bottom).
  2797      */
  2798     public Type lub(List<Type> ts) {
  2799         final int ARRAY_BOUND = 1;
  2800         final int CLASS_BOUND = 2;
  2801         int boundkind = 0;
  2802         for (Type t : ts) {
  2803             switch (t.tag) {
  2804             case CLASS:
  2805                 boundkind |= CLASS_BOUND;
  2806                 break;
  2807             case ARRAY:
  2808                 boundkind |= ARRAY_BOUND;
  2809                 break;
  2810             case  TYPEVAR:
  2811                 do {
  2812                     t = t.getUpperBound();
  2813                 } while (t.tag == TYPEVAR);
  2814                 if (t.tag == ARRAY) {
  2815                     boundkind |= ARRAY_BOUND;
  2816                 } else {
  2817                     boundkind |= CLASS_BOUND;
  2819                 break;
  2820             default:
  2821                 if (t.isPrimitive())
  2822                     return syms.errType;
  2825         switch (boundkind) {
  2826         case 0:
  2827             return syms.botType;
  2829         case ARRAY_BOUND:
  2830             // calculate lub(A[], B[])
  2831             List<Type> elements = Type.map(ts, elemTypeFun);
  2832             for (Type t : elements) {
  2833                 if (t.isPrimitive()) {
  2834                     // if a primitive type is found, then return
  2835                     // arraySuperType unless all the types are the
  2836                     // same
  2837                     Type first = ts.head;
  2838                     for (Type s : ts.tail) {
  2839                         if (!isSameType(first, s)) {
  2840                              // lub(int[], B[]) is Cloneable & Serializable
  2841                             return arraySuperType();
  2844                     // all the array types are the same, return one
  2845                     // lub(int[], int[]) is int[]
  2846                     return first;
  2849             // lub(A[], B[]) is lub(A, B)[]
  2850             return new ArrayType(lub(elements), syms.arrayClass);
  2852         case CLASS_BOUND:
  2853             // calculate lub(A, B)
  2854             while (ts.head.tag != CLASS && ts.head.tag != TYPEVAR)
  2855                 ts = ts.tail;
  2856             Assert.check(!ts.isEmpty());
  2857             //step 1 - compute erased candidate set (EC)
  2858             List<Type> cl = erasedSupertypes(ts.head);
  2859             for (Type t : ts.tail) {
  2860                 if (t.tag == CLASS || t.tag == TYPEVAR)
  2861                     cl = intersect(cl, erasedSupertypes(t));
  2863             //step 2 - compute minimal erased candidate set (MEC)
  2864             List<Type> mec = closureMin(cl);
  2865             //step 3 - for each element G in MEC, compute lci(Inv(G))
  2866             List<Type> candidates = List.nil();
  2867             for (Type erasedSupertype : mec) {
  2868                 List<Type> lci = List.of(asSuper(ts.head, erasedSupertype.tsym));
  2869                 for (Type t : ts) {
  2870                     lci = intersect(lci, List.of(asSuper(t, erasedSupertype.tsym)));
  2872                 candidates = candidates.appendList(lci);
  2874             //step 4 - let MEC be { G1, G2 ... Gn }, then we have that
  2875             //lub = lci(Inv(G1)) & lci(Inv(G2)) & ... & lci(Inv(Gn))
  2876             return compoundMin(candidates);
  2878         default:
  2879             // calculate lub(A, B[])
  2880             List<Type> classes = List.of(arraySuperType());
  2881             for (Type t : ts) {
  2882                 if (t.tag != ARRAY) // Filter out any arrays
  2883                     classes = classes.prepend(t);
  2885             // lub(A, B[]) is lub(A, arraySuperType)
  2886             return lub(classes);
  2889     // where
  2890         List<Type> erasedSupertypes(Type t) {
  2891             ListBuffer<Type> buf = lb();
  2892             for (Type sup : closure(t)) {
  2893                 if (sup.tag == TYPEVAR) {
  2894                     buf.append(sup);
  2895                 } else {
  2896                     buf.append(erasure(sup));
  2899             return buf.toList();
  2902         private Type arraySuperType = null;
  2903         private Type arraySuperType() {
  2904             // initialized lazily to avoid problems during compiler startup
  2905             if (arraySuperType == null) {
  2906                 synchronized (this) {
  2907                     if (arraySuperType == null) {
  2908                         // JLS 10.8: all arrays implement Cloneable and Serializable.
  2909                         arraySuperType = makeCompoundType(List.of(syms.serializableType,
  2910                                                                   syms.cloneableType),
  2911                                                           syms.objectType);
  2915             return arraySuperType;
  2917     // </editor-fold>
  2919     // <editor-fold defaultstate="collapsed" desc="Greatest lower bound">
  2920     public Type glb(List<Type> ts) {
  2921         Type t1 = ts.head;
  2922         for (Type t2 : ts.tail) {
  2923             if (t1.isErroneous())
  2924                 return t1;
  2925             t1 = glb(t1, t2);
  2927         return t1;
  2929     //where
  2930     public Type glb(Type t, Type s) {
  2931         if (s == null)
  2932             return t;
  2933         else if (t.isPrimitive() || s.isPrimitive())
  2934             return syms.errType;
  2935         else if (isSubtypeNoCapture(t, s))
  2936             return t;
  2937         else if (isSubtypeNoCapture(s, t))
  2938             return s;
  2940         List<Type> closure = union(closure(t), closure(s));
  2941         List<Type> bounds = closureMin(closure);
  2943         if (bounds.isEmpty()) {             // length == 0
  2944             return syms.objectType;
  2945         } else if (bounds.tail.isEmpty()) { // length == 1
  2946             return bounds.head;
  2947         } else {                            // length > 1
  2948             int classCount = 0;
  2949             for (Type bound : bounds)
  2950                 if (!bound.isInterface())
  2951                     classCount++;
  2952             if (classCount > 1)
  2953                 return createErrorType(t);
  2955         return makeCompoundType(bounds);
  2957     // </editor-fold>
  2959     // <editor-fold defaultstate="collapsed" desc="hashCode">
  2960     /**
  2961      * Compute a hash code on a type.
  2962      */
  2963     public static int hashCode(Type t) {
  2964         return hashCode.visit(t);
  2966     // where
  2967         private static final UnaryVisitor<Integer> hashCode = new UnaryVisitor<Integer>() {
  2969             public Integer visitType(Type t, Void ignored) {
  2970                 return t.tag;
  2973             @Override
  2974             public Integer visitClassType(ClassType t, Void ignored) {
  2975                 int result = visit(t.getEnclosingType());
  2976                 result *= 127;
  2977                 result += t.tsym.flatName().hashCode();
  2978                 for (Type s : t.getTypeArguments()) {
  2979                     result *= 127;
  2980                     result += visit(s);
  2982                 return result;
  2985             @Override
  2986             public Integer visitWildcardType(WildcardType t, Void ignored) {
  2987                 int result = t.kind.hashCode();
  2988                 if (t.type != null) {
  2989                     result *= 127;
  2990                     result += visit(t.type);
  2992                 return result;
  2995             @Override
  2996             public Integer visitArrayType(ArrayType t, Void ignored) {
  2997                 return visit(t.elemtype) + 12;
  3000             @Override
  3001             public Integer visitTypeVar(TypeVar t, Void ignored) {
  3002                 return System.identityHashCode(t.tsym);
  3005             @Override
  3006             public Integer visitUndetVar(UndetVar t, Void ignored) {
  3007                 return System.identityHashCode(t);
  3010             @Override
  3011             public Integer visitErrorType(ErrorType t, Void ignored) {
  3012                 return 0;
  3014         };
  3015     // </editor-fold>
  3017     // <editor-fold defaultstate="collapsed" desc="Return-Type-Substitutable">
  3018     /**
  3019      * Does t have a result that is a subtype of the result type of s,
  3020      * suitable for covariant returns?  It is assumed that both types
  3021      * are (possibly polymorphic) method types.  Monomorphic method
  3022      * types are handled in the obvious way.  Polymorphic method types
  3023      * require renaming all type variables of one to corresponding
  3024      * type variables in the other, where correspondence is by
  3025      * position in the type parameter list. */
  3026     public boolean resultSubtype(Type t, Type s, Warner warner) {
  3027         List<Type> tvars = t.getTypeArguments();
  3028         List<Type> svars = s.getTypeArguments();
  3029         Type tres = t.getReturnType();
  3030         Type sres = subst(s.getReturnType(), svars, tvars);
  3031         return covariantReturnType(tres, sres, warner);
  3034     /**
  3035      * Return-Type-Substitutable.
  3036      * @see <a href="http://java.sun.com/docs/books/jls/">The Java
  3037      * Language Specification, Third Ed. (8.4.5)</a>
  3038      */
  3039     public boolean returnTypeSubstitutable(Type r1, Type r2) {
  3040         if (hasSameArgs(r1, r2))
  3041             return resultSubtype(r1, r2, Warner.noWarnings);
  3042         else
  3043             return covariantReturnType(r1.getReturnType(),
  3044                                        erasure(r2.getReturnType()),
  3045                                        Warner.noWarnings);
  3048     public boolean returnTypeSubstitutable(Type r1,
  3049                                            Type r2, Type r2res,
  3050                                            Warner warner) {
  3051         if (isSameType(r1.getReturnType(), r2res))
  3052             return true;
  3053         if (r1.getReturnType().isPrimitive() || r2res.isPrimitive())
  3054             return false;
  3056         if (hasSameArgs(r1, r2))
  3057             return covariantReturnType(r1.getReturnType(), r2res, warner);
  3058         if (!source.allowCovariantReturns())
  3059             return false;
  3060         if (isSubtypeUnchecked(r1.getReturnType(), r2res, warner))
  3061             return true;
  3062         if (!isSubtype(r1.getReturnType(), erasure(r2res)))
  3063             return false;
  3064         warner.warn(LintCategory.UNCHECKED);
  3065         return true;
  3068     /**
  3069      * Is t an appropriate return type in an overrider for a
  3070      * method that returns s?
  3071      */
  3072     public boolean covariantReturnType(Type t, Type s, Warner warner) {
  3073         return
  3074             isSameType(t, s) ||
  3075             source.allowCovariantReturns() &&
  3076             !t.isPrimitive() &&
  3077             !s.isPrimitive() &&
  3078             isAssignable(t, s, warner);
  3080     // </editor-fold>
  3082     // <editor-fold defaultstate="collapsed" desc="Box/unbox support">
  3083     /**
  3084      * Return the class that boxes the given primitive.
  3085      */
  3086     public ClassSymbol boxedClass(Type t) {
  3087         return reader.enterClass(syms.boxedName[t.tag]);
  3090     /**
  3091      * Return the boxed type if 't' is primitive, otherwise return 't' itself.
  3092      */
  3093     public Type boxedTypeOrType(Type t) {
  3094         return t.isPrimitive() ?
  3095             boxedClass(t).type :
  3096             t;
  3099     /**
  3100      * Return the primitive type corresponding to a boxed type.
  3101      */
  3102     public Type unboxedType(Type t) {
  3103         if (allowBoxing) {
  3104             for (int i=0; i<syms.boxedName.length; i++) {
  3105                 Name box = syms.boxedName[i];
  3106                 if (box != null &&
  3107                     asSuper(t, reader.enterClass(box)) != null)
  3108                     return syms.typeOfTag[i];
  3111         return Type.noType;
  3113     // </editor-fold>
  3115     // <editor-fold defaultstate="collapsed" desc="Capture conversion">
  3116     /*
  3117      * JLS 3rd Ed. 5.1.10 Capture Conversion:
  3119      * Let G name a generic type declaration with n formal type
  3120      * parameters A1 ... An with corresponding bounds U1 ... Un. There
  3121      * exists a capture conversion from G<T1 ... Tn> to G<S1 ... Sn>,
  3122      * where, for 1 <= i <= n:
  3124      * + If Ti is a wildcard type argument (4.5.1) of the form ? then
  3125      *   Si is a fresh type variable whose upper bound is
  3126      *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is the null
  3127      *   type.
  3129      * + If Ti is a wildcard type argument of the form ? extends Bi,
  3130      *   then Si is a fresh type variable whose upper bound is
  3131      *   glb(Bi, Ui[A1 := S1, ..., An := Sn]) and whose lower bound is
  3132      *   the null type, where glb(V1,... ,Vm) is V1 & ... & Vm. It is
  3133      *   a compile-time error if for any two classes (not interfaces)
  3134      *   Vi and Vj,Vi is not a subclass of Vj or vice versa.
  3136      * + If Ti is a wildcard type argument of the form ? super Bi,
  3137      *   then Si is a fresh type variable whose upper bound is
  3138      *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is Bi.
  3140      * + Otherwise, Si = Ti.
  3142      * Capture conversion on any type other than a parameterized type
  3143      * (4.5) acts as an identity conversion (5.1.1). Capture
  3144      * conversions never require a special action at run time and
  3145      * therefore never throw an exception at run time.
  3147      * Capture conversion is not applied recursively.
  3148      */
  3149     /**
  3150      * Capture conversion as specified by JLS 3rd Ed.
  3151      */
  3153     public List<Type> capture(List<Type> ts) {
  3154         List<Type> buf = List.nil();
  3155         for (Type t : ts) {
  3156             buf = buf.prepend(capture(t));
  3158         return buf.reverse();
  3160     public Type capture(Type t) {
  3161         if (t.tag != CLASS)
  3162             return t;
  3163         if (t.getEnclosingType() != Type.noType) {
  3164             Type capturedEncl = capture(t.getEnclosingType());
  3165             if (capturedEncl != t.getEnclosingType()) {
  3166                 Type type1 = memberType(capturedEncl, t.tsym);
  3167                 t = subst(type1, t.tsym.type.getTypeArguments(), t.getTypeArguments());
  3170         ClassType cls = (ClassType)t;
  3171         if (cls.isRaw() || !cls.isParameterized())
  3172             return cls;
  3174         ClassType G = (ClassType)cls.asElement().asType();
  3175         List<Type> A = G.getTypeArguments();
  3176         List<Type> T = cls.getTypeArguments();
  3177         List<Type> S = freshTypeVariables(T);
  3179         List<Type> currentA = A;
  3180         List<Type> currentT = T;
  3181         List<Type> currentS = S;
  3182         boolean captured = false;
  3183         while (!currentA.isEmpty() &&
  3184                !currentT.isEmpty() &&
  3185                !currentS.isEmpty()) {
  3186             if (currentS.head != currentT.head) {
  3187                 captured = true;
  3188                 WildcardType Ti = (WildcardType)currentT.head;
  3189                 Type Ui = currentA.head.getUpperBound();
  3190                 CapturedType Si = (CapturedType)currentS.head;
  3191                 if (Ui == null)
  3192                     Ui = syms.objectType;
  3193                 switch (Ti.kind) {
  3194                 case UNBOUND:
  3195                     Si.bound = subst(Ui, A, S);
  3196                     Si.lower = syms.botType;
  3197                     break;
  3198                 case EXTENDS:
  3199                     Si.bound = glb(Ti.getExtendsBound(), subst(Ui, A, S));
  3200                     Si.lower = syms.botType;
  3201                     break;
  3202                 case SUPER:
  3203                     Si.bound = subst(Ui, A, S);
  3204                     Si.lower = Ti.getSuperBound();
  3205                     break;
  3207                 if (Si.bound == Si.lower)
  3208                     currentS.head = Si.bound;
  3210             currentA = currentA.tail;
  3211             currentT = currentT.tail;
  3212             currentS = currentS.tail;
  3214         if (!currentA.isEmpty() || !currentT.isEmpty() || !currentS.isEmpty())
  3215             return erasure(t); // some "rare" type involved
  3217         if (captured)
  3218             return new ClassType(cls.getEnclosingType(), S, cls.tsym);
  3219         else
  3220             return t;
  3222     // where
  3223         public List<Type> freshTypeVariables(List<Type> types) {
  3224             ListBuffer<Type> result = lb();
  3225             for (Type t : types) {
  3226                 if (t.tag == WILDCARD) {
  3227                     Type bound = ((WildcardType)t).getExtendsBound();
  3228                     if (bound == null)
  3229                         bound = syms.objectType;
  3230                     result.append(new CapturedType(capturedName,
  3231                                                    syms.noSymbol,
  3232                                                    bound,
  3233                                                    syms.botType,
  3234                                                    (WildcardType)t));
  3235                 } else {
  3236                     result.append(t);
  3239             return result.toList();
  3241     // </editor-fold>
  3243     // <editor-fold defaultstate="collapsed" desc="Internal utility methods">
  3244     private List<Type> upperBounds(List<Type> ss) {
  3245         if (ss.isEmpty()) return ss;
  3246         Type head = upperBound(ss.head);
  3247         List<Type> tail = upperBounds(ss.tail);
  3248         if (head != ss.head || tail != ss.tail)
  3249             return tail.prepend(head);
  3250         else
  3251             return ss;
  3254     private boolean sideCast(Type from, Type to, Warner warn) {
  3255         // We are casting from type $from$ to type $to$, which are
  3256         // non-final unrelated types.  This method
  3257         // tries to reject a cast by transferring type parameters
  3258         // from $to$ to $from$ by common superinterfaces.
  3259         boolean reverse = false;
  3260         Type target = to;
  3261         if ((to.tsym.flags() & INTERFACE) == 0) {
  3262             Assert.check((from.tsym.flags() & INTERFACE) != 0);
  3263             reverse = true;
  3264             to = from;
  3265             from = target;
  3267         List<Type> commonSupers = superClosure(to, erasure(from));
  3268         boolean giveWarning = commonSupers.isEmpty();
  3269         // The arguments to the supers could be unified here to
  3270         // get a more accurate analysis
  3271         while (commonSupers.nonEmpty()) {
  3272             Type t1 = asSuper(from, commonSupers.head.tsym);
  3273             Type t2 = commonSupers.head; // same as asSuper(to, commonSupers.head.tsym);
  3274             if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
  3275                 return false;
  3276             giveWarning = giveWarning || (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2));
  3277             commonSupers = commonSupers.tail;
  3279         if (giveWarning && !isReifiable(reverse ? from : to))
  3280             warn.warn(LintCategory.UNCHECKED);
  3281         if (!source.allowCovariantReturns())
  3282             // reject if there is a common method signature with
  3283             // incompatible return types.
  3284             chk.checkCompatibleAbstracts(warn.pos(), from, to);
  3285         return true;
  3288     private boolean sideCastFinal(Type from, Type to, Warner warn) {
  3289         // We are casting from type $from$ to type $to$, which are
  3290         // unrelated types one of which is final and the other of
  3291         // which is an interface.  This method
  3292         // tries to reject a cast by transferring type parameters
  3293         // from the final class to the interface.
  3294         boolean reverse = false;
  3295         Type target = to;
  3296         if ((to.tsym.flags() & INTERFACE) == 0) {
  3297             Assert.check((from.tsym.flags() & INTERFACE) != 0);
  3298             reverse = true;
  3299             to = from;
  3300             from = target;
  3302         Assert.check((from.tsym.flags() & FINAL) != 0);
  3303         Type t1 = asSuper(from, to.tsym);
  3304         if (t1 == null) return false;
  3305         Type t2 = to;
  3306         if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
  3307             return false;
  3308         if (!source.allowCovariantReturns())
  3309             // reject if there is a common method signature with
  3310             // incompatible return types.
  3311             chk.checkCompatibleAbstracts(warn.pos(), from, to);
  3312         if (!isReifiable(target) &&
  3313             (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2)))
  3314             warn.warn(LintCategory.UNCHECKED);
  3315         return true;
  3318     private boolean giveWarning(Type from, Type to) {
  3319         Type subFrom = asSub(from, to.tsym);
  3320         return to.isParameterized() &&
  3321                 (!(isUnbounded(to) ||
  3322                 isSubtype(from, to) ||
  3323                 ((subFrom != null) && containsType(to.allparams(), subFrom.allparams()))));
  3326     private List<Type> superClosure(Type t, Type s) {
  3327         List<Type> cl = List.nil();
  3328         for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
  3329             if (isSubtype(s, erasure(l.head))) {
  3330                 cl = insert(cl, l.head);
  3331             } else {
  3332                 cl = union(cl, superClosure(l.head, s));
  3335         return cl;
  3338     private boolean containsTypeEquivalent(Type t, Type s) {
  3339         return
  3340             isSameType(t, s) || // shortcut
  3341             containsType(t, s) && containsType(s, t);
  3344     // <editor-fold defaultstate="collapsed" desc="adapt">
  3345     /**
  3346      * Adapt a type by computing a substitution which maps a source
  3347      * type to a target type.
  3349      * @param source    the source type
  3350      * @param target    the target type
  3351      * @param from      the type variables of the computed substitution
  3352      * @param to        the types of the computed substitution.
  3353      */
  3354     public void adapt(Type source,
  3355                        Type target,
  3356                        ListBuffer<Type> from,
  3357                        ListBuffer<Type> to) throws AdaptFailure {
  3358         new Adapter(from, to).adapt(source, target);
  3361     class Adapter extends SimpleVisitor<Void, Type> {
  3363         ListBuffer<Type> from;
  3364         ListBuffer<Type> to;
  3365         Map<Symbol,Type> mapping;
  3367         Adapter(ListBuffer<Type> from, ListBuffer<Type> to) {
  3368             this.from = from;
  3369             this.to = to;
  3370             mapping = new HashMap<Symbol,Type>();
  3373         public void adapt(Type source, Type target) throws AdaptFailure {
  3374             visit(source, target);
  3375             List<Type> fromList = from.toList();
  3376             List<Type> toList = to.toList();
  3377             while (!fromList.isEmpty()) {
  3378                 Type val = mapping.get(fromList.head.tsym);
  3379                 if (toList.head != val)
  3380                     toList.head = val;
  3381                 fromList = fromList.tail;
  3382                 toList = toList.tail;
  3386         @Override
  3387         public Void visitClassType(ClassType source, Type target) throws AdaptFailure {
  3388             if (target.tag == CLASS)
  3389                 adaptRecursive(source.allparams(), target.allparams());
  3390             return null;
  3393         @Override
  3394         public Void visitArrayType(ArrayType source, Type target) throws AdaptFailure {
  3395             if (target.tag == ARRAY)
  3396                 adaptRecursive(elemtype(source), elemtype(target));
  3397             return null;
  3400         @Override
  3401         public Void visitWildcardType(WildcardType source, Type target) throws AdaptFailure {
  3402             if (source.isExtendsBound())
  3403                 adaptRecursive(upperBound(source), upperBound(target));
  3404             else if (source.isSuperBound())
  3405                 adaptRecursive(lowerBound(source), lowerBound(target));
  3406             return null;
  3409         @Override
  3410         public Void visitTypeVar(TypeVar source, Type target) throws AdaptFailure {
  3411             // Check to see if there is
  3412             // already a mapping for $source$, in which case
  3413             // the old mapping will be merged with the new
  3414             Type val = mapping.get(source.tsym);
  3415             if (val != null) {
  3416                 if (val.isSuperBound() && target.isSuperBound()) {
  3417                     val = isSubtype(lowerBound(val), lowerBound(target))
  3418                         ? target : val;
  3419                 } else if (val.isExtendsBound() && target.isExtendsBound()) {
  3420                     val = isSubtype(upperBound(val), upperBound(target))
  3421                         ? val : target;
  3422                 } else if (!isSameType(val, target)) {
  3423                     throw new AdaptFailure();
  3425             } else {
  3426                 val = target;
  3427                 from.append(source);
  3428                 to.append(target);
  3430             mapping.put(source.tsym, val);
  3431             return null;
  3434         @Override
  3435         public Void visitType(Type source, Type target) {
  3436             return null;
  3439         private Set<TypePair> cache = new HashSet<TypePair>();
  3441         private void adaptRecursive(Type source, Type target) {
  3442             TypePair pair = new TypePair(source, target);
  3443             if (cache.add(pair)) {
  3444                 try {
  3445                     visit(source, target);
  3446                 } finally {
  3447                     cache.remove(pair);
  3452         private void adaptRecursive(List<Type> source, List<Type> target) {
  3453             if (source.length() == target.length()) {
  3454                 while (source.nonEmpty()) {
  3455                     adaptRecursive(source.head, target.head);
  3456                     source = source.tail;
  3457                     target = target.tail;
  3463     public static class AdaptFailure extends RuntimeException {
  3464         static final long serialVersionUID = -7490231548272701566L;
  3467     private void adaptSelf(Type t,
  3468                            ListBuffer<Type> from,
  3469                            ListBuffer<Type> to) {
  3470         try {
  3471             //if (t.tsym.type != t)
  3472                 adapt(t.tsym.type, t, from, to);
  3473         } catch (AdaptFailure ex) {
  3474             // Adapt should never fail calculating a mapping from
  3475             // t.tsym.type to t as there can be no merge problem.
  3476             throw new AssertionError(ex);
  3479     // </editor-fold>
  3481     /**
  3482      * Rewrite all type variables (universal quantifiers) in the given
  3483      * type to wildcards (existential quantifiers).  This is used to
  3484      * determine if a cast is allowed.  For example, if high is true
  3485      * and {@code T <: Number}, then {@code List<T>} is rewritten to
  3486      * {@code List<?  extends Number>}.  Since {@code List<Integer> <:
  3487      * List<? extends Number>} a {@code List<T>} can be cast to {@code
  3488      * List<Integer>} with a warning.
  3489      * @param t a type
  3490      * @param high if true return an upper bound; otherwise a lower
  3491      * bound
  3492      * @param rewriteTypeVars only rewrite captured wildcards if false;
  3493      * otherwise rewrite all type variables
  3494      * @return the type rewritten with wildcards (existential
  3495      * quantifiers) only
  3496      */
  3497     private Type rewriteQuantifiers(Type t, boolean high, boolean rewriteTypeVars) {
  3498         return new Rewriter(high, rewriteTypeVars).visit(t);
  3501     class Rewriter extends UnaryVisitor<Type> {
  3503         boolean high;
  3504         boolean rewriteTypeVars;
  3506         Rewriter(boolean high, boolean rewriteTypeVars) {
  3507             this.high = high;
  3508             this.rewriteTypeVars = rewriteTypeVars;
  3511         @Override
  3512         public Type visitClassType(ClassType t, Void s) {
  3513             ListBuffer<Type> rewritten = new ListBuffer<Type>();
  3514             boolean changed = false;
  3515             for (Type arg : t.allparams()) {
  3516                 Type bound = visit(arg);
  3517                 if (arg != bound) {
  3518                     changed = true;
  3520                 rewritten.append(bound);
  3522             if (changed)
  3523                 return subst(t.tsym.type,
  3524                         t.tsym.type.allparams(),
  3525                         rewritten.toList());
  3526             else
  3527                 return t;
  3530         public Type visitType(Type t, Void s) {
  3531             return high ? upperBound(t) : lowerBound(t);
  3534         @Override
  3535         public Type visitCapturedType(CapturedType t, Void s) {
  3536             Type bound = visitWildcardType(t.wildcard, null);
  3537             return (bound.contains(t)) ?
  3538                     erasure(bound) :
  3539                     bound;
  3542         @Override
  3543         public Type visitTypeVar(TypeVar t, Void s) {
  3544             if (rewriteTypeVars) {
  3545                 Type bound = high ?
  3546                     (t.bound.contains(t) ?
  3547                         erasure(t.bound) :
  3548                         visit(t.bound)) :
  3549                     syms.botType;
  3550                 return rewriteAsWildcardType(bound, t);
  3552             else
  3553                 return t;
  3556         @Override
  3557         public Type visitWildcardType(WildcardType t, Void s) {
  3558             Type bound = high ? t.getExtendsBound() :
  3559                                 t.getSuperBound();
  3560             if (bound == null)
  3561             bound = high ? syms.objectType : syms.botType;
  3562             return rewriteAsWildcardType(visit(bound), t.bound);
  3565         private Type rewriteAsWildcardType(Type bound, TypeVar formal) {
  3566             return high ?
  3567                 makeExtendsWildcard(B(bound), formal) :
  3568                 makeSuperWildcard(B(bound), formal);
  3571         Type B(Type t) {
  3572             while (t.tag == WILDCARD) {
  3573                 WildcardType w = (WildcardType)t;
  3574                 t = high ?
  3575                     w.getExtendsBound() :
  3576                     w.getSuperBound();
  3577                 if (t == null) {
  3578                     t = high ? syms.objectType : syms.botType;
  3581             return t;
  3586     /**
  3587      * Create a wildcard with the given upper (extends) bound; create
  3588      * an unbounded wildcard if bound is Object.
  3590      * @param bound the upper bound
  3591      * @param formal the formal type parameter that will be
  3592      * substituted by the wildcard
  3593      */
  3594     private WildcardType makeExtendsWildcard(Type bound, TypeVar formal) {
  3595         if (bound == syms.objectType) {
  3596             return new WildcardType(syms.objectType,
  3597                                     BoundKind.UNBOUND,
  3598                                     syms.boundClass,
  3599                                     formal);
  3600         } else {
  3601             return new WildcardType(bound,
  3602                                     BoundKind.EXTENDS,
  3603                                     syms.boundClass,
  3604                                     formal);
  3608     /**
  3609      * Create a wildcard with the given lower (super) bound; create an
  3610      * unbounded wildcard if bound is bottom (type of {@code null}).
  3612      * @param bound the lower bound
  3613      * @param formal the formal type parameter that will be
  3614      * substituted by the wildcard
  3615      */
  3616     private WildcardType makeSuperWildcard(Type bound, TypeVar formal) {
  3617         if (bound.tag == BOT) {
  3618             return new WildcardType(syms.objectType,
  3619                                     BoundKind.UNBOUND,
  3620                                     syms.boundClass,
  3621                                     formal);
  3622         } else {
  3623             return new WildcardType(bound,
  3624                                     BoundKind.SUPER,
  3625                                     syms.boundClass,
  3626                                     formal);
  3630     /**
  3631      * A wrapper for a type that allows use in sets.
  3632      */
  3633     class SingletonType {
  3634         final Type t;
  3635         SingletonType(Type t) {
  3636             this.t = t;
  3638         public int hashCode() {
  3639             return Types.hashCode(t);
  3641         public boolean equals(Object obj) {
  3642             return (obj instanceof SingletonType) &&
  3643                 isSameType(t, ((SingletonType)obj).t);
  3645         public String toString() {
  3646             return t.toString();
  3649     // </editor-fold>
  3651     // <editor-fold defaultstate="collapsed" desc="Visitors">
  3652     /**
  3653      * A default visitor for types.  All visitor methods except
  3654      * visitType are implemented by delegating to visitType.  Concrete
  3655      * subclasses must provide an implementation of visitType and can
  3656      * override other methods as needed.
  3658      * @param <R> the return type of the operation implemented by this
  3659      * visitor; use Void if no return type is needed.
  3660      * @param <S> the type of the second argument (the first being the
  3661      * type itself) of the operation implemented by this visitor; use
  3662      * Void if a second argument is not needed.
  3663      */
  3664     public static abstract class DefaultTypeVisitor<R,S> implements Type.Visitor<R,S> {
  3665         final public R visit(Type t, S s)               { return t.accept(this, s); }
  3666         public R visitClassType(ClassType t, S s)       { return visitType(t, s); }
  3667         public R visitWildcardType(WildcardType t, S s) { return visitType(t, s); }
  3668         public R visitArrayType(ArrayType t, S s)       { return visitType(t, s); }
  3669         public R visitMethodType(MethodType t, S s)     { return visitType(t, s); }
  3670         public R visitPackageType(PackageType t, S s)   { return visitType(t, s); }
  3671         public R visitTypeVar(TypeVar t, S s)           { return visitType(t, s); }
  3672         public R visitCapturedType(CapturedType t, S s) { return visitType(t, s); }
  3673         public R visitForAll(ForAll t, S s)             { return visitType(t, s); }
  3674         public R visitUndetVar(UndetVar t, S s)         { return visitType(t, s); }
  3675         public R visitErrorType(ErrorType t, S s)       { return visitType(t, s); }
  3678     /**
  3679      * A default visitor for symbols.  All visitor methods except
  3680      * visitSymbol are implemented by delegating to visitSymbol.  Concrete
  3681      * subclasses must provide an implementation of visitSymbol and can
  3682      * override other methods as needed.
  3684      * @param <R> the return type of the operation implemented by this
  3685      * visitor; use Void if no return type is needed.
  3686      * @param <S> the type of the second argument (the first being the
  3687      * symbol itself) of the operation implemented by this visitor; use
  3688      * Void if a second argument is not needed.
  3689      */
  3690     public static abstract class DefaultSymbolVisitor<R,S> implements Symbol.Visitor<R,S> {
  3691         final public R visit(Symbol s, S arg)                   { return s.accept(this, arg); }
  3692         public R visitClassSymbol(ClassSymbol s, S arg)         { return visitSymbol(s, arg); }
  3693         public R visitMethodSymbol(MethodSymbol s, S arg)       { return visitSymbol(s, arg); }
  3694         public R visitOperatorSymbol(OperatorSymbol s, S arg)   { return visitSymbol(s, arg); }
  3695         public R visitPackageSymbol(PackageSymbol s, S arg)     { return visitSymbol(s, arg); }
  3696         public R visitTypeSymbol(TypeSymbol s, S arg)           { return visitSymbol(s, arg); }
  3697         public R visitVarSymbol(VarSymbol s, S arg)             { return visitSymbol(s, arg); }
  3700     /**
  3701      * A <em>simple</em> visitor for types.  This visitor is simple as
  3702      * captured wildcards, for-all types (generic methods), and
  3703      * undetermined type variables (part of inference) are hidden.
  3704      * Captured wildcards are hidden by treating them as type
  3705      * variables and the rest are hidden by visiting their qtypes.
  3707      * @param <R> the return type of the operation implemented by this
  3708      * visitor; use Void if no return type is needed.
  3709      * @param <S> the type of the second argument (the first being the
  3710      * type itself) of the operation implemented by this visitor; use
  3711      * Void if a second argument is not needed.
  3712      */
  3713     public static abstract class SimpleVisitor<R,S> extends DefaultTypeVisitor<R,S> {
  3714         @Override
  3715         public R visitCapturedType(CapturedType t, S s) {
  3716             return visitTypeVar(t, s);
  3718         @Override
  3719         public R visitForAll(ForAll t, S s) {
  3720             return visit(t.qtype, s);
  3722         @Override
  3723         public R visitUndetVar(UndetVar t, S s) {
  3724             return visit(t.qtype, s);
  3728     /**
  3729      * A plain relation on types.  That is a 2-ary function on the
  3730      * form Type&nbsp;&times;&nbsp;Type&nbsp;&rarr;&nbsp;Boolean.
  3731      * <!-- In plain text: Type x Type -> Boolean -->
  3732      */
  3733     public static abstract class TypeRelation extends SimpleVisitor<Boolean,Type> {}
  3735     /**
  3736      * A convenience visitor for implementing operations that only
  3737      * require one argument (the type itself), that is, unary
  3738      * operations.
  3740      * @param <R> the return type of the operation implemented by this
  3741      * visitor; use Void if no return type is needed.
  3742      */
  3743     public static abstract class UnaryVisitor<R> extends SimpleVisitor<R,Void> {
  3744         final public R visit(Type t) { return t.accept(this, null); }
  3747     /**
  3748      * A visitor for implementing a mapping from types to types.  The
  3749      * default behavior of this class is to implement the identity
  3750      * mapping (mapping a type to itself).  This can be overridden in
  3751      * subclasses.
  3753      * @param <S> the type of the second argument (the first being the
  3754      * type itself) of this mapping; use Void if a second argument is
  3755      * not needed.
  3756      */
  3757     public static class MapVisitor<S> extends DefaultTypeVisitor<Type,S> {
  3758         final public Type visit(Type t) { return t.accept(this, null); }
  3759         public Type visitType(Type t, S s) { return t; }
  3761     // </editor-fold>
  3764     // <editor-fold defaultstate="collapsed" desc="Annotation support">
  3766     public RetentionPolicy getRetention(Attribute.Compound a) {
  3767         RetentionPolicy vis = RetentionPolicy.CLASS; // the default
  3768         Attribute.Compound c = a.type.tsym.attribute(syms.retentionType.tsym);
  3769         if (c != null) {
  3770             Attribute value = c.member(names.value);
  3771             if (value != null && value instanceof Attribute.Enum) {
  3772                 Name levelName = ((Attribute.Enum)value).value.name;
  3773                 if (levelName == names.SOURCE) vis = RetentionPolicy.SOURCE;
  3774                 else if (levelName == names.CLASS) vis = RetentionPolicy.CLASS;
  3775                 else if (levelName == names.RUNTIME) vis = RetentionPolicy.RUNTIME;
  3776                 else ;// /* fail soft */ throw new AssertionError(levelName);
  3779         return vis;
  3781     // </editor-fold>

mercurial