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

Tue, 23 Nov 2010 11:08:43 +0000

author
mcimadamore
date
Tue, 23 Nov 2010 11:08:43 +0000
changeset 753
2536dedd897e
parent 736
e9e41c88b03e
child 779
5ef88773462b
permissions
-rw-r--r--

6995200: JDK 7 compiler crashes when type-variable is inferred from expected primitive type
Summary: 15.12.2.8 should use boxing when expected type in assignment context is a primitive type
Reviewed-by: jjg

     1 /*
     2  * Copyright (c) 2003, 2009, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    26 package com.sun.tools.javac.code;
    28 import java.lang.ref.SoftReference;
    29 import java.util.*;
    31 import com.sun.tools.javac.util.*;
    32 import com.sun.tools.javac.util.List;
    34 import com.sun.tools.javac.jvm.ClassReader;
    35 import com.sun.tools.javac.code.Attribute.RetentionPolicy;
    36 import com.sun.tools.javac.comp.Check;
    38 import static com.sun.tools.javac.code.Type.*;
    39 import static com.sun.tools.javac.code.TypeTags.*;
    40 import static com.sun.tools.javac.code.Symbol.*;
    41 import static com.sun.tools.javac.code.Flags.*;
    42 import static com.sun.tools.javac.code.BoundKind.*;
    43 import static com.sun.tools.javac.util.ListBuffer.lb;
    45 /**
    46  * Utility class containing various operations on types.
    47  *
    48  * <p>Unless other names are more illustrative, the following naming
    49  * conventions should be observed in this file:
    50  *
    51  * <dl>
    52  * <dt>t</dt>
    53  * <dd>If the first argument to an operation is a type, it should be named t.</dd>
    54  * <dt>s</dt>
    55  * <dd>Similarly, if the second argument to an operation is a type, it should be named s.</dd>
    56  * <dt>ts</dt>
    57  * <dd>If an operations takes a list of types, the first should be named ts.</dd>
    58  * <dt>ss</dt>
    59  * <dd>A second list of types should be named ss.</dd>
    60  * </dl>
    61  *
    62  * <p><b>This is NOT part of any supported API.
    63  * If you write code that depends on this, you do so at your own risk.
    64  * This code and its internal interfaces are subject to change or
    65  * deletion without notice.</b>
    66  */
    67 public class Types {
    68     protected static final Context.Key<Types> typesKey =
    69         new Context.Key<Types>();
    71     final Symtab syms;
    72     final Scope.ScopeCounter scopeCounter;
    73     final JavacMessages messages;
    74     final Names names;
    75     final boolean allowBoxing;
    76     final ClassReader reader;
    77     final Source source;
    78     final Check chk;
    79     List<Warner> warnStack = List.nil();
    80     final Name capturedName;
    82     // <editor-fold defaultstate="collapsed" desc="Instantiating">
    83     public static Types instance(Context context) {
    84         Types instance = context.get(typesKey);
    85         if (instance == null)
    86             instance = new Types(context);
    87         return instance;
    88     }
    90     protected Types(Context context) {
    91         context.put(typesKey, this);
    92         syms = Symtab.instance(context);
    93         scopeCounter = Scope.ScopeCounter.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             return isSubtypeUnchecked(t, s, warn);
   277         if (!allowBoxing) return false;
   278         return tPrimitive
   279             ? isSubtype(boxedClass(t).type, s)
   280             : isSubtype(unboxedType(t), s);
   281     }
   283     /**
   284      * Is t a subtype of or convertiable via boxing/unboxing
   285      * convertions to s?
   286      */
   287     public boolean isConvertible(Type t, Type s) {
   288         return isConvertible(t, s, Warner.noWarnings);
   289     }
   290     // </editor-fold>
   292     // <editor-fold defaultstate="collapsed" desc="isSubtype">
   293     /**
   294      * Is t an unchecked subtype of s?
   295      */
   296     public boolean isSubtypeUnchecked(Type t, Type s) {
   297         return isSubtypeUnchecked(t, s, Warner.noWarnings);
   298     }
   299     /**
   300      * Is t an unchecked subtype of s?
   301      */
   302     public boolean isSubtypeUnchecked(Type t, Type s, Warner warn) {
   303         if (t.tag == ARRAY && s.tag == ARRAY) {
   304             return (((ArrayType)t).elemtype.tag <= lastBaseTag)
   305                 ? isSameType(elemtype(t), elemtype(s))
   306                 : isSubtypeUnchecked(elemtype(t), elemtype(s), warn);
   307         } else if (isSubtype(t, s)) {
   308             return true;
   309         }
   310         else if (t.tag == TYPEVAR) {
   311             return isSubtypeUnchecked(t.getUpperBound(), s, warn);
   312         }
   313         else if (s.tag == UNDETVAR) {
   314             UndetVar uv = (UndetVar)s;
   315             if (uv.inst != null)
   316                 return isSubtypeUnchecked(t, uv.inst, warn);
   317         }
   318         else if (!s.isRaw()) {
   319             Type t2 = asSuper(t, s.tsym);
   320             if (t2 != null && t2.isRaw()) {
   321                 if (isReifiable(s))
   322                     warn.silentUnchecked();
   323                 else
   324                     warn.warnUnchecked();
   325                 return true;
   326             }
   327         }
   328         return false;
   329     }
   331     /**
   332      * Is t a subtype of s?<br>
   333      * (not defined for Method and ForAll types)
   334      */
   335     final public boolean isSubtype(Type t, Type s) {
   336         return isSubtype(t, s, true);
   337     }
   338     final public boolean isSubtypeNoCapture(Type t, Type s) {
   339         return isSubtype(t, s, false);
   340     }
   341     public boolean isSubtype(Type t, Type s, boolean capture) {
   342         if (t == s)
   343             return true;
   345         if (s.tag >= firstPartialTag)
   346             return isSuperType(s, t);
   348         if (s.isCompound()) {
   349             for (Type s2 : interfaces(s).prepend(supertype(s))) {
   350                 if (!isSubtype(t, s2, capture))
   351                     return false;
   352             }
   353             return true;
   354         }
   356         Type lower = lowerBound(s);
   357         if (s != lower)
   358             return isSubtype(capture ? capture(t) : t, lower, false);
   360         return isSubtype.visit(capture ? capture(t) : t, s);
   361     }
   362     // where
   363         private TypeRelation isSubtype = new TypeRelation()
   364         {
   365             public Boolean visitType(Type t, Type s) {
   366                 switch (t.tag) {
   367                 case BYTE: case CHAR:
   368                     return (t.tag == s.tag ||
   369                               t.tag + 2 <= s.tag && s.tag <= DOUBLE);
   370                 case SHORT: case INT: case LONG: case FLOAT: case DOUBLE:
   371                     return t.tag <= s.tag && s.tag <= DOUBLE;
   372                 case BOOLEAN: case VOID:
   373                     return t.tag == s.tag;
   374                 case TYPEVAR:
   375                     return isSubtypeNoCapture(t.getUpperBound(), s);
   376                 case BOT:
   377                     return
   378                         s.tag == BOT || s.tag == CLASS ||
   379                         s.tag == ARRAY || s.tag == TYPEVAR;
   380                 case NONE:
   381                     return false;
   382                 default:
   383                     throw new AssertionError("isSubtype " + t.tag);
   384                 }
   385             }
   387             private Set<TypePair> cache = new HashSet<TypePair>();
   389             private boolean containsTypeRecursive(Type t, Type s) {
   390                 TypePair pair = new TypePair(t, s);
   391                 if (cache.add(pair)) {
   392                     try {
   393                         return containsType(t.getTypeArguments(),
   394                                             s.getTypeArguments());
   395                     } finally {
   396                         cache.remove(pair);
   397                     }
   398                 } else {
   399                     return containsType(t.getTypeArguments(),
   400                                         rewriteSupers(s).getTypeArguments());
   401                 }
   402             }
   404             private Type rewriteSupers(Type t) {
   405                 if (!t.isParameterized())
   406                     return t;
   407                 ListBuffer<Type> from = lb();
   408                 ListBuffer<Type> to = lb();
   409                 adaptSelf(t, from, to);
   410                 if (from.isEmpty())
   411                     return t;
   412                 ListBuffer<Type> rewrite = lb();
   413                 boolean changed = false;
   414                 for (Type orig : to.toList()) {
   415                     Type s = rewriteSupers(orig);
   416                     if (s.isSuperBound() && !s.isExtendsBound()) {
   417                         s = new WildcardType(syms.objectType,
   418                                              BoundKind.UNBOUND,
   419                                              syms.boundClass);
   420                         changed = true;
   421                     } else if (s != orig) {
   422                         s = new WildcardType(upperBound(s),
   423                                              BoundKind.EXTENDS,
   424                                              syms.boundClass);
   425                         changed = true;
   426                     }
   427                     rewrite.append(s);
   428                 }
   429                 if (changed)
   430                     return subst(t.tsym.type, from.toList(), rewrite.toList());
   431                 else
   432                     return t;
   433             }
   435             @Override
   436             public Boolean visitClassType(ClassType t, Type s) {
   437                 Type sup = asSuper(t, s.tsym);
   438                 return sup != null
   439                     && sup.tsym == s.tsym
   440                     // You're not allowed to write
   441                     //     Vector<Object> vec = new Vector<String>();
   442                     // But with wildcards you can write
   443                     //     Vector<? extends Object> vec = new Vector<String>();
   444                     // which means that subtype checking must be done
   445                     // here instead of same-type checking (via containsType).
   446                     && (!s.isParameterized() || containsTypeRecursive(s, sup))
   447                     && isSubtypeNoCapture(sup.getEnclosingType(),
   448                                           s.getEnclosingType());
   449             }
   451             @Override
   452             public Boolean visitArrayType(ArrayType t, Type s) {
   453                 if (s.tag == ARRAY) {
   454                     if (t.elemtype.tag <= lastBaseTag)
   455                         return isSameType(t.elemtype, elemtype(s));
   456                     else
   457                         return isSubtypeNoCapture(t.elemtype, elemtype(s));
   458                 }
   460                 if (s.tag == CLASS) {
   461                     Name sname = s.tsym.getQualifiedName();
   462                     return sname == names.java_lang_Object
   463                         || sname == names.java_lang_Cloneable
   464                         || sname == names.java_io_Serializable;
   465                 }
   467                 return false;
   468             }
   470             @Override
   471             public Boolean visitUndetVar(UndetVar t, Type s) {
   472                 //todo: test against origin needed? or replace with substitution?
   473                 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN)
   474                     return true;
   476                 if (t.inst != null)
   477                     return isSubtypeNoCapture(t.inst, s); // TODO: ", warn"?
   479                 t.hibounds = t.hibounds.prepend(s);
   480                 return true;
   481             }
   483             @Override
   484             public Boolean visitErrorType(ErrorType t, Type s) {
   485                 return true;
   486             }
   487         };
   489     /**
   490      * Is t a subtype of every type in given list `ts'?<br>
   491      * (not defined for Method and ForAll types)<br>
   492      * Allows unchecked conversions.
   493      */
   494     public boolean isSubtypeUnchecked(Type t, List<Type> ts, Warner warn) {
   495         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
   496             if (!isSubtypeUnchecked(t, l.head, warn))
   497                 return false;
   498         return true;
   499     }
   501     /**
   502      * Are corresponding elements of ts subtypes of ss?  If lists are
   503      * of different length, return false.
   504      */
   505     public boolean isSubtypes(List<Type> ts, List<Type> ss) {
   506         while (ts.tail != null && ss.tail != null
   507                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   508                isSubtype(ts.head, ss.head)) {
   509             ts = ts.tail;
   510             ss = ss.tail;
   511         }
   512         return ts.tail == null && ss.tail == null;
   513         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   514     }
   516     /**
   517      * Are corresponding elements of ts subtypes of ss, allowing
   518      * unchecked conversions?  If lists are of different length,
   519      * return false.
   520      **/
   521     public boolean isSubtypesUnchecked(List<Type> ts, List<Type> ss, Warner warn) {
   522         while (ts.tail != null && ss.tail != null
   523                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   524                isSubtypeUnchecked(ts.head, ss.head, warn)) {
   525             ts = ts.tail;
   526             ss = ss.tail;
   527         }
   528         return ts.tail == null && ss.tail == null;
   529         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   530     }
   531     // </editor-fold>
   533     // <editor-fold defaultstate="collapsed" desc="isSuperType">
   534     /**
   535      * Is t a supertype of s?
   536      */
   537     public boolean isSuperType(Type t, Type s) {
   538         switch (t.tag) {
   539         case ERROR:
   540             return true;
   541         case UNDETVAR: {
   542             UndetVar undet = (UndetVar)t;
   543             if (t == s ||
   544                 undet.qtype == s ||
   545                 s.tag == ERROR ||
   546                 s.tag == BOT) return true;
   547             if (undet.inst != null)
   548                 return isSubtype(s, undet.inst);
   549             undet.lobounds = undet.lobounds.prepend(s);
   550             return true;
   551         }
   552         default:
   553             return isSubtype(s, t);
   554         }
   555     }
   556     // </editor-fold>
   558     // <editor-fold defaultstate="collapsed" desc="isSameType">
   559     /**
   560      * Are corresponding elements of the lists the same type?  If
   561      * lists are of different length, return false.
   562      */
   563     public boolean isSameTypes(List<Type> ts, List<Type> ss) {
   564         while (ts.tail != null && ss.tail != null
   565                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   566                isSameType(ts.head, ss.head)) {
   567             ts = ts.tail;
   568             ss = ss.tail;
   569         }
   570         return ts.tail == null && ss.tail == null;
   571         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   572     }
   574     /**
   575      * Is t the same type as s?
   576      */
   577     public boolean isSameType(Type t, Type s) {
   578         return isSameType.visit(t, s);
   579     }
   580     // where
   581         private TypeRelation isSameType = new TypeRelation() {
   583             public Boolean visitType(Type t, Type s) {
   584                 if (t == s)
   585                     return true;
   587                 if (s.tag >= firstPartialTag)
   588                     return visit(s, t);
   590                 switch (t.tag) {
   591                 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
   592                 case DOUBLE: case BOOLEAN: case VOID: case BOT: case NONE:
   593                     return t.tag == s.tag;
   594                 case TYPEVAR: {
   595                     if (s.tag == TYPEVAR) {
   596                         //type-substitution does not preserve type-var types
   597                         //check that type var symbols and bounds are indeed the same
   598                         return t.tsym == s.tsym &&
   599                                 visit(t.getUpperBound(), s.getUpperBound());
   600                     }
   601                     else {
   602                         //special case for s == ? super X, where upper(s) = u
   603                         //check that u == t, where u has been set by Type.withTypeVar
   604                         return s.isSuperBound() &&
   605                                 !s.isExtendsBound() &&
   606                                 visit(t, upperBound(s));
   607                     }
   608                 }
   609                 default:
   610                     throw new AssertionError("isSameType " + t.tag);
   611                 }
   612             }
   614             @Override
   615             public Boolean visitWildcardType(WildcardType t, Type s) {
   616                 if (s.tag >= firstPartialTag)
   617                     return visit(s, t);
   618                 else
   619                     return false;
   620             }
   622             @Override
   623             public Boolean visitClassType(ClassType t, Type s) {
   624                 if (t == s)
   625                     return true;
   627                 if (s.tag >= firstPartialTag)
   628                     return visit(s, t);
   630                 if (s.isSuperBound() && !s.isExtendsBound())
   631                     return visit(t, upperBound(s)) && visit(t, lowerBound(s));
   633                 if (t.isCompound() && s.isCompound()) {
   634                     if (!visit(supertype(t), supertype(s)))
   635                         return false;
   637                     HashSet<SingletonType> set = new HashSet<SingletonType>();
   638                     for (Type x : interfaces(t))
   639                         set.add(new SingletonType(x));
   640                     for (Type x : interfaces(s)) {
   641                         if (!set.remove(new SingletonType(x)))
   642                             return false;
   643                     }
   644                     return (set.size() == 0);
   645                 }
   646                 return t.tsym == s.tsym
   647                     && visit(t.getEnclosingType(), s.getEnclosingType())
   648                     && containsTypeEquivalent(t.getTypeArguments(), s.getTypeArguments());
   649             }
   651             @Override
   652             public Boolean visitArrayType(ArrayType t, Type s) {
   653                 if (t == s)
   654                     return true;
   656                 if (s.tag >= firstPartialTag)
   657                     return visit(s, t);
   659                 return s.tag == ARRAY
   660                     && containsTypeEquivalent(t.elemtype, elemtype(s));
   661             }
   663             @Override
   664             public Boolean visitMethodType(MethodType t, Type s) {
   665                 // isSameType for methods does not take thrown
   666                 // exceptions into account!
   667                 return hasSameArgs(t, s) && visit(t.getReturnType(), s.getReturnType());
   668             }
   670             @Override
   671             public Boolean visitPackageType(PackageType t, Type s) {
   672                 return t == s;
   673             }
   675             @Override
   676             public Boolean visitForAll(ForAll t, Type s) {
   677                 if (s.tag != FORALL)
   678                     return false;
   680                 ForAll forAll = (ForAll)s;
   681                 return hasSameBounds(t, forAll)
   682                     && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
   683             }
   685             @Override
   686             public Boolean visitUndetVar(UndetVar t, Type s) {
   687                 if (s.tag == WILDCARD)
   688                     // FIXME, this might be leftovers from before capture conversion
   689                     return false;
   691                 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN)
   692                     return true;
   694                 if (t.inst != null)
   695                     return visit(t.inst, s);
   697                 t.inst = fromUnknownFun.apply(s);
   698                 for (List<Type> l = t.lobounds; l.nonEmpty(); l = l.tail) {
   699                     if (!isSubtype(l.head, t.inst))
   700                         return false;
   701                 }
   702                 for (List<Type> l = t.hibounds; l.nonEmpty(); l = l.tail) {
   703                     if (!isSubtype(t.inst, l.head))
   704                         return false;
   705                 }
   706                 return true;
   707             }
   709             @Override
   710             public Boolean visitErrorType(ErrorType t, Type s) {
   711                 return true;
   712             }
   713         };
   714     // </editor-fold>
   716     // <editor-fold defaultstate="collapsed" desc="fromUnknownFun">
   717     /**
   718      * A mapping that turns all unknown types in this type to fresh
   719      * unknown variables.
   720      */
   721     public Mapping fromUnknownFun = new Mapping("fromUnknownFun") {
   722             public Type apply(Type t) {
   723                 if (t.tag == UNKNOWN) return new UndetVar(t);
   724                 else return t.map(this);
   725             }
   726         };
   727     // </editor-fold>
   729     // <editor-fold defaultstate="collapsed" desc="Contains Type">
   730     public boolean containedBy(Type t, Type s) {
   731         switch (t.tag) {
   732         case UNDETVAR:
   733             if (s.tag == WILDCARD) {
   734                 UndetVar undetvar = (UndetVar)t;
   735                 WildcardType wt = (WildcardType)s;
   736                 switch(wt.kind) {
   737                     case UNBOUND: //similar to ? extends Object
   738                     case EXTENDS: {
   739                         Type bound = upperBound(s);
   740                         // We should check the new upper bound against any of the
   741                         // undetvar's lower bounds.
   742                         for (Type t2 : undetvar.lobounds) {
   743                             if (!isSubtype(t2, bound))
   744                                 return false;
   745                         }
   746                         undetvar.hibounds = undetvar.hibounds.prepend(bound);
   747                         break;
   748                     }
   749                     case SUPER: {
   750                         Type bound = lowerBound(s);
   751                         // We should check the new lower bound against any of the
   752                         // undetvar's lower bounds.
   753                         for (Type t2 : undetvar.hibounds) {
   754                             if (!isSubtype(bound, t2))
   755                                 return false;
   756                         }
   757                         undetvar.lobounds = undetvar.lobounds.prepend(bound);
   758                         break;
   759                     }
   760                 }
   761                 return true;
   762             } else {
   763                 return isSameType(t, s);
   764             }
   765         case ERROR:
   766             return true;
   767         default:
   768             return containsType(s, t);
   769         }
   770     }
   772     boolean containsType(List<Type> ts, List<Type> ss) {
   773         while (ts.nonEmpty() && ss.nonEmpty()
   774                && containsType(ts.head, ss.head)) {
   775             ts = ts.tail;
   776             ss = ss.tail;
   777         }
   778         return ts.isEmpty() && ss.isEmpty();
   779     }
   781     /**
   782      * Check if t contains s.
   783      *
   784      * <p>T contains S if:
   785      *
   786      * <p>{@code L(T) <: L(S) && U(S) <: U(T)}
   787      *
   788      * <p>This relation is only used by ClassType.isSubtype(), that
   789      * is,
   790      *
   791      * <p>{@code C<S> <: C<T> if T contains S.}
   792      *
   793      * <p>Because of F-bounds, this relation can lead to infinite
   794      * recursion.  Thus we must somehow break that recursion.  Notice
   795      * that containsType() is only called from ClassType.isSubtype().
   796      * Since the arguments have already been checked against their
   797      * bounds, we know:
   798      *
   799      * <p>{@code U(S) <: U(T) if T is "super" bound (U(T) *is* the bound)}
   800      *
   801      * <p>{@code L(T) <: L(S) if T is "extends" bound (L(T) is bottom)}
   802      *
   803      * @param t a type
   804      * @param s a type
   805      */
   806     public boolean containsType(Type t, Type s) {
   807         return containsType.visit(t, s);
   808     }
   809     // where
   810         private TypeRelation containsType = new TypeRelation() {
   812             private Type U(Type t) {
   813                 while (t.tag == WILDCARD) {
   814                     WildcardType w = (WildcardType)t;
   815                     if (w.isSuperBound())
   816                         return w.bound == null ? syms.objectType : w.bound.bound;
   817                     else
   818                         t = w.type;
   819                 }
   820                 return t;
   821             }
   823             private Type L(Type t) {
   824                 while (t.tag == WILDCARD) {
   825                     WildcardType w = (WildcardType)t;
   826                     if (w.isExtendsBound())
   827                         return syms.botType;
   828                     else
   829                         t = w.type;
   830                 }
   831                 return t;
   832             }
   834             public Boolean visitType(Type t, Type s) {
   835                 if (s.tag >= firstPartialTag)
   836                     return containedBy(s, t);
   837                 else
   838                     return isSameType(t, s);
   839             }
   841             void debugContainsType(WildcardType t, Type s) {
   842                 System.err.println();
   843                 System.err.format(" does %s contain %s?%n", t, s);
   844                 System.err.format(" %s U(%s) <: U(%s) %s = %s%n",
   845                                   upperBound(s), s, t, U(t),
   846                                   t.isSuperBound()
   847                                   || isSubtypeNoCapture(upperBound(s), U(t)));
   848                 System.err.format(" %s L(%s) <: L(%s) %s = %s%n",
   849                                   L(t), t, s, lowerBound(s),
   850                                   t.isExtendsBound()
   851                                   || isSubtypeNoCapture(L(t), lowerBound(s)));
   852                 System.err.println();
   853             }
   855             @Override
   856             public Boolean visitWildcardType(WildcardType t, Type s) {
   857                 if (s.tag >= firstPartialTag)
   858                     return containedBy(s, t);
   859                 else {
   860                     // debugContainsType(t, s);
   861                     return isSameWildcard(t, s)
   862                         || isCaptureOf(s, t)
   863                         || ((t.isExtendsBound() || isSubtypeNoCapture(L(t), lowerBound(s))) &&
   864                             (t.isSuperBound() || isSubtypeNoCapture(upperBound(s), U(t))));
   865                 }
   866             }
   868             @Override
   869             public Boolean visitUndetVar(UndetVar t, Type s) {
   870                 if (s.tag != WILDCARD)
   871                     return isSameType(t, s);
   872                 else
   873                     return false;
   874             }
   876             @Override
   877             public Boolean visitErrorType(ErrorType t, Type s) {
   878                 return true;
   879             }
   880         };
   882     public boolean isCaptureOf(Type s, WildcardType t) {
   883         if (s.tag != TYPEVAR || !((TypeVar)s).isCaptured())
   884             return false;
   885         return isSameWildcard(t, ((CapturedType)s).wildcard);
   886     }
   888     public boolean isSameWildcard(WildcardType t, Type s) {
   889         if (s.tag != WILDCARD)
   890             return false;
   891         WildcardType w = (WildcardType)s;
   892         return w.kind == t.kind && w.type == t.type;
   893     }
   895     public boolean containsTypeEquivalent(List<Type> ts, List<Type> ss) {
   896         while (ts.nonEmpty() && ss.nonEmpty()
   897                && containsTypeEquivalent(ts.head, ss.head)) {
   898             ts = ts.tail;
   899             ss = ss.tail;
   900         }
   901         return ts.isEmpty() && ss.isEmpty();
   902     }
   903     // </editor-fold>
   905     // <editor-fold defaultstate="collapsed" desc="isCastable">
   906     public boolean isCastable(Type t, Type s) {
   907         return isCastable(t, s, Warner.noWarnings);
   908     }
   910     /**
   911      * Is t is castable to s?<br>
   912      * s is assumed to be an erased type.<br>
   913      * (not defined for Method and ForAll types).
   914      */
   915     public boolean isCastable(Type t, Type s, Warner warn) {
   916         if (t == s)
   917             return true;
   919         if (t.isPrimitive() != s.isPrimitive())
   920             return allowBoxing && (isConvertible(t, s, warn) || isConvertible(s, t, warn));
   922         if (warn != warnStack.head) {
   923             try {
   924                 warnStack = warnStack.prepend(warn);
   925                 return isCastable.visit(t,s);
   926             } finally {
   927                 warnStack = warnStack.tail;
   928             }
   929         } else {
   930             return isCastable.visit(t,s);
   931         }
   932     }
   933     // where
   934         private TypeRelation isCastable = new TypeRelation() {
   936             public Boolean visitType(Type t, Type s) {
   937                 if (s.tag == ERROR)
   938                     return true;
   940                 switch (t.tag) {
   941                 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
   942                 case DOUBLE:
   943                     return s.tag <= DOUBLE;
   944                 case BOOLEAN:
   945                     return s.tag == BOOLEAN;
   946                 case VOID:
   947                     return false;
   948                 case BOT:
   949                     return isSubtype(t, s);
   950                 default:
   951                     throw new AssertionError();
   952                 }
   953             }
   955             @Override
   956             public Boolean visitWildcardType(WildcardType t, Type s) {
   957                 return isCastable(upperBound(t), s, warnStack.head);
   958             }
   960             @Override
   961             public Boolean visitClassType(ClassType t, Type s) {
   962                 if (s.tag == ERROR || s.tag == BOT)
   963                     return true;
   965                 if (s.tag == TYPEVAR) {
   966                     if (isCastable(t, s.getUpperBound(), Warner.noWarnings)) {
   967                         warnStack.head.warnUnchecked();
   968                         return true;
   969                     } else {
   970                         return false;
   971                     }
   972                 }
   974                 if (t.isCompound()) {
   975                     Warner oldWarner = warnStack.head;
   976                     warnStack.head = Warner.noWarnings;
   977                     if (!visit(supertype(t), s))
   978                         return false;
   979                     for (Type intf : interfaces(t)) {
   980                         if (!visit(intf, s))
   981                             return false;
   982                     }
   983                     if (warnStack.head.unchecked == true)
   984                         oldWarner.warnUnchecked();
   985                     return true;
   986                 }
   988                 if (s.isCompound()) {
   989                     // call recursively to reuse the above code
   990                     return visitClassType((ClassType)s, t);
   991                 }
   993                 if (s.tag == CLASS || s.tag == ARRAY) {
   994                     boolean upcast;
   995                     if ((upcast = isSubtype(erasure(t), erasure(s)))
   996                         || isSubtype(erasure(s), erasure(t))) {
   997                         if (!upcast && s.tag == ARRAY) {
   998                             if (!isReifiable(s))
   999                                 warnStack.head.warnUnchecked();
  1000                             return true;
  1001                         } else if (s.isRaw()) {
  1002                             return true;
  1003                         } else if (t.isRaw()) {
  1004                             if (!isUnbounded(s))
  1005                                 warnStack.head.warnUnchecked();
  1006                             return true;
  1008                         // Assume |a| <: |b|
  1009                         final Type a = upcast ? t : s;
  1010                         final Type b = upcast ? s : t;
  1011                         final boolean HIGH = true;
  1012                         final boolean LOW = false;
  1013                         final boolean DONT_REWRITE_TYPEVARS = false;
  1014                         Type aHigh = rewriteQuantifiers(a, HIGH, DONT_REWRITE_TYPEVARS);
  1015                         Type aLow  = rewriteQuantifiers(a, LOW,  DONT_REWRITE_TYPEVARS);
  1016                         Type bHigh = rewriteQuantifiers(b, HIGH, DONT_REWRITE_TYPEVARS);
  1017                         Type bLow  = rewriteQuantifiers(b, LOW,  DONT_REWRITE_TYPEVARS);
  1018                         Type lowSub = asSub(bLow, aLow.tsym);
  1019                         Type highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
  1020                         if (highSub == null) {
  1021                             final boolean REWRITE_TYPEVARS = true;
  1022                             aHigh = rewriteQuantifiers(a, HIGH, REWRITE_TYPEVARS);
  1023                             aLow  = rewriteQuantifiers(a, LOW,  REWRITE_TYPEVARS);
  1024                             bHigh = rewriteQuantifiers(b, HIGH, REWRITE_TYPEVARS);
  1025                             bLow  = rewriteQuantifiers(b, LOW,  REWRITE_TYPEVARS);
  1026                             lowSub = asSub(bLow, aLow.tsym);
  1027                             highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
  1029                         if (highSub != null) {
  1030                             assert a.tsym == highSub.tsym && a.tsym == lowSub.tsym
  1031                                 : a.tsym + " != " + highSub.tsym + " != " + lowSub.tsym;
  1032                             if (!disjointTypes(aHigh.allparams(), highSub.allparams())
  1033                                 && !disjointTypes(aHigh.allparams(), lowSub.allparams())
  1034                                 && !disjointTypes(aLow.allparams(), highSub.allparams())
  1035                                 && !disjointTypes(aLow.allparams(), lowSub.allparams())) {
  1036                                 if (s.isInterface() &&
  1037                                         !t.isInterface() &&
  1038                                         t.isFinal() &&
  1039                                         !isSubtype(t, s)) {
  1040                                     return false;
  1041                                 } else if (upcast ? giveWarning(a, b) :
  1042                                     giveWarning(b, a))
  1043                                     warnStack.head.warnUnchecked();
  1044                                 return true;
  1047                         if (isReifiable(s))
  1048                             return isSubtypeUnchecked(a, b);
  1049                         else
  1050                             return isSubtypeUnchecked(a, b, warnStack.head);
  1053                     // Sidecast
  1054                     if (s.tag == CLASS) {
  1055                         if ((s.tsym.flags() & INTERFACE) != 0) {
  1056                             return ((t.tsym.flags() & FINAL) == 0)
  1057                                 ? sideCast(t, s, warnStack.head)
  1058                                 : sideCastFinal(t, s, warnStack.head);
  1059                         } else if ((t.tsym.flags() & INTERFACE) != 0) {
  1060                             return ((s.tsym.flags() & FINAL) == 0)
  1061                                 ? sideCast(t, s, warnStack.head)
  1062                                 : sideCastFinal(t, s, warnStack.head);
  1063                         } else {
  1064                             // unrelated class types
  1065                             return false;
  1069                 return false;
  1072             @Override
  1073             public Boolean visitArrayType(ArrayType t, Type s) {
  1074                 switch (s.tag) {
  1075                 case ERROR:
  1076                 case BOT:
  1077                     return true;
  1078                 case TYPEVAR:
  1079                     if (isCastable(s, t, Warner.noWarnings)) {
  1080                         warnStack.head.warnUnchecked();
  1081                         return true;
  1082                     } else {
  1083                         return false;
  1085                 case CLASS:
  1086                     return isSubtype(t, s);
  1087                 case ARRAY:
  1088                     if (elemtype(t).tag <= lastBaseTag) {
  1089                         return elemtype(t).tag == elemtype(s).tag;
  1090                     } else {
  1091                         return visit(elemtype(t), elemtype(s));
  1093                 default:
  1094                     return false;
  1098             @Override
  1099             public Boolean visitTypeVar(TypeVar t, Type s) {
  1100                 switch (s.tag) {
  1101                 case ERROR:
  1102                 case BOT:
  1103                     return true;
  1104                 case TYPEVAR:
  1105                     if (isSubtype(t, s)) {
  1106                         return true;
  1107                     } else if (isCastable(t.bound, s, Warner.noWarnings)) {
  1108                         warnStack.head.warnUnchecked();
  1109                         return true;
  1110                     } else {
  1111                         return false;
  1113                 default:
  1114                     return isCastable(t.bound, s, warnStack.head);
  1118             @Override
  1119             public Boolean visitErrorType(ErrorType t, Type s) {
  1120                 return true;
  1122         };
  1123     // </editor-fold>
  1125     // <editor-fold defaultstate="collapsed" desc="disjointTypes">
  1126     public boolean disjointTypes(List<Type> ts, List<Type> ss) {
  1127         while (ts.tail != null && ss.tail != null) {
  1128             if (disjointType(ts.head, ss.head)) return true;
  1129             ts = ts.tail;
  1130             ss = ss.tail;
  1132         return false;
  1135     /**
  1136      * Two types or wildcards are considered disjoint if it can be
  1137      * proven that no type can be contained in both. It is
  1138      * conservative in that it is allowed to say that two types are
  1139      * not disjoint, even though they actually are.
  1141      * The type C<X> is castable to C<Y> exactly if X and Y are not
  1142      * disjoint.
  1143      */
  1144     public boolean disjointType(Type t, Type s) {
  1145         return disjointType.visit(t, s);
  1147     // where
  1148         private TypeRelation disjointType = new TypeRelation() {
  1150             private Set<TypePair> cache = new HashSet<TypePair>();
  1152             public Boolean visitType(Type t, Type s) {
  1153                 if (s.tag == WILDCARD)
  1154                     return visit(s, t);
  1155                 else
  1156                     return notSoftSubtypeRecursive(t, s) || notSoftSubtypeRecursive(s, t);
  1159             private boolean isCastableRecursive(Type t, Type s) {
  1160                 TypePair pair = new TypePair(t, s);
  1161                 if (cache.add(pair)) {
  1162                     try {
  1163                         return Types.this.isCastable(t, s);
  1164                     } finally {
  1165                         cache.remove(pair);
  1167                 } else {
  1168                     return true;
  1172             private boolean notSoftSubtypeRecursive(Type t, Type s) {
  1173                 TypePair pair = new TypePair(t, s);
  1174                 if (cache.add(pair)) {
  1175                     try {
  1176                         return Types.this.notSoftSubtype(t, s);
  1177                     } finally {
  1178                         cache.remove(pair);
  1180                 } else {
  1181                     return false;
  1185             @Override
  1186             public Boolean visitWildcardType(WildcardType t, Type s) {
  1187                 if (t.isUnbound())
  1188                     return false;
  1190                 if (s.tag != WILDCARD) {
  1191                     if (t.isExtendsBound())
  1192                         return notSoftSubtypeRecursive(s, t.type);
  1193                     else // isSuperBound()
  1194                         return notSoftSubtypeRecursive(t.type, s);
  1197                 if (s.isUnbound())
  1198                     return false;
  1200                 if (t.isExtendsBound()) {
  1201                     if (s.isExtendsBound())
  1202                         return !isCastableRecursive(t.type, upperBound(s));
  1203                     else if (s.isSuperBound())
  1204                         return notSoftSubtypeRecursive(lowerBound(s), t.type);
  1205                 } else if (t.isSuperBound()) {
  1206                     if (s.isExtendsBound())
  1207                         return notSoftSubtypeRecursive(t.type, upperBound(s));
  1209                 return false;
  1211         };
  1212     // </editor-fold>
  1214     // <editor-fold defaultstate="collapsed" desc="lowerBoundArgtypes">
  1215     /**
  1216      * Returns the lower bounds of the formals of a method.
  1217      */
  1218     public List<Type> lowerBoundArgtypes(Type t) {
  1219         return map(t.getParameterTypes(), lowerBoundMapping);
  1221     private final Mapping lowerBoundMapping = new Mapping("lowerBound") {
  1222             public Type apply(Type t) {
  1223                 return lowerBound(t);
  1225         };
  1226     // </editor-fold>
  1228     // <editor-fold defaultstate="collapsed" desc="notSoftSubtype">
  1229     /**
  1230      * This relation answers the question: is impossible that
  1231      * something of type `t' can be a subtype of `s'? This is
  1232      * different from the question "is `t' not a subtype of `s'?"
  1233      * when type variables are involved: Integer is not a subtype of T
  1234      * where <T extends Number> but it is not true that Integer cannot
  1235      * possibly be a subtype of T.
  1236      */
  1237     public boolean notSoftSubtype(Type t, Type s) {
  1238         if (t == s) return false;
  1239         if (t.tag == TYPEVAR) {
  1240             TypeVar tv = (TypeVar) t;
  1241             return !isCastable(tv.bound,
  1242                                relaxBound(s),
  1243                                Warner.noWarnings);
  1245         if (s.tag != WILDCARD)
  1246             s = upperBound(s);
  1248         return !isSubtype(t, relaxBound(s));
  1251     private Type relaxBound(Type t) {
  1252         if (t.tag == TYPEVAR) {
  1253             while (t.tag == TYPEVAR)
  1254                 t = t.getUpperBound();
  1255             t = rewriteQuantifiers(t, true, true);
  1257         return t;
  1259     // </editor-fold>
  1261     // <editor-fold defaultstate="collapsed" desc="isReifiable">
  1262     public boolean isReifiable(Type t) {
  1263         return isReifiable.visit(t);
  1265     // where
  1266         private UnaryVisitor<Boolean> isReifiable = new UnaryVisitor<Boolean>() {
  1268             public Boolean visitType(Type t, Void ignored) {
  1269                 return true;
  1272             @Override
  1273             public Boolean visitClassType(ClassType t, Void ignored) {
  1274                 if (t.isCompound())
  1275                     return false;
  1276                 else {
  1277                     if (!t.isParameterized())
  1278                         return true;
  1280                     for (Type param : t.allparams()) {
  1281                         if (!param.isUnbound())
  1282                             return false;
  1284                     return true;
  1288             @Override
  1289             public Boolean visitArrayType(ArrayType t, Void ignored) {
  1290                 return visit(t.elemtype);
  1293             @Override
  1294             public Boolean visitTypeVar(TypeVar t, Void ignored) {
  1295                 return false;
  1297         };
  1298     // </editor-fold>
  1300     // <editor-fold defaultstate="collapsed" desc="Array Utils">
  1301     public boolean isArray(Type t) {
  1302         while (t.tag == WILDCARD)
  1303             t = upperBound(t);
  1304         return t.tag == ARRAY;
  1307     /**
  1308      * The element type of an array.
  1309      */
  1310     public Type elemtype(Type t) {
  1311         switch (t.tag) {
  1312         case WILDCARD:
  1313             return elemtype(upperBound(t));
  1314         case ARRAY:
  1315             return ((ArrayType)t).elemtype;
  1316         case FORALL:
  1317             return elemtype(((ForAll)t).qtype);
  1318         case ERROR:
  1319             return t;
  1320         default:
  1321             return null;
  1325     /**
  1326      * Mapping to take element type of an arraytype
  1327      */
  1328     private Mapping elemTypeFun = new Mapping ("elemTypeFun") {
  1329         public Type apply(Type t) { return elemtype(t); }
  1330     };
  1332     /**
  1333      * The number of dimensions of an array type.
  1334      */
  1335     public int dimensions(Type t) {
  1336         int result = 0;
  1337         while (t.tag == ARRAY) {
  1338             result++;
  1339             t = elemtype(t);
  1341         return result;
  1343     // </editor-fold>
  1345     // <editor-fold defaultstate="collapsed" desc="asSuper">
  1346     /**
  1347      * Return the (most specific) base type of t that starts with the
  1348      * given symbol.  If none exists, return null.
  1350      * @param t a type
  1351      * @param sym a symbol
  1352      */
  1353     public Type asSuper(Type t, Symbol sym) {
  1354         return asSuper.visit(t, sym);
  1356     // where
  1357         private SimpleVisitor<Type,Symbol> asSuper = new SimpleVisitor<Type,Symbol>() {
  1359             public Type visitType(Type t, Symbol sym) {
  1360                 return null;
  1363             @Override
  1364             public Type visitClassType(ClassType t, Symbol sym) {
  1365                 if (t.tsym == sym)
  1366                     return t;
  1368                 Type st = supertype(t);
  1369                 if (st.tag == CLASS || st.tag == TYPEVAR || st.tag == ERROR) {
  1370                     Type x = asSuper(st, sym);
  1371                     if (x != null)
  1372                         return x;
  1374                 if ((sym.flags() & INTERFACE) != 0) {
  1375                     for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
  1376                         Type x = asSuper(l.head, sym);
  1377                         if (x != null)
  1378                             return x;
  1381                 return null;
  1384             @Override
  1385             public Type visitArrayType(ArrayType t, Symbol sym) {
  1386                 return isSubtype(t, sym.type) ? sym.type : null;
  1389             @Override
  1390             public Type visitTypeVar(TypeVar t, Symbol sym) {
  1391                 if (t.tsym == sym)
  1392                     return t;
  1393                 else
  1394                     return asSuper(t.bound, sym);
  1397             @Override
  1398             public Type visitErrorType(ErrorType t, Symbol sym) {
  1399                 return t;
  1401         };
  1403     /**
  1404      * Return the base type of t or any of its outer types that starts
  1405      * with the given symbol.  If none exists, return null.
  1407      * @param t a type
  1408      * @param sym a symbol
  1409      */
  1410     public Type asOuterSuper(Type t, Symbol sym) {
  1411         switch (t.tag) {
  1412         case CLASS:
  1413             do {
  1414                 Type s = asSuper(t, sym);
  1415                 if (s != null) return s;
  1416                 t = t.getEnclosingType();
  1417             } while (t.tag == CLASS);
  1418             return null;
  1419         case ARRAY:
  1420             return isSubtype(t, sym.type) ? sym.type : null;
  1421         case TYPEVAR:
  1422             return asSuper(t, sym);
  1423         case ERROR:
  1424             return t;
  1425         default:
  1426             return null;
  1430     /**
  1431      * Return the base type of t or any of its enclosing types that
  1432      * starts with the given symbol.  If none exists, return null.
  1434      * @param t a type
  1435      * @param sym a symbol
  1436      */
  1437     public Type asEnclosingSuper(Type t, Symbol sym) {
  1438         switch (t.tag) {
  1439         case CLASS:
  1440             do {
  1441                 Type s = asSuper(t, sym);
  1442                 if (s != null) return s;
  1443                 Type outer = t.getEnclosingType();
  1444                 t = (outer.tag == CLASS) ? outer :
  1445                     (t.tsym.owner.enclClass() != null) ? t.tsym.owner.enclClass().type :
  1446                     Type.noType;
  1447             } while (t.tag == CLASS);
  1448             return null;
  1449         case ARRAY:
  1450             return isSubtype(t, sym.type) ? sym.type : null;
  1451         case TYPEVAR:
  1452             return asSuper(t, sym);
  1453         case ERROR:
  1454             return t;
  1455         default:
  1456             return null;
  1459     // </editor-fold>
  1461     // <editor-fold defaultstate="collapsed" desc="memberType">
  1462     /**
  1463      * The type of given symbol, seen as a member of t.
  1465      * @param t a type
  1466      * @param sym a symbol
  1467      */
  1468     public Type memberType(Type t, Symbol sym) {
  1469         return (sym.flags() & STATIC) != 0
  1470             ? sym.type
  1471             : memberType.visit(t, sym);
  1473     // where
  1474         private SimpleVisitor<Type,Symbol> memberType = new SimpleVisitor<Type,Symbol>() {
  1476             public Type visitType(Type t, Symbol sym) {
  1477                 return sym.type;
  1480             @Override
  1481             public Type visitWildcardType(WildcardType t, Symbol sym) {
  1482                 return memberType(upperBound(t), sym);
  1485             @Override
  1486             public Type visitClassType(ClassType t, Symbol sym) {
  1487                 Symbol owner = sym.owner;
  1488                 long flags = sym.flags();
  1489                 if (((flags & STATIC) == 0) && owner.type.isParameterized()) {
  1490                     Type base = asOuterSuper(t, owner);
  1491                     //if t is an intersection type T = CT & I1 & I2 ... & In
  1492                     //its supertypes CT, I1, ... In might contain wildcards
  1493                     //so we need to go through capture conversion
  1494                     base = t.isCompound() ? capture(base) : base;
  1495                     if (base != null) {
  1496                         List<Type> ownerParams = owner.type.allparams();
  1497                         List<Type> baseParams = base.allparams();
  1498                         if (ownerParams.nonEmpty()) {
  1499                             if (baseParams.isEmpty()) {
  1500                                 // then base is a raw type
  1501                                 return erasure(sym.type);
  1502                             } else {
  1503                                 return subst(sym.type, ownerParams, baseParams);
  1508                 return sym.type;
  1511             @Override
  1512             public Type visitTypeVar(TypeVar t, Symbol sym) {
  1513                 return memberType(t.bound, sym);
  1516             @Override
  1517             public Type visitErrorType(ErrorType t, Symbol sym) {
  1518                 return t;
  1520         };
  1521     // </editor-fold>
  1523     // <editor-fold defaultstate="collapsed" desc="isAssignable">
  1524     public boolean isAssignable(Type t, Type s) {
  1525         return isAssignable(t, s, Warner.noWarnings);
  1528     /**
  1529      * Is t assignable to s?<br>
  1530      * Equivalent to subtype except for constant values and raw
  1531      * types.<br>
  1532      * (not defined for Method and ForAll types)
  1533      */
  1534     public boolean isAssignable(Type t, Type s, Warner warn) {
  1535         if (t.tag == ERROR)
  1536             return true;
  1537         if (t.tag <= INT && t.constValue() != null) {
  1538             int value = ((Number)t.constValue()).intValue();
  1539             switch (s.tag) {
  1540             case BYTE:
  1541                 if (Byte.MIN_VALUE <= value && value <= Byte.MAX_VALUE)
  1542                     return true;
  1543                 break;
  1544             case CHAR:
  1545                 if (Character.MIN_VALUE <= value && value <= Character.MAX_VALUE)
  1546                     return true;
  1547                 break;
  1548             case SHORT:
  1549                 if (Short.MIN_VALUE <= value && value <= Short.MAX_VALUE)
  1550                     return true;
  1551                 break;
  1552             case INT:
  1553                 return true;
  1554             case CLASS:
  1555                 switch (unboxedType(s).tag) {
  1556                 case BYTE:
  1557                 case CHAR:
  1558                 case SHORT:
  1559                     return isAssignable(t, unboxedType(s), warn);
  1561                 break;
  1564         return isConvertible(t, s, warn);
  1566     // </editor-fold>
  1568     // <editor-fold defaultstate="collapsed" desc="erasure">
  1569     /**
  1570      * The erasure of t {@code |t|} -- the type that results when all
  1571      * type parameters in t are deleted.
  1572      */
  1573     public Type erasure(Type t) {
  1574         return erasure(t, false);
  1576     //where
  1577     private Type erasure(Type t, boolean recurse) {
  1578         if (t.tag <= lastBaseTag)
  1579             return t; /* fast special case */
  1580         else
  1581             return erasure.visit(t, recurse);
  1583     // where
  1584         private SimpleVisitor<Type, Boolean> erasure = new SimpleVisitor<Type, Boolean>() {
  1585             public Type visitType(Type t, Boolean recurse) {
  1586                 if (t.tag <= lastBaseTag)
  1587                     return t; /*fast special case*/
  1588                 else
  1589                     return t.map(recurse ? erasureRecFun : erasureFun);
  1592             @Override
  1593             public Type visitWildcardType(WildcardType t, Boolean recurse) {
  1594                 return erasure(upperBound(t), recurse);
  1597             @Override
  1598             public Type visitClassType(ClassType t, Boolean recurse) {
  1599                 Type erased = t.tsym.erasure(Types.this);
  1600                 if (recurse) {
  1601                     erased = new ErasedClassType(erased.getEnclosingType(),erased.tsym);
  1603                 return erased;
  1606             @Override
  1607             public Type visitTypeVar(TypeVar t, Boolean recurse) {
  1608                 return erasure(t.bound, recurse);
  1611             @Override
  1612             public Type visitErrorType(ErrorType t, Boolean recurse) {
  1613                 return t;
  1615         };
  1617     private Mapping erasureFun = new Mapping ("erasure") {
  1618             public Type apply(Type t) { return erasure(t); }
  1619         };
  1621     private Mapping erasureRecFun = new Mapping ("erasureRecursive") {
  1622         public Type apply(Type t) { return erasureRecursive(t); }
  1623     };
  1625     public List<Type> erasure(List<Type> ts) {
  1626         return Type.map(ts, erasureFun);
  1629     public Type erasureRecursive(Type t) {
  1630         return erasure(t, true);
  1633     public List<Type> erasureRecursive(List<Type> ts) {
  1634         return Type.map(ts, erasureRecFun);
  1636     // </editor-fold>
  1638     // <editor-fold defaultstate="collapsed" desc="makeCompoundType">
  1639     /**
  1640      * Make a compound type from non-empty list of types
  1642      * @param bounds            the types from which the compound type is formed
  1643      * @param supertype         is objectType if all bounds are interfaces,
  1644      *                          null otherwise.
  1645      */
  1646     public Type makeCompoundType(List<Type> bounds,
  1647                                  Type supertype) {
  1648         ClassSymbol bc =
  1649             new ClassSymbol(ABSTRACT|PUBLIC|SYNTHETIC|COMPOUND|ACYCLIC,
  1650                             Type.moreInfo
  1651                                 ? names.fromString(bounds.toString())
  1652                                 : names.empty,
  1653                             syms.noSymbol);
  1654         if (bounds.head.tag == TYPEVAR)
  1655             // error condition, recover
  1656                 bc.erasure_field = syms.objectType;
  1657             else
  1658                 bc.erasure_field = erasure(bounds.head);
  1659             bc.members_field = new Scope(bc);
  1660         ClassType bt = (ClassType)bc.type;
  1661         bt.allparams_field = List.nil();
  1662         if (supertype != null) {
  1663             bt.supertype_field = supertype;
  1664             bt.interfaces_field = bounds;
  1665         } else {
  1666             bt.supertype_field = bounds.head;
  1667             bt.interfaces_field = bounds.tail;
  1669         assert bt.supertype_field.tsym.completer != null
  1670             || !bt.supertype_field.isInterface()
  1671             : bt.supertype_field;
  1672         return bt;
  1675     /**
  1676      * Same as {@link #makeCompoundType(List,Type)}, except that the
  1677      * second parameter is computed directly. Note that this might
  1678      * cause a symbol completion.  Hence, this version of
  1679      * makeCompoundType may not be called during a classfile read.
  1680      */
  1681     public Type makeCompoundType(List<Type> bounds) {
  1682         Type supertype = (bounds.head.tsym.flags() & INTERFACE) != 0 ?
  1683             supertype(bounds.head) : null;
  1684         return makeCompoundType(bounds, supertype);
  1687     /**
  1688      * A convenience wrapper for {@link #makeCompoundType(List)}; the
  1689      * arguments are converted to a list and passed to the other
  1690      * method.  Note that this might cause a symbol completion.
  1691      * Hence, this version of makeCompoundType may not be called
  1692      * during a classfile read.
  1693      */
  1694     public Type makeCompoundType(Type bound1, Type bound2) {
  1695         return makeCompoundType(List.of(bound1, bound2));
  1697     // </editor-fold>
  1699     // <editor-fold defaultstate="collapsed" desc="supertype">
  1700     public Type supertype(Type t) {
  1701         return supertype.visit(t);
  1703     // where
  1704         private UnaryVisitor<Type> supertype = new UnaryVisitor<Type>() {
  1706             public Type visitType(Type t, Void ignored) {
  1707                 // A note on wildcards: there is no good way to
  1708                 // determine a supertype for a super bounded wildcard.
  1709                 return null;
  1712             @Override
  1713             public Type visitClassType(ClassType t, Void ignored) {
  1714                 if (t.supertype_field == null) {
  1715                     Type supertype = ((ClassSymbol)t.tsym).getSuperclass();
  1716                     // An interface has no superclass; its supertype is Object.
  1717                     if (t.isInterface())
  1718                         supertype = ((ClassType)t.tsym.type).supertype_field;
  1719                     if (t.supertype_field == null) {
  1720                         List<Type> actuals = classBound(t).allparams();
  1721                         List<Type> formals = t.tsym.type.allparams();
  1722                         if (t.hasErasedSupertypes()) {
  1723                             t.supertype_field = erasureRecursive(supertype);
  1724                         } else if (formals.nonEmpty()) {
  1725                             t.supertype_field = subst(supertype, formals, actuals);
  1727                         else {
  1728                             t.supertype_field = supertype;
  1732                 return t.supertype_field;
  1735             /**
  1736              * The supertype is always a class type. If the type
  1737              * variable's bounds start with a class type, this is also
  1738              * the supertype.  Otherwise, the supertype is
  1739              * java.lang.Object.
  1740              */
  1741             @Override
  1742             public Type visitTypeVar(TypeVar t, Void ignored) {
  1743                 if (t.bound.tag == TYPEVAR ||
  1744                     (!t.bound.isCompound() && !t.bound.isInterface())) {
  1745                     return t.bound;
  1746                 } else {
  1747                     return supertype(t.bound);
  1751             @Override
  1752             public Type visitArrayType(ArrayType t, Void ignored) {
  1753                 if (t.elemtype.isPrimitive() || isSameType(t.elemtype, syms.objectType))
  1754                     return arraySuperType();
  1755                 else
  1756                     return new ArrayType(supertype(t.elemtype), t.tsym);
  1759             @Override
  1760             public Type visitErrorType(ErrorType t, Void ignored) {
  1761                 return t;
  1763         };
  1764     // </editor-fold>
  1766     // <editor-fold defaultstate="collapsed" desc="interfaces">
  1767     /**
  1768      * Return the interfaces implemented by this class.
  1769      */
  1770     public List<Type> interfaces(Type t) {
  1771         return interfaces.visit(t);
  1773     // where
  1774         private UnaryVisitor<List<Type>> interfaces = new UnaryVisitor<List<Type>>() {
  1776             public List<Type> visitType(Type t, Void ignored) {
  1777                 return List.nil();
  1780             @Override
  1781             public List<Type> visitClassType(ClassType t, Void ignored) {
  1782                 if (t.interfaces_field == null) {
  1783                     List<Type> interfaces = ((ClassSymbol)t.tsym).getInterfaces();
  1784                     if (t.interfaces_field == null) {
  1785                         // If t.interfaces_field is null, then t must
  1786                         // be a parameterized type (not to be confused
  1787                         // with a generic type declaration).
  1788                         // Terminology:
  1789                         //    Parameterized type: List<String>
  1790                         //    Generic type declaration: class List<E> { ... }
  1791                         // So t corresponds to List<String> and
  1792                         // t.tsym.type corresponds to List<E>.
  1793                         // The reason t must be parameterized type is
  1794                         // that completion will happen as a side
  1795                         // effect of calling
  1796                         // ClassSymbol.getInterfaces.  Since
  1797                         // t.interfaces_field is null after
  1798                         // completion, we can assume that t is not the
  1799                         // type of a class/interface declaration.
  1800                         assert t != t.tsym.type : t.toString();
  1801                         List<Type> actuals = t.allparams();
  1802                         List<Type> formals = t.tsym.type.allparams();
  1803                         if (t.hasErasedSupertypes()) {
  1804                             t.interfaces_field = erasureRecursive(interfaces);
  1805                         } else if (formals.nonEmpty()) {
  1806                             t.interfaces_field =
  1807                                 upperBounds(subst(interfaces, formals, actuals));
  1809                         else {
  1810                             t.interfaces_field = interfaces;
  1814                 return t.interfaces_field;
  1817             @Override
  1818             public List<Type> visitTypeVar(TypeVar t, Void ignored) {
  1819                 if (t.bound.isCompound())
  1820                     return interfaces(t.bound);
  1822                 if (t.bound.isInterface())
  1823                     return List.of(t.bound);
  1825                 return List.nil();
  1827         };
  1828     // </editor-fold>
  1830     // <editor-fold defaultstate="collapsed" desc="isDerivedRaw">
  1831     Map<Type,Boolean> isDerivedRawCache = new HashMap<Type,Boolean>();
  1833     public boolean isDerivedRaw(Type t) {
  1834         Boolean result = isDerivedRawCache.get(t);
  1835         if (result == null) {
  1836             result = isDerivedRawInternal(t);
  1837             isDerivedRawCache.put(t, result);
  1839         return result;
  1842     public boolean isDerivedRawInternal(Type t) {
  1843         if (t.isErroneous())
  1844             return false;
  1845         return
  1846             t.isRaw() ||
  1847             supertype(t) != null && isDerivedRaw(supertype(t)) ||
  1848             isDerivedRaw(interfaces(t));
  1851     public boolean isDerivedRaw(List<Type> ts) {
  1852         List<Type> l = ts;
  1853         while (l.nonEmpty() && !isDerivedRaw(l.head)) l = l.tail;
  1854         return l.nonEmpty();
  1856     // </editor-fold>
  1858     // <editor-fold defaultstate="collapsed" desc="setBounds">
  1859     /**
  1860      * Set the bounds field of the given type variable to reflect a
  1861      * (possibly multiple) list of bounds.
  1862      * @param t                 a type variable
  1863      * @param bounds            the bounds, must be nonempty
  1864      * @param supertype         is objectType if all bounds are interfaces,
  1865      *                          null otherwise.
  1866      */
  1867     public void setBounds(TypeVar t, List<Type> bounds, Type supertype) {
  1868         if (bounds.tail.isEmpty())
  1869             t.bound = bounds.head;
  1870         else
  1871             t.bound = makeCompoundType(bounds, supertype);
  1872         t.rank_field = -1;
  1875     /**
  1876      * Same as {@link #setBounds(Type.TypeVar,List,Type)}, except that
  1877      * third parameter is computed directly, as follows: if all
  1878      * all bounds are interface types, the computed supertype is Object,
  1879      * otherwise the supertype is simply left null (in this case, the supertype
  1880      * is assumed to be the head of the bound list passed as second argument).
  1881      * Note that this check might cause a symbol completion. Hence, this version of
  1882      * setBounds may not be called during a classfile read.
  1883      */
  1884     public void setBounds(TypeVar t, List<Type> bounds) {
  1885         Type supertype = (bounds.head.tsym.flags() & INTERFACE) != 0 ?
  1886             syms.objectType : null;
  1887         setBounds(t, bounds, supertype);
  1888         t.rank_field = -1;
  1890     // </editor-fold>
  1892     // <editor-fold defaultstate="collapsed" desc="getBounds">
  1893     /**
  1894      * Return list of bounds of the given type variable.
  1895      */
  1896     public List<Type> getBounds(TypeVar t) {
  1897         if (t.bound.isErroneous() || !t.bound.isCompound())
  1898             return List.of(t.bound);
  1899         else if ((erasure(t).tsym.flags() & INTERFACE) == 0)
  1900             return interfaces(t).prepend(supertype(t));
  1901         else
  1902             // No superclass was given in bounds.
  1903             // In this case, supertype is Object, erasure is first interface.
  1904             return interfaces(t);
  1906     // </editor-fold>
  1908     // <editor-fold defaultstate="collapsed" desc="classBound">
  1909     /**
  1910      * If the given type is a (possibly selected) type variable,
  1911      * return the bounding class of this type, otherwise return the
  1912      * type itself.
  1913      */
  1914     public Type classBound(Type t) {
  1915         return classBound.visit(t);
  1917     // where
  1918         private UnaryVisitor<Type> classBound = new UnaryVisitor<Type>() {
  1920             public Type visitType(Type t, Void ignored) {
  1921                 return t;
  1924             @Override
  1925             public Type visitClassType(ClassType t, Void ignored) {
  1926                 Type outer1 = classBound(t.getEnclosingType());
  1927                 if (outer1 != t.getEnclosingType())
  1928                     return new ClassType(outer1, t.getTypeArguments(), t.tsym);
  1929                 else
  1930                     return t;
  1933             @Override
  1934             public Type visitTypeVar(TypeVar t, Void ignored) {
  1935                 return classBound(supertype(t));
  1938             @Override
  1939             public Type visitErrorType(ErrorType t, Void ignored) {
  1940                 return t;
  1942         };
  1943     // </editor-fold>
  1945     // <editor-fold defaultstate="collapsed" desc="sub signature / override equivalence">
  1946     /**
  1947      * Returns true iff the first signature is a <em>sub
  1948      * signature</em> of the other.  This is <b>not</b> an equivalence
  1949      * relation.
  1951      * @see "The Java Language Specification, Third Ed. (8.4.2)."
  1952      * @see #overrideEquivalent(Type t, Type s)
  1953      * @param t first signature (possibly raw).
  1954      * @param s second signature (could be subjected to erasure).
  1955      * @return true if t is a sub signature of s.
  1956      */
  1957     public boolean isSubSignature(Type t, Type s) {
  1958         return hasSameArgs(t, s) || hasSameArgs(t, erasure(s));
  1961     /**
  1962      * Returns true iff these signatures are related by <em>override
  1963      * equivalence</em>.  This is the natural extension of
  1964      * isSubSignature to an equivalence relation.
  1966      * @see "The Java Language Specification, Third Ed. (8.4.2)."
  1967      * @see #isSubSignature(Type t, Type s)
  1968      * @param t a signature (possible raw, could be subjected to
  1969      * erasure).
  1970      * @param s a signature (possible raw, could be subjected to
  1971      * erasure).
  1972      * @return true if either argument is a sub signature of the other.
  1973      */
  1974     public boolean overrideEquivalent(Type t, Type s) {
  1975         return hasSameArgs(t, s) ||
  1976             hasSameArgs(t, erasure(s)) || hasSameArgs(erasure(t), s);
  1979     // <editor-fold defaultstate="collapsed" desc="Determining method implementation in given site">
  1980     class ImplementationCache {
  1982         private WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>> _map =
  1983                 new WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>>();
  1985         class Entry {
  1986             final MethodSymbol cachedImpl;
  1987             final Filter<Symbol> implFilter;
  1988             final boolean checkResult;
  1989             final Scope.ScopeCounter scopeCounter;
  1991             public Entry(MethodSymbol cachedImpl,
  1992                     Filter<Symbol> scopeFilter,
  1993                     boolean checkResult,
  1994                     Scope.ScopeCounter scopeCounter) {
  1995                 this.cachedImpl = cachedImpl;
  1996                 this.implFilter = scopeFilter;
  1997                 this.checkResult = checkResult;
  1998                 this.scopeCounter = scopeCounter;
  2001             boolean matches(Filter<Symbol> scopeFilter, boolean checkResult, Scope.ScopeCounter scopeCounter) {
  2002                 return this.implFilter == scopeFilter &&
  2003                         this.checkResult == checkResult &&
  2004                         this.scopeCounter.val() >= scopeCounter.val();
  2008         MethodSymbol get(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter, Scope.ScopeCounter scopeCounter) {
  2009             SoftReference<Map<TypeSymbol, Entry>> ref_cache = _map.get(ms);
  2010             Map<TypeSymbol, Entry> cache = ref_cache != null ? ref_cache.get() : null;
  2011             if (cache == null) {
  2012                 cache = new HashMap<TypeSymbol, Entry>();
  2013                 _map.put(ms, new SoftReference<Map<TypeSymbol, Entry>>(cache));
  2015             Entry e = cache.get(origin);
  2016             if (e == null ||
  2017                     !e.matches(implFilter, checkResult, scopeCounter)) {
  2018                 MethodSymbol impl = implementationInternal(ms, origin, Types.this, checkResult, implFilter);
  2019                 cache.put(origin, new Entry(impl, implFilter, checkResult, scopeCounter));
  2020                 return impl;
  2022             else {
  2023                 return e.cachedImpl;
  2027         private MethodSymbol implementationInternal(MethodSymbol ms, TypeSymbol origin, Types types, boolean checkResult, Filter<Symbol> implFilter) {
  2028             for (Type t = origin.type; t.tag == CLASS || t.tag == TYPEVAR; t = types.supertype(t)) {
  2029                 while (t.tag == TYPEVAR)
  2030                     t = t.getUpperBound();
  2031                 TypeSymbol c = t.tsym;
  2032                 for (Scope.Entry e = c.members().lookup(ms.name, implFilter);
  2033                      e.scope != null;
  2034                      e = e.next()) {
  2035                     if (e.sym != null &&
  2036                              e.sym.overrides(ms, origin, types, checkResult))
  2037                         return (MethodSymbol)e.sym;
  2040             return null;
  2044     private ImplementationCache implCache = new ImplementationCache();
  2046     public MethodSymbol implementation(MethodSymbol ms, TypeSymbol origin, Types types, boolean checkResult, Filter<Symbol> implFilter) {
  2047         return implCache.get(ms, origin, checkResult, implFilter, scopeCounter);
  2049     // </editor-fold>
  2051     /**
  2052      * Does t have the same arguments as s?  It is assumed that both
  2053      * types are (possibly polymorphic) method types.  Monomorphic
  2054      * method types "have the same arguments", if their argument lists
  2055      * are equal.  Polymorphic method types "have the same arguments",
  2056      * if they have the same arguments after renaming all type
  2057      * variables of one to corresponding type variables in the other,
  2058      * where correspondence is by position in the type parameter list.
  2059      */
  2060     public boolean hasSameArgs(Type t, Type s) {
  2061         return hasSameArgs.visit(t, s);
  2063     // where
  2064         private TypeRelation hasSameArgs = new TypeRelation() {
  2066             public Boolean visitType(Type t, Type s) {
  2067                 throw new AssertionError();
  2070             @Override
  2071             public Boolean visitMethodType(MethodType t, Type s) {
  2072                 return s.tag == METHOD
  2073                     && containsTypeEquivalent(t.argtypes, s.getParameterTypes());
  2076             @Override
  2077             public Boolean visitForAll(ForAll t, Type s) {
  2078                 if (s.tag != FORALL)
  2079                     return false;
  2081                 ForAll forAll = (ForAll)s;
  2082                 return hasSameBounds(t, forAll)
  2083                     && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
  2086             @Override
  2087             public Boolean visitErrorType(ErrorType t, Type s) {
  2088                 return false;
  2090         };
  2091     // </editor-fold>
  2093     // <editor-fold defaultstate="collapsed" desc="subst">
  2094     public List<Type> subst(List<Type> ts,
  2095                             List<Type> from,
  2096                             List<Type> to) {
  2097         return new Subst(from, to).subst(ts);
  2100     /**
  2101      * Substitute all occurrences of a type in `from' with the
  2102      * corresponding type in `to' in 't'. Match lists `from' and `to'
  2103      * from the right: If lists have different length, discard leading
  2104      * elements of the longer list.
  2105      */
  2106     public Type subst(Type t, List<Type> from, List<Type> to) {
  2107         return new Subst(from, to).subst(t);
  2110     private class Subst extends UnaryVisitor<Type> {
  2111         List<Type> from;
  2112         List<Type> to;
  2114         public Subst(List<Type> from, List<Type> to) {
  2115             int fromLength = from.length();
  2116             int toLength = to.length();
  2117             while (fromLength > toLength) {
  2118                 fromLength--;
  2119                 from = from.tail;
  2121             while (fromLength < toLength) {
  2122                 toLength--;
  2123                 to = to.tail;
  2125             this.from = from;
  2126             this.to = to;
  2129         Type subst(Type t) {
  2130             if (from.tail == null)
  2131                 return t;
  2132             else
  2133                 return visit(t);
  2136         List<Type> subst(List<Type> ts) {
  2137             if (from.tail == null)
  2138                 return ts;
  2139             boolean wild = false;
  2140             if (ts.nonEmpty() && from.nonEmpty()) {
  2141                 Type head1 = subst(ts.head);
  2142                 List<Type> tail1 = subst(ts.tail);
  2143                 if (head1 != ts.head || tail1 != ts.tail)
  2144                     return tail1.prepend(head1);
  2146             return ts;
  2149         public Type visitType(Type t, Void ignored) {
  2150             return t;
  2153         @Override
  2154         public Type visitMethodType(MethodType t, Void ignored) {
  2155             List<Type> argtypes = subst(t.argtypes);
  2156             Type restype = subst(t.restype);
  2157             List<Type> thrown = subst(t.thrown);
  2158             if (argtypes == t.argtypes &&
  2159                 restype == t.restype &&
  2160                 thrown == t.thrown)
  2161                 return t;
  2162             else
  2163                 return new MethodType(argtypes, restype, thrown, t.tsym);
  2166         @Override
  2167         public Type visitTypeVar(TypeVar t, Void ignored) {
  2168             for (List<Type> from = this.from, to = this.to;
  2169                  from.nonEmpty();
  2170                  from = from.tail, to = to.tail) {
  2171                 if (t == from.head) {
  2172                     return to.head.withTypeVar(t);
  2175             return t;
  2178         @Override
  2179         public Type visitClassType(ClassType t, Void ignored) {
  2180             if (!t.isCompound()) {
  2181                 List<Type> typarams = t.getTypeArguments();
  2182                 List<Type> typarams1 = subst(typarams);
  2183                 Type outer = t.getEnclosingType();
  2184                 Type outer1 = subst(outer);
  2185                 if (typarams1 == typarams && outer1 == outer)
  2186                     return t;
  2187                 else
  2188                     return new ClassType(outer1, typarams1, t.tsym);
  2189             } else {
  2190                 Type st = subst(supertype(t));
  2191                 List<Type> is = upperBounds(subst(interfaces(t)));
  2192                 if (st == supertype(t) && is == interfaces(t))
  2193                     return t;
  2194                 else
  2195                     return makeCompoundType(is.prepend(st));
  2199         @Override
  2200         public Type visitWildcardType(WildcardType t, Void ignored) {
  2201             Type bound = t.type;
  2202             if (t.kind != BoundKind.UNBOUND)
  2203                 bound = subst(bound);
  2204             if (bound == t.type) {
  2205                 return t;
  2206             } else {
  2207                 if (t.isExtendsBound() && bound.isExtendsBound())
  2208                     bound = upperBound(bound);
  2209                 return new WildcardType(bound, t.kind, syms.boundClass, t.bound);
  2213         @Override
  2214         public Type visitArrayType(ArrayType t, Void ignored) {
  2215             Type elemtype = subst(t.elemtype);
  2216             if (elemtype == t.elemtype)
  2217                 return t;
  2218             else
  2219                 return new ArrayType(upperBound(elemtype), t.tsym);
  2222         @Override
  2223         public Type visitForAll(ForAll t, Void ignored) {
  2224             List<Type> tvars1 = substBounds(t.tvars, from, to);
  2225             Type qtype1 = subst(t.qtype);
  2226             if (tvars1 == t.tvars && qtype1 == t.qtype) {
  2227                 return t;
  2228             } else if (tvars1 == t.tvars) {
  2229                 return new ForAll(tvars1, qtype1);
  2230             } else {
  2231                 return new ForAll(tvars1, Types.this.subst(qtype1, t.tvars, tvars1));
  2235         @Override
  2236         public Type visitErrorType(ErrorType t, Void ignored) {
  2237             return t;
  2241     public List<Type> substBounds(List<Type> tvars,
  2242                                   List<Type> from,
  2243                                   List<Type> to) {
  2244         if (tvars.isEmpty())
  2245             return tvars;
  2246         ListBuffer<Type> newBoundsBuf = lb();
  2247         boolean changed = false;
  2248         // calculate new bounds
  2249         for (Type t : tvars) {
  2250             TypeVar tv = (TypeVar) t;
  2251             Type bound = subst(tv.bound, from, to);
  2252             if (bound != tv.bound)
  2253                 changed = true;
  2254             newBoundsBuf.append(bound);
  2256         if (!changed)
  2257             return tvars;
  2258         ListBuffer<Type> newTvars = lb();
  2259         // create new type variables without bounds
  2260         for (Type t : tvars) {
  2261             newTvars.append(new TypeVar(t.tsym, null, syms.botType));
  2263         // the new bounds should use the new type variables in place
  2264         // of the old
  2265         List<Type> newBounds = newBoundsBuf.toList();
  2266         from = tvars;
  2267         to = newTvars.toList();
  2268         for (; !newBounds.isEmpty(); newBounds = newBounds.tail) {
  2269             newBounds.head = subst(newBounds.head, from, to);
  2271         newBounds = newBoundsBuf.toList();
  2272         // set the bounds of new type variables to the new bounds
  2273         for (Type t : newTvars.toList()) {
  2274             TypeVar tv = (TypeVar) t;
  2275             tv.bound = newBounds.head;
  2276             newBounds = newBounds.tail;
  2278         return newTvars.toList();
  2281     public TypeVar substBound(TypeVar t, List<Type> from, List<Type> to) {
  2282         Type bound1 = subst(t.bound, from, to);
  2283         if (bound1 == t.bound)
  2284             return t;
  2285         else {
  2286             // create new type variable without bounds
  2287             TypeVar tv = new TypeVar(t.tsym, null, syms.botType);
  2288             // the new bound should use the new type variable in place
  2289             // of the old
  2290             tv.bound = subst(bound1, List.<Type>of(t), List.<Type>of(tv));
  2291             return tv;
  2294     // </editor-fold>
  2296     // <editor-fold defaultstate="collapsed" desc="hasSameBounds">
  2297     /**
  2298      * Does t have the same bounds for quantified variables as s?
  2299      */
  2300     boolean hasSameBounds(ForAll t, ForAll s) {
  2301         List<Type> l1 = t.tvars;
  2302         List<Type> l2 = s.tvars;
  2303         while (l1.nonEmpty() && l2.nonEmpty() &&
  2304                isSameType(l1.head.getUpperBound(),
  2305                           subst(l2.head.getUpperBound(),
  2306                                 s.tvars,
  2307                                 t.tvars))) {
  2308             l1 = l1.tail;
  2309             l2 = l2.tail;
  2311         return l1.isEmpty() && l2.isEmpty();
  2313     // </editor-fold>
  2315     // <editor-fold defaultstate="collapsed" desc="newInstances">
  2316     /** Create new vector of type variables from list of variables
  2317      *  changing all recursive bounds from old to new list.
  2318      */
  2319     public List<Type> newInstances(List<Type> tvars) {
  2320         List<Type> tvars1 = Type.map(tvars, newInstanceFun);
  2321         for (List<Type> l = tvars1; l.nonEmpty(); l = l.tail) {
  2322             TypeVar tv = (TypeVar) l.head;
  2323             tv.bound = subst(tv.bound, tvars, tvars1);
  2325         return tvars1;
  2327     static private Mapping newInstanceFun = new Mapping("newInstanceFun") {
  2328             public Type apply(Type t) { return new TypeVar(t.tsym, t.getUpperBound(), t.getLowerBound()); }
  2329         };
  2330     // </editor-fold>
  2332     // <editor-fold defaultstate="collapsed" desc="createErrorType">
  2333     public Type createErrorType(Type originalType) {
  2334         return new ErrorType(originalType, syms.errSymbol);
  2337     public Type createErrorType(ClassSymbol c, Type originalType) {
  2338         return new ErrorType(c, originalType);
  2341     public Type createErrorType(Name name, TypeSymbol container, Type originalType) {
  2342         return new ErrorType(name, container, originalType);
  2344     // </editor-fold>
  2346     // <editor-fold defaultstate="collapsed" desc="rank">
  2347     /**
  2348      * The rank of a class is the length of the longest path between
  2349      * the class and java.lang.Object in the class inheritance
  2350      * graph. Undefined for all but reference types.
  2351      */
  2352     public int rank(Type t) {
  2353         switch(t.tag) {
  2354         case CLASS: {
  2355             ClassType cls = (ClassType)t;
  2356             if (cls.rank_field < 0) {
  2357                 Name fullname = cls.tsym.getQualifiedName();
  2358                 if (fullname == names.java_lang_Object)
  2359                     cls.rank_field = 0;
  2360                 else {
  2361                     int r = rank(supertype(cls));
  2362                     for (List<Type> l = interfaces(cls);
  2363                          l.nonEmpty();
  2364                          l = l.tail) {
  2365                         if (rank(l.head) > r)
  2366                             r = rank(l.head);
  2368                     cls.rank_field = r + 1;
  2371             return cls.rank_field;
  2373         case TYPEVAR: {
  2374             TypeVar tvar = (TypeVar)t;
  2375             if (tvar.rank_field < 0) {
  2376                 int r = rank(supertype(tvar));
  2377                 for (List<Type> l = interfaces(tvar);
  2378                      l.nonEmpty();
  2379                      l = l.tail) {
  2380                     if (rank(l.head) > r) r = rank(l.head);
  2382                 tvar.rank_field = r + 1;
  2384             return tvar.rank_field;
  2386         case ERROR:
  2387             return 0;
  2388         default:
  2389             throw new AssertionError();
  2392     // </editor-fold>
  2394     /**
  2395      * Helper method for generating a string representation of a given type
  2396      * accordingly to a given locale
  2397      */
  2398     public String toString(Type t, Locale locale) {
  2399         return Printer.createStandardPrinter(messages).visit(t, locale);
  2402     /**
  2403      * Helper method for generating a string representation of a given type
  2404      * accordingly to a given locale
  2405      */
  2406     public String toString(Symbol t, Locale locale) {
  2407         return Printer.createStandardPrinter(messages).visit(t, locale);
  2410     // <editor-fold defaultstate="collapsed" desc="toString">
  2411     /**
  2412      * This toString is slightly more descriptive than the one on Type.
  2414      * @deprecated Types.toString(Type t, Locale l) provides better support
  2415      * for localization
  2416      */
  2417     @Deprecated
  2418     public String toString(Type t) {
  2419         if (t.tag == FORALL) {
  2420             ForAll forAll = (ForAll)t;
  2421             return typaramsString(forAll.tvars) + forAll.qtype;
  2423         return "" + t;
  2425     // where
  2426         private String typaramsString(List<Type> tvars) {
  2427             StringBuffer s = new StringBuffer();
  2428             s.append('<');
  2429             boolean first = true;
  2430             for (Type t : tvars) {
  2431                 if (!first) s.append(", ");
  2432                 first = false;
  2433                 appendTyparamString(((TypeVar)t), s);
  2435             s.append('>');
  2436             return s.toString();
  2438         private void appendTyparamString(TypeVar t, StringBuffer buf) {
  2439             buf.append(t);
  2440             if (t.bound == null ||
  2441                 t.bound.tsym.getQualifiedName() == names.java_lang_Object)
  2442                 return;
  2443             buf.append(" extends "); // Java syntax; no need for i18n
  2444             Type bound = t.bound;
  2445             if (!bound.isCompound()) {
  2446                 buf.append(bound);
  2447             } else if ((erasure(t).tsym.flags() & INTERFACE) == 0) {
  2448                 buf.append(supertype(t));
  2449                 for (Type intf : interfaces(t)) {
  2450                     buf.append('&');
  2451                     buf.append(intf);
  2453             } else {
  2454                 // No superclass was given in bounds.
  2455                 // In this case, supertype is Object, erasure is first interface.
  2456                 boolean first = true;
  2457                 for (Type intf : interfaces(t)) {
  2458                     if (!first) buf.append('&');
  2459                     first = false;
  2460                     buf.append(intf);
  2464     // </editor-fold>
  2466     // <editor-fold defaultstate="collapsed" desc="Determining least upper bounds of types">
  2467     /**
  2468      * A cache for closures.
  2470      * <p>A closure is a list of all the supertypes and interfaces of
  2471      * a class or interface type, ordered by ClassSymbol.precedes
  2472      * (that is, subclasses come first, arbitrary but fixed
  2473      * otherwise).
  2474      */
  2475     private Map<Type,List<Type>> closureCache = new HashMap<Type,List<Type>>();
  2477     /**
  2478      * Returns the closure of a class or interface type.
  2479      */
  2480     public List<Type> closure(Type t) {
  2481         List<Type> cl = closureCache.get(t);
  2482         if (cl == null) {
  2483             Type st = supertype(t);
  2484             if (!t.isCompound()) {
  2485                 if (st.tag == CLASS) {
  2486                     cl = insert(closure(st), t);
  2487                 } else if (st.tag == TYPEVAR) {
  2488                     cl = closure(st).prepend(t);
  2489                 } else {
  2490                     cl = List.of(t);
  2492             } else {
  2493                 cl = closure(supertype(t));
  2495             for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail)
  2496                 cl = union(cl, closure(l.head));
  2497             closureCache.put(t, cl);
  2499         return cl;
  2502     /**
  2503      * Insert a type in a closure
  2504      */
  2505     public List<Type> insert(List<Type> cl, Type t) {
  2506         if (cl.isEmpty() || t.tsym.precedes(cl.head.tsym, this)) {
  2507             return cl.prepend(t);
  2508         } else if (cl.head.tsym.precedes(t.tsym, this)) {
  2509             return insert(cl.tail, t).prepend(cl.head);
  2510         } else {
  2511             return cl;
  2515     /**
  2516      * Form the union of two closures
  2517      */
  2518     public List<Type> union(List<Type> cl1, List<Type> cl2) {
  2519         if (cl1.isEmpty()) {
  2520             return cl2;
  2521         } else if (cl2.isEmpty()) {
  2522             return cl1;
  2523         } else if (cl1.head.tsym.precedes(cl2.head.tsym, this)) {
  2524             return union(cl1.tail, cl2).prepend(cl1.head);
  2525         } else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) {
  2526             return union(cl1, cl2.tail).prepend(cl2.head);
  2527         } else {
  2528             return union(cl1.tail, cl2.tail).prepend(cl1.head);
  2532     /**
  2533      * Intersect two closures
  2534      */
  2535     public List<Type> intersect(List<Type> cl1, List<Type> cl2) {
  2536         if (cl1 == cl2)
  2537             return cl1;
  2538         if (cl1.isEmpty() || cl2.isEmpty())
  2539             return List.nil();
  2540         if (cl1.head.tsym.precedes(cl2.head.tsym, this))
  2541             return intersect(cl1.tail, cl2);
  2542         if (cl2.head.tsym.precedes(cl1.head.tsym, this))
  2543             return intersect(cl1, cl2.tail);
  2544         if (isSameType(cl1.head, cl2.head))
  2545             return intersect(cl1.tail, cl2.tail).prepend(cl1.head);
  2546         if (cl1.head.tsym == cl2.head.tsym &&
  2547             cl1.head.tag == CLASS && cl2.head.tag == CLASS) {
  2548             if (cl1.head.isParameterized() && cl2.head.isParameterized()) {
  2549                 Type merge = merge(cl1.head,cl2.head);
  2550                 return intersect(cl1.tail, cl2.tail).prepend(merge);
  2552             if (cl1.head.isRaw() || cl2.head.isRaw())
  2553                 return intersect(cl1.tail, cl2.tail).prepend(erasure(cl1.head));
  2555         return intersect(cl1.tail, cl2.tail);
  2557     // where
  2558         class TypePair {
  2559             final Type t1;
  2560             final Type t2;
  2561             TypePair(Type t1, Type t2) {
  2562                 this.t1 = t1;
  2563                 this.t2 = t2;
  2565             @Override
  2566             public int hashCode() {
  2567                 return 127 * Types.hashCode(t1) + Types.hashCode(t2);
  2569             @Override
  2570             public boolean equals(Object obj) {
  2571                 if (!(obj instanceof TypePair))
  2572                     return false;
  2573                 TypePair typePair = (TypePair)obj;
  2574                 return isSameType(t1, typePair.t1)
  2575                     && isSameType(t2, typePair.t2);
  2578         Set<TypePair> mergeCache = new HashSet<TypePair>();
  2579         private Type merge(Type c1, Type c2) {
  2580             ClassType class1 = (ClassType) c1;
  2581             List<Type> act1 = class1.getTypeArguments();
  2582             ClassType class2 = (ClassType) c2;
  2583             List<Type> act2 = class2.getTypeArguments();
  2584             ListBuffer<Type> merged = new ListBuffer<Type>();
  2585             List<Type> typarams = class1.tsym.type.getTypeArguments();
  2587             while (act1.nonEmpty() && act2.nonEmpty() && typarams.nonEmpty()) {
  2588                 if (containsType(act1.head, act2.head)) {
  2589                     merged.append(act1.head);
  2590                 } else if (containsType(act2.head, act1.head)) {
  2591                     merged.append(act2.head);
  2592                 } else {
  2593                     TypePair pair = new TypePair(c1, c2);
  2594                     Type m;
  2595                     if (mergeCache.add(pair)) {
  2596                         m = new WildcardType(lub(upperBound(act1.head),
  2597                                                  upperBound(act2.head)),
  2598                                              BoundKind.EXTENDS,
  2599                                              syms.boundClass);
  2600                         mergeCache.remove(pair);
  2601                     } else {
  2602                         m = new WildcardType(syms.objectType,
  2603                                              BoundKind.UNBOUND,
  2604                                              syms.boundClass);
  2606                     merged.append(m.withTypeVar(typarams.head));
  2608                 act1 = act1.tail;
  2609                 act2 = act2.tail;
  2610                 typarams = typarams.tail;
  2612             assert(act1.isEmpty() && act2.isEmpty() && typarams.isEmpty());
  2613             return new ClassType(class1.getEnclosingType(), merged.toList(), class1.tsym);
  2616     /**
  2617      * Return the minimum type of a closure, a compound type if no
  2618      * unique minimum exists.
  2619      */
  2620     private Type compoundMin(List<Type> cl) {
  2621         if (cl.isEmpty()) return syms.objectType;
  2622         List<Type> compound = closureMin(cl);
  2623         if (compound.isEmpty())
  2624             return null;
  2625         else if (compound.tail.isEmpty())
  2626             return compound.head;
  2627         else
  2628             return makeCompoundType(compound);
  2631     /**
  2632      * Return the minimum types of a closure, suitable for computing
  2633      * compoundMin or glb.
  2634      */
  2635     private List<Type> closureMin(List<Type> cl) {
  2636         ListBuffer<Type> classes = lb();
  2637         ListBuffer<Type> interfaces = lb();
  2638         while (!cl.isEmpty()) {
  2639             Type current = cl.head;
  2640             if (current.isInterface())
  2641                 interfaces.append(current);
  2642             else
  2643                 classes.append(current);
  2644             ListBuffer<Type> candidates = lb();
  2645             for (Type t : cl.tail) {
  2646                 if (!isSubtypeNoCapture(current, t))
  2647                     candidates.append(t);
  2649             cl = candidates.toList();
  2651         return classes.appendList(interfaces).toList();
  2654     /**
  2655      * Return the least upper bound of pair of types.  if the lub does
  2656      * not exist return null.
  2657      */
  2658     public Type lub(Type t1, Type t2) {
  2659         return lub(List.of(t1, t2));
  2662     /**
  2663      * Return the least upper bound (lub) of set of types.  If the lub
  2664      * does not exist return the type of null (bottom).
  2665      */
  2666     public Type lub(List<Type> ts) {
  2667         final int ARRAY_BOUND = 1;
  2668         final int CLASS_BOUND = 2;
  2669         int boundkind = 0;
  2670         for (Type t : ts) {
  2671             switch (t.tag) {
  2672             case CLASS:
  2673                 boundkind |= CLASS_BOUND;
  2674                 break;
  2675             case ARRAY:
  2676                 boundkind |= ARRAY_BOUND;
  2677                 break;
  2678             case  TYPEVAR:
  2679                 do {
  2680                     t = t.getUpperBound();
  2681                 } while (t.tag == TYPEVAR);
  2682                 if (t.tag == ARRAY) {
  2683                     boundkind |= ARRAY_BOUND;
  2684                 } else {
  2685                     boundkind |= CLASS_BOUND;
  2687                 break;
  2688             default:
  2689                 if (t.isPrimitive())
  2690                     return syms.errType;
  2693         switch (boundkind) {
  2694         case 0:
  2695             return syms.botType;
  2697         case ARRAY_BOUND:
  2698             // calculate lub(A[], B[])
  2699             List<Type> elements = Type.map(ts, elemTypeFun);
  2700             for (Type t : elements) {
  2701                 if (t.isPrimitive()) {
  2702                     // if a primitive type is found, then return
  2703                     // arraySuperType unless all the types are the
  2704                     // same
  2705                     Type first = ts.head;
  2706                     for (Type s : ts.tail) {
  2707                         if (!isSameType(first, s)) {
  2708                              // lub(int[], B[]) is Cloneable & Serializable
  2709                             return arraySuperType();
  2712                     // all the array types are the same, return one
  2713                     // lub(int[], int[]) is int[]
  2714                     return first;
  2717             // lub(A[], B[]) is lub(A, B)[]
  2718             return new ArrayType(lub(elements), syms.arrayClass);
  2720         case CLASS_BOUND:
  2721             // calculate lub(A, B)
  2722             while (ts.head.tag != CLASS && ts.head.tag != TYPEVAR)
  2723                 ts = ts.tail;
  2724             assert !ts.isEmpty();
  2725             List<Type> cl = closure(ts.head);
  2726             for (Type t : ts.tail) {
  2727                 if (t.tag == CLASS || t.tag == TYPEVAR)
  2728                     cl = intersect(cl, closure(t));
  2730             return compoundMin(cl);
  2732         default:
  2733             // calculate lub(A, B[])
  2734             List<Type> classes = List.of(arraySuperType());
  2735             for (Type t : ts) {
  2736                 if (t.tag != ARRAY) // Filter out any arrays
  2737                     classes = classes.prepend(t);
  2739             // lub(A, B[]) is lub(A, arraySuperType)
  2740             return lub(classes);
  2743     // where
  2744         private Type arraySuperType = null;
  2745         private Type arraySuperType() {
  2746             // initialized lazily to avoid problems during compiler startup
  2747             if (arraySuperType == null) {
  2748                 synchronized (this) {
  2749                     if (arraySuperType == null) {
  2750                         // JLS 10.8: all arrays implement Cloneable and Serializable.
  2751                         arraySuperType = makeCompoundType(List.of(syms.serializableType,
  2752                                                                   syms.cloneableType),
  2753                                                           syms.objectType);
  2757             return arraySuperType;
  2759     // </editor-fold>
  2761     // <editor-fold defaultstate="collapsed" desc="Greatest lower bound">
  2762     public Type glb(List<Type> ts) {
  2763         Type t1 = ts.head;
  2764         for (Type t2 : ts.tail) {
  2765             if (t1.isErroneous())
  2766                 return t1;
  2767             t1 = glb(t1, t2);
  2769         return t1;
  2771     //where
  2772     public Type glb(Type t, Type s) {
  2773         if (s == null)
  2774             return t;
  2775         else if (t.isPrimitive() || s.isPrimitive())
  2776             return syms.errType;
  2777         else if (isSubtypeNoCapture(t, s))
  2778             return t;
  2779         else if (isSubtypeNoCapture(s, t))
  2780             return s;
  2782         List<Type> closure = union(closure(t), closure(s));
  2783         List<Type> bounds = closureMin(closure);
  2785         if (bounds.isEmpty()) {             // length == 0
  2786             return syms.objectType;
  2787         } else if (bounds.tail.isEmpty()) { // length == 1
  2788             return bounds.head;
  2789         } else {                            // length > 1
  2790             int classCount = 0;
  2791             for (Type bound : bounds)
  2792                 if (!bound.isInterface())
  2793                     classCount++;
  2794             if (classCount > 1)
  2795                 return createErrorType(t);
  2797         return makeCompoundType(bounds);
  2799     // </editor-fold>
  2801     // <editor-fold defaultstate="collapsed" desc="hashCode">
  2802     /**
  2803      * Compute a hash code on a type.
  2804      */
  2805     public static int hashCode(Type t) {
  2806         return hashCode.visit(t);
  2808     // where
  2809         private static final UnaryVisitor<Integer> hashCode = new UnaryVisitor<Integer>() {
  2811             public Integer visitType(Type t, Void ignored) {
  2812                 return t.tag;
  2815             @Override
  2816             public Integer visitClassType(ClassType t, Void ignored) {
  2817                 int result = visit(t.getEnclosingType());
  2818                 result *= 127;
  2819                 result += t.tsym.flatName().hashCode();
  2820                 for (Type s : t.getTypeArguments()) {
  2821                     result *= 127;
  2822                     result += visit(s);
  2824                 return result;
  2827             @Override
  2828             public Integer visitWildcardType(WildcardType t, Void ignored) {
  2829                 int result = t.kind.hashCode();
  2830                 if (t.type != null) {
  2831                     result *= 127;
  2832                     result += visit(t.type);
  2834                 return result;
  2837             @Override
  2838             public Integer visitArrayType(ArrayType t, Void ignored) {
  2839                 return visit(t.elemtype) + 12;
  2842             @Override
  2843             public Integer visitTypeVar(TypeVar t, Void ignored) {
  2844                 return System.identityHashCode(t.tsym);
  2847             @Override
  2848             public Integer visitUndetVar(UndetVar t, Void ignored) {
  2849                 return System.identityHashCode(t);
  2852             @Override
  2853             public Integer visitErrorType(ErrorType t, Void ignored) {
  2854                 return 0;
  2856         };
  2857     // </editor-fold>
  2859     // <editor-fold defaultstate="collapsed" desc="Return-Type-Substitutable">
  2860     /**
  2861      * Does t have a result that is a subtype of the result type of s,
  2862      * suitable for covariant returns?  It is assumed that both types
  2863      * are (possibly polymorphic) method types.  Monomorphic method
  2864      * types are handled in the obvious way.  Polymorphic method types
  2865      * require renaming all type variables of one to corresponding
  2866      * type variables in the other, where correspondence is by
  2867      * position in the type parameter list. */
  2868     public boolean resultSubtype(Type t, Type s, Warner warner) {
  2869         List<Type> tvars = t.getTypeArguments();
  2870         List<Type> svars = s.getTypeArguments();
  2871         Type tres = t.getReturnType();
  2872         Type sres = subst(s.getReturnType(), svars, tvars);
  2873         return covariantReturnType(tres, sres, warner);
  2876     /**
  2877      * Return-Type-Substitutable.
  2878      * @see <a href="http://java.sun.com/docs/books/jls/">The Java
  2879      * Language Specification, Third Ed. (8.4.5)</a>
  2880      */
  2881     public boolean returnTypeSubstitutable(Type r1, Type r2) {
  2882         if (hasSameArgs(r1, r2))
  2883             return resultSubtype(r1, r2, Warner.noWarnings);
  2884         else
  2885             return covariantReturnType(r1.getReturnType(),
  2886                                        erasure(r2.getReturnType()),
  2887                                        Warner.noWarnings);
  2890     public boolean returnTypeSubstitutable(Type r1,
  2891                                            Type r2, Type r2res,
  2892                                            Warner warner) {
  2893         if (isSameType(r1.getReturnType(), r2res))
  2894             return true;
  2895         if (r1.getReturnType().isPrimitive() || r2res.isPrimitive())
  2896             return false;
  2898         if (hasSameArgs(r1, r2))
  2899             return covariantReturnType(r1.getReturnType(), r2res, warner);
  2900         if (!source.allowCovariantReturns())
  2901             return false;
  2902         if (isSubtypeUnchecked(r1.getReturnType(), r2res, warner))
  2903             return true;
  2904         if (!isSubtype(r1.getReturnType(), erasure(r2res)))
  2905             return false;
  2906         warner.warnUnchecked();
  2907         return true;
  2910     /**
  2911      * Is t an appropriate return type in an overrider for a
  2912      * method that returns s?
  2913      */
  2914     public boolean covariantReturnType(Type t, Type s, Warner warner) {
  2915         return
  2916             isSameType(t, s) ||
  2917             source.allowCovariantReturns() &&
  2918             !t.isPrimitive() &&
  2919             !s.isPrimitive() &&
  2920             isAssignable(t, s, warner);
  2922     // </editor-fold>
  2924     // <editor-fold defaultstate="collapsed" desc="Box/unbox support">
  2925     /**
  2926      * Return the class that boxes the given primitive.
  2927      */
  2928     public ClassSymbol boxedClass(Type t) {
  2929         return reader.enterClass(syms.boxedName[t.tag]);
  2932     /**
  2933      * Return the boxed type if 't' is primitive, otherwise return 't' itself.
  2934      */
  2935     public Type boxedTypeOrType(Type t) {
  2936         return t.isPrimitive() ?
  2937             boxedClass(t).type :
  2938             t;
  2941     /**
  2942      * Return the primitive type corresponding to a boxed type.
  2943      */
  2944     public Type unboxedType(Type t) {
  2945         if (allowBoxing) {
  2946             for (int i=0; i<syms.boxedName.length; i++) {
  2947                 Name box = syms.boxedName[i];
  2948                 if (box != null &&
  2949                     asSuper(t, reader.enterClass(box)) != null)
  2950                     return syms.typeOfTag[i];
  2953         return Type.noType;
  2955     // </editor-fold>
  2957     // <editor-fold defaultstate="collapsed" desc="Capture conversion">
  2958     /*
  2959      * JLS 3rd Ed. 5.1.10 Capture Conversion:
  2961      * Let G name a generic type declaration with n formal type
  2962      * parameters A1 ... An with corresponding bounds U1 ... Un. There
  2963      * exists a capture conversion from G<T1 ... Tn> to G<S1 ... Sn>,
  2964      * where, for 1 <= i <= n:
  2966      * + If Ti is a wildcard type argument (4.5.1) of the form ? then
  2967      *   Si is a fresh type variable whose upper bound is
  2968      *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is the null
  2969      *   type.
  2971      * + If Ti is a wildcard type argument of the form ? extends Bi,
  2972      *   then Si is a fresh type variable whose upper bound is
  2973      *   glb(Bi, Ui[A1 := S1, ..., An := Sn]) and whose lower bound is
  2974      *   the null type, where glb(V1,... ,Vm) is V1 & ... & Vm. It is
  2975      *   a compile-time error if for any two classes (not interfaces)
  2976      *   Vi and Vj,Vi is not a subclass of Vj or vice versa.
  2978      * + If Ti is a wildcard type argument of the form ? super Bi,
  2979      *   then Si is a fresh type variable whose upper bound is
  2980      *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is Bi.
  2982      * + Otherwise, Si = Ti.
  2984      * Capture conversion on any type other than a parameterized type
  2985      * (4.5) acts as an identity conversion (5.1.1). Capture
  2986      * conversions never require a special action at run time and
  2987      * therefore never throw an exception at run time.
  2989      * Capture conversion is not applied recursively.
  2990      */
  2991     /**
  2992      * Capture conversion as specified by JLS 3rd Ed.
  2993      */
  2995     public List<Type> capture(List<Type> ts) {
  2996         List<Type> buf = List.nil();
  2997         for (Type t : ts) {
  2998             buf = buf.prepend(capture(t));
  3000         return buf.reverse();
  3002     public Type capture(Type t) {
  3003         if (t.tag != CLASS)
  3004             return t;
  3005         if (t.getEnclosingType() != Type.noType) {
  3006             Type capturedEncl = capture(t.getEnclosingType());
  3007             if (capturedEncl != t.getEnclosingType()) {
  3008                 Type type1 = memberType(capturedEncl, t.tsym);
  3009                 t = subst(type1, t.tsym.type.getTypeArguments(), t.getTypeArguments());
  3012         ClassType cls = (ClassType)t;
  3013         if (cls.isRaw() || !cls.isParameterized())
  3014             return cls;
  3016         ClassType G = (ClassType)cls.asElement().asType();
  3017         List<Type> A = G.getTypeArguments();
  3018         List<Type> T = cls.getTypeArguments();
  3019         List<Type> S = freshTypeVariables(T);
  3021         List<Type> currentA = A;
  3022         List<Type> currentT = T;
  3023         List<Type> currentS = S;
  3024         boolean captured = false;
  3025         while (!currentA.isEmpty() &&
  3026                !currentT.isEmpty() &&
  3027                !currentS.isEmpty()) {
  3028             if (currentS.head != currentT.head) {
  3029                 captured = true;
  3030                 WildcardType Ti = (WildcardType)currentT.head;
  3031                 Type Ui = currentA.head.getUpperBound();
  3032                 CapturedType Si = (CapturedType)currentS.head;
  3033                 if (Ui == null)
  3034                     Ui = syms.objectType;
  3035                 switch (Ti.kind) {
  3036                 case UNBOUND:
  3037                     Si.bound = subst(Ui, A, S);
  3038                     Si.lower = syms.botType;
  3039                     break;
  3040                 case EXTENDS:
  3041                     Si.bound = glb(Ti.getExtendsBound(), subst(Ui, A, S));
  3042                     Si.lower = syms.botType;
  3043                     break;
  3044                 case SUPER:
  3045                     Si.bound = subst(Ui, A, S);
  3046                     Si.lower = Ti.getSuperBound();
  3047                     break;
  3049                 if (Si.bound == Si.lower)
  3050                     currentS.head = Si.bound;
  3052             currentA = currentA.tail;
  3053             currentT = currentT.tail;
  3054             currentS = currentS.tail;
  3056         if (!currentA.isEmpty() || !currentT.isEmpty() || !currentS.isEmpty())
  3057             return erasure(t); // some "rare" type involved
  3059         if (captured)
  3060             return new ClassType(cls.getEnclosingType(), S, cls.tsym);
  3061         else
  3062             return t;
  3064     // where
  3065         public List<Type> freshTypeVariables(List<Type> types) {
  3066             ListBuffer<Type> result = lb();
  3067             for (Type t : types) {
  3068                 if (t.tag == WILDCARD) {
  3069                     Type bound = ((WildcardType)t).getExtendsBound();
  3070                     if (bound == null)
  3071                         bound = syms.objectType;
  3072                     result.append(new CapturedType(capturedName,
  3073                                                    syms.noSymbol,
  3074                                                    bound,
  3075                                                    syms.botType,
  3076                                                    (WildcardType)t));
  3077                 } else {
  3078                     result.append(t);
  3081             return result.toList();
  3083     // </editor-fold>
  3085     // <editor-fold defaultstate="collapsed" desc="Internal utility methods">
  3086     private List<Type> upperBounds(List<Type> ss) {
  3087         if (ss.isEmpty()) return ss;
  3088         Type head = upperBound(ss.head);
  3089         List<Type> tail = upperBounds(ss.tail);
  3090         if (head != ss.head || tail != ss.tail)
  3091             return tail.prepend(head);
  3092         else
  3093             return ss;
  3096     private boolean sideCast(Type from, Type to, Warner warn) {
  3097         // We are casting from type $from$ to type $to$, which are
  3098         // non-final unrelated types.  This method
  3099         // tries to reject a cast by transferring type parameters
  3100         // from $to$ to $from$ by common superinterfaces.
  3101         boolean reverse = false;
  3102         Type target = to;
  3103         if ((to.tsym.flags() & INTERFACE) == 0) {
  3104             assert (from.tsym.flags() & INTERFACE) != 0;
  3105             reverse = true;
  3106             to = from;
  3107             from = target;
  3109         List<Type> commonSupers = superClosure(to, erasure(from));
  3110         boolean giveWarning = commonSupers.isEmpty();
  3111         // The arguments to the supers could be unified here to
  3112         // get a more accurate analysis
  3113         while (commonSupers.nonEmpty()) {
  3114             Type t1 = asSuper(from, commonSupers.head.tsym);
  3115             Type t2 = commonSupers.head; // same as asSuper(to, commonSupers.head.tsym);
  3116             if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
  3117                 return false;
  3118             giveWarning = giveWarning || (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2));
  3119             commonSupers = commonSupers.tail;
  3121         if (giveWarning && !isReifiable(reverse ? from : to))
  3122             warn.warnUnchecked();
  3123         if (!source.allowCovariantReturns())
  3124             // reject if there is a common method signature with
  3125             // incompatible return types.
  3126             chk.checkCompatibleAbstracts(warn.pos(), from, to);
  3127         return true;
  3130     private boolean sideCastFinal(Type from, Type to, Warner warn) {
  3131         // We are casting from type $from$ to type $to$, which are
  3132         // unrelated types one of which is final and the other of
  3133         // which is an interface.  This method
  3134         // tries to reject a cast by transferring type parameters
  3135         // from the final class to the interface.
  3136         boolean reverse = false;
  3137         Type target = to;
  3138         if ((to.tsym.flags() & INTERFACE) == 0) {
  3139             assert (from.tsym.flags() & INTERFACE) != 0;
  3140             reverse = true;
  3141             to = from;
  3142             from = target;
  3144         assert (from.tsym.flags() & FINAL) != 0;
  3145         Type t1 = asSuper(from, to.tsym);
  3146         if (t1 == null) return false;
  3147         Type t2 = to;
  3148         if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
  3149             return false;
  3150         if (!source.allowCovariantReturns())
  3151             // reject if there is a common method signature with
  3152             // incompatible return types.
  3153             chk.checkCompatibleAbstracts(warn.pos(), from, to);
  3154         if (!isReifiable(target) &&
  3155             (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2)))
  3156             warn.warnUnchecked();
  3157         return true;
  3160     private boolean giveWarning(Type from, Type to) {
  3161         Type subFrom = asSub(from, to.tsym);
  3162         return to.isParameterized() &&
  3163                 (!(isUnbounded(to) ||
  3164                 isSubtype(from, to) ||
  3165                 ((subFrom != null) && containsType(to.allparams(), subFrom.allparams()))));
  3168     private List<Type> superClosure(Type t, Type s) {
  3169         List<Type> cl = List.nil();
  3170         for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
  3171             if (isSubtype(s, erasure(l.head))) {
  3172                 cl = insert(cl, l.head);
  3173             } else {
  3174                 cl = union(cl, superClosure(l.head, s));
  3177         return cl;
  3180     private boolean containsTypeEquivalent(Type t, Type s) {
  3181         return
  3182             isSameType(t, s) || // shortcut
  3183             containsType(t, s) && containsType(s, t);
  3186     // <editor-fold defaultstate="collapsed" desc="adapt">
  3187     /**
  3188      * Adapt a type by computing a substitution which maps a source
  3189      * type to a target type.
  3191      * @param source    the source type
  3192      * @param target    the target type
  3193      * @param from      the type variables of the computed substitution
  3194      * @param to        the types of the computed substitution.
  3195      */
  3196     public void adapt(Type source,
  3197                        Type target,
  3198                        ListBuffer<Type> from,
  3199                        ListBuffer<Type> to) throws AdaptFailure {
  3200         new Adapter(from, to).adapt(source, target);
  3203     class Adapter extends SimpleVisitor<Void, Type> {
  3205         ListBuffer<Type> from;
  3206         ListBuffer<Type> to;
  3207         Map<Symbol,Type> mapping;
  3209         Adapter(ListBuffer<Type> from, ListBuffer<Type> to) {
  3210             this.from = from;
  3211             this.to = to;
  3212             mapping = new HashMap<Symbol,Type>();
  3215         public void adapt(Type source, Type target) throws AdaptFailure {
  3216             visit(source, target);
  3217             List<Type> fromList = from.toList();
  3218             List<Type> toList = to.toList();
  3219             while (!fromList.isEmpty()) {
  3220                 Type val = mapping.get(fromList.head.tsym);
  3221                 if (toList.head != val)
  3222                     toList.head = val;
  3223                 fromList = fromList.tail;
  3224                 toList = toList.tail;
  3228         @Override
  3229         public Void visitClassType(ClassType source, Type target) throws AdaptFailure {
  3230             if (target.tag == CLASS)
  3231                 adaptRecursive(source.allparams(), target.allparams());
  3232             return null;
  3235         @Override
  3236         public Void visitArrayType(ArrayType source, Type target) throws AdaptFailure {
  3237             if (target.tag == ARRAY)
  3238                 adaptRecursive(elemtype(source), elemtype(target));
  3239             return null;
  3242         @Override
  3243         public Void visitWildcardType(WildcardType source, Type target) throws AdaptFailure {
  3244             if (source.isExtendsBound())
  3245                 adaptRecursive(upperBound(source), upperBound(target));
  3246             else if (source.isSuperBound())
  3247                 adaptRecursive(lowerBound(source), lowerBound(target));
  3248             return null;
  3251         @Override
  3252         public Void visitTypeVar(TypeVar source, Type target) throws AdaptFailure {
  3253             // Check to see if there is
  3254             // already a mapping for $source$, in which case
  3255             // the old mapping will be merged with the new
  3256             Type val = mapping.get(source.tsym);
  3257             if (val != null) {
  3258                 if (val.isSuperBound() && target.isSuperBound()) {
  3259                     val = isSubtype(lowerBound(val), lowerBound(target))
  3260                         ? target : val;
  3261                 } else if (val.isExtendsBound() && target.isExtendsBound()) {
  3262                     val = isSubtype(upperBound(val), upperBound(target))
  3263                         ? val : target;
  3264                 } else if (!isSameType(val, target)) {
  3265                     throw new AdaptFailure();
  3267             } else {
  3268                 val = target;
  3269                 from.append(source);
  3270                 to.append(target);
  3272             mapping.put(source.tsym, val);
  3273             return null;
  3276         @Override
  3277         public Void visitType(Type source, Type target) {
  3278             return null;
  3281         private Set<TypePair> cache = new HashSet<TypePair>();
  3283         private void adaptRecursive(Type source, Type target) {
  3284             TypePair pair = new TypePair(source, target);
  3285             if (cache.add(pair)) {
  3286                 try {
  3287                     visit(source, target);
  3288                 } finally {
  3289                     cache.remove(pair);
  3294         private void adaptRecursive(List<Type> source, List<Type> target) {
  3295             if (source.length() == target.length()) {
  3296                 while (source.nonEmpty()) {
  3297                     adaptRecursive(source.head, target.head);
  3298                     source = source.tail;
  3299                     target = target.tail;
  3305     public static class AdaptFailure extends RuntimeException {
  3306         static final long serialVersionUID = -7490231548272701566L;
  3309     private void adaptSelf(Type t,
  3310                            ListBuffer<Type> from,
  3311                            ListBuffer<Type> to) {
  3312         try {
  3313             //if (t.tsym.type != t)
  3314                 adapt(t.tsym.type, t, from, to);
  3315         } catch (AdaptFailure ex) {
  3316             // Adapt should never fail calculating a mapping from
  3317             // t.tsym.type to t as there can be no merge problem.
  3318             throw new AssertionError(ex);
  3321     // </editor-fold>
  3323     /**
  3324      * Rewrite all type variables (universal quantifiers) in the given
  3325      * type to wildcards (existential quantifiers).  This is used to
  3326      * determine if a cast is allowed.  For example, if high is true
  3327      * and {@code T <: Number}, then {@code List<T>} is rewritten to
  3328      * {@code List<?  extends Number>}.  Since {@code List<Integer> <:
  3329      * List<? extends Number>} a {@code List<T>} can be cast to {@code
  3330      * List<Integer>} with a warning.
  3331      * @param t a type
  3332      * @param high if true return an upper bound; otherwise a lower
  3333      * bound
  3334      * @param rewriteTypeVars only rewrite captured wildcards if false;
  3335      * otherwise rewrite all type variables
  3336      * @return the type rewritten with wildcards (existential
  3337      * quantifiers) only
  3338      */
  3339     private Type rewriteQuantifiers(Type t, boolean high, boolean rewriteTypeVars) {
  3340         return new Rewriter(high, rewriteTypeVars).visit(t);
  3343     class Rewriter extends UnaryVisitor<Type> {
  3345         boolean high;
  3346         boolean rewriteTypeVars;
  3348         Rewriter(boolean high, boolean rewriteTypeVars) {
  3349             this.high = high;
  3350             this.rewriteTypeVars = rewriteTypeVars;
  3353         @Override
  3354         public Type visitClassType(ClassType t, Void s) {
  3355             ListBuffer<Type> rewritten = new ListBuffer<Type>();
  3356             boolean changed = false;
  3357             for (Type arg : t.allparams()) {
  3358                 Type bound = visit(arg);
  3359                 if (arg != bound) {
  3360                     changed = true;
  3362                 rewritten.append(bound);
  3364             if (changed)
  3365                 return subst(t.tsym.type,
  3366                         t.tsym.type.allparams(),
  3367                         rewritten.toList());
  3368             else
  3369                 return t;
  3372         public Type visitType(Type t, Void s) {
  3373             return high ? upperBound(t) : lowerBound(t);
  3376         @Override
  3377         public Type visitCapturedType(CapturedType t, Void s) {
  3378             Type bound = visitWildcardType(t.wildcard, null);
  3379             return (bound.contains(t)) ?
  3380                     (high ? syms.objectType : syms.botType) :
  3381                         bound;
  3384         @Override
  3385         public Type visitTypeVar(TypeVar t, Void s) {
  3386             if (rewriteTypeVars) {
  3387                 Type bound = high ?
  3388                     (t.bound.contains(t) ?
  3389                         syms.objectType :
  3390                         visit(t.bound)) :
  3391                     syms.botType;
  3392                 return rewriteAsWildcardType(bound, t);
  3394             else
  3395                 return t;
  3398         @Override
  3399         public Type visitWildcardType(WildcardType t, Void s) {
  3400             Type bound = high ? t.getExtendsBound() :
  3401                                 t.getSuperBound();
  3402             if (bound == null)
  3403             bound = high ? syms.objectType : syms.botType;
  3404             return rewriteAsWildcardType(visit(bound), t.bound);
  3407         private Type rewriteAsWildcardType(Type bound, TypeVar formal) {
  3408             return high ?
  3409                 makeExtendsWildcard(B(bound), formal) :
  3410                 makeSuperWildcard(B(bound), formal);
  3413         Type B(Type t) {
  3414             while (t.tag == WILDCARD) {
  3415                 WildcardType w = (WildcardType)t;
  3416                 t = high ?
  3417                     w.getExtendsBound() :
  3418                     w.getSuperBound();
  3419                 if (t == null) {
  3420                     t = high ? syms.objectType : syms.botType;
  3423             return t;
  3428     /**
  3429      * Create a wildcard with the given upper (extends) bound; create
  3430      * an unbounded wildcard if bound is Object.
  3432      * @param bound the upper bound
  3433      * @param formal the formal type parameter that will be
  3434      * substituted by the wildcard
  3435      */
  3436     private WildcardType makeExtendsWildcard(Type bound, TypeVar formal) {
  3437         if (bound == syms.objectType) {
  3438             return new WildcardType(syms.objectType,
  3439                                     BoundKind.UNBOUND,
  3440                                     syms.boundClass,
  3441                                     formal);
  3442         } else {
  3443             return new WildcardType(bound,
  3444                                     BoundKind.EXTENDS,
  3445                                     syms.boundClass,
  3446                                     formal);
  3450     /**
  3451      * Create a wildcard with the given lower (super) bound; create an
  3452      * unbounded wildcard if bound is bottom (type of {@code null}).
  3454      * @param bound the lower bound
  3455      * @param formal the formal type parameter that will be
  3456      * substituted by the wildcard
  3457      */
  3458     private WildcardType makeSuperWildcard(Type bound, TypeVar formal) {
  3459         if (bound.tag == BOT) {
  3460             return new WildcardType(syms.objectType,
  3461                                     BoundKind.UNBOUND,
  3462                                     syms.boundClass,
  3463                                     formal);
  3464         } else {
  3465             return new WildcardType(bound,
  3466                                     BoundKind.SUPER,
  3467                                     syms.boundClass,
  3468                                     formal);
  3472     /**
  3473      * A wrapper for a type that allows use in sets.
  3474      */
  3475     class SingletonType {
  3476         final Type t;
  3477         SingletonType(Type t) {
  3478             this.t = t;
  3480         public int hashCode() {
  3481             return Types.hashCode(t);
  3483         public boolean equals(Object obj) {
  3484             return (obj instanceof SingletonType) &&
  3485                 isSameType(t, ((SingletonType)obj).t);
  3487         public String toString() {
  3488             return t.toString();
  3491     // </editor-fold>
  3493     // <editor-fold defaultstate="collapsed" desc="Visitors">
  3494     /**
  3495      * A default visitor for types.  All visitor methods except
  3496      * visitType are implemented by delegating to visitType.  Concrete
  3497      * subclasses must provide an implementation of visitType and can
  3498      * override other methods as needed.
  3500      * @param <R> the return type of the operation implemented by this
  3501      * visitor; use Void if no return type is needed.
  3502      * @param <S> the type of the second argument (the first being the
  3503      * type itself) of the operation implemented by this visitor; use
  3504      * Void if a second argument is not needed.
  3505      */
  3506     public static abstract class DefaultTypeVisitor<R,S> implements Type.Visitor<R,S> {
  3507         final public R visit(Type t, S s)               { return t.accept(this, s); }
  3508         public R visitClassType(ClassType t, S s)       { return visitType(t, s); }
  3509         public R visitWildcardType(WildcardType t, S s) { return visitType(t, s); }
  3510         public R visitArrayType(ArrayType t, S s)       { return visitType(t, s); }
  3511         public R visitMethodType(MethodType t, S s)     { return visitType(t, s); }
  3512         public R visitPackageType(PackageType t, S s)   { return visitType(t, s); }
  3513         public R visitTypeVar(TypeVar t, S s)           { return visitType(t, s); }
  3514         public R visitCapturedType(CapturedType t, S s) { return visitType(t, s); }
  3515         public R visitForAll(ForAll t, S s)             { return visitType(t, s); }
  3516         public R visitUndetVar(UndetVar t, S s)         { return visitType(t, s); }
  3517         public R visitErrorType(ErrorType t, S s)       { return visitType(t, s); }
  3520     /**
  3521      * A default visitor for symbols.  All visitor methods except
  3522      * visitSymbol are implemented by delegating to visitSymbol.  Concrete
  3523      * subclasses must provide an implementation of visitSymbol and can
  3524      * override other methods as needed.
  3526      * @param <R> the return type of the operation implemented by this
  3527      * visitor; use Void if no return type is needed.
  3528      * @param <S> the type of the second argument (the first being the
  3529      * symbol itself) of the operation implemented by this visitor; use
  3530      * Void if a second argument is not needed.
  3531      */
  3532     public static abstract class DefaultSymbolVisitor<R,S> implements Symbol.Visitor<R,S> {
  3533         final public R visit(Symbol s, S arg)                   { return s.accept(this, arg); }
  3534         public R visitClassSymbol(ClassSymbol s, S arg)         { return visitSymbol(s, arg); }
  3535         public R visitMethodSymbol(MethodSymbol s, S arg)       { return visitSymbol(s, arg); }
  3536         public R visitOperatorSymbol(OperatorSymbol s, S arg)   { return visitSymbol(s, arg); }
  3537         public R visitPackageSymbol(PackageSymbol s, S arg)     { return visitSymbol(s, arg); }
  3538         public R visitTypeSymbol(TypeSymbol s, S arg)           { return visitSymbol(s, arg); }
  3539         public R visitVarSymbol(VarSymbol s, S arg)             { return visitSymbol(s, arg); }
  3542     /**
  3543      * A <em>simple</em> visitor for types.  This visitor is simple as
  3544      * captured wildcards, for-all types (generic methods), and
  3545      * undetermined type variables (part of inference) are hidden.
  3546      * Captured wildcards are hidden by treating them as type
  3547      * variables and the rest are hidden by visiting their qtypes.
  3549      * @param <R> the return type of the operation implemented by this
  3550      * visitor; use Void if no return type is needed.
  3551      * @param <S> the type of the second argument (the first being the
  3552      * type itself) of the operation implemented by this visitor; use
  3553      * Void if a second argument is not needed.
  3554      */
  3555     public static abstract class SimpleVisitor<R,S> extends DefaultTypeVisitor<R,S> {
  3556         @Override
  3557         public R visitCapturedType(CapturedType t, S s) {
  3558             return visitTypeVar(t, s);
  3560         @Override
  3561         public R visitForAll(ForAll t, S s) {
  3562             return visit(t.qtype, s);
  3564         @Override
  3565         public R visitUndetVar(UndetVar t, S s) {
  3566             return visit(t.qtype, s);
  3570     /**
  3571      * A plain relation on types.  That is a 2-ary function on the
  3572      * form Type&nbsp;&times;&nbsp;Type&nbsp;&rarr;&nbsp;Boolean.
  3573      * <!-- In plain text: Type x Type -> Boolean -->
  3574      */
  3575     public static abstract class TypeRelation extends SimpleVisitor<Boolean,Type> {}
  3577     /**
  3578      * A convenience visitor for implementing operations that only
  3579      * require one argument (the type itself), that is, unary
  3580      * operations.
  3582      * @param <R> the return type of the operation implemented by this
  3583      * visitor; use Void if no return type is needed.
  3584      */
  3585     public static abstract class UnaryVisitor<R> extends SimpleVisitor<R,Void> {
  3586         final public R visit(Type t) { return t.accept(this, null); }
  3589     /**
  3590      * A visitor for implementing a mapping from types to types.  The
  3591      * default behavior of this class is to implement the identity
  3592      * mapping (mapping a type to itself).  This can be overridden in
  3593      * subclasses.
  3595      * @param <S> the type of the second argument (the first being the
  3596      * type itself) of this mapping; use Void if a second argument is
  3597      * not needed.
  3598      */
  3599     public static class MapVisitor<S> extends DefaultTypeVisitor<Type,S> {
  3600         final public Type visit(Type t) { return t.accept(this, null); }
  3601         public Type visitType(Type t, S s) { return t; }
  3603     // </editor-fold>
  3606     // <editor-fold defaultstate="collapsed" desc="Annotation support">
  3608     public RetentionPolicy getRetention(Attribute.Compound a) {
  3609         RetentionPolicy vis = RetentionPolicy.CLASS; // the default
  3610         Attribute.Compound c = a.type.tsym.attribute(syms.retentionType.tsym);
  3611         if (c != null) {
  3612             Attribute value = c.member(names.value);
  3613             if (value != null && value instanceof Attribute.Enum) {
  3614                 Name levelName = ((Attribute.Enum)value).value.name;
  3615                 if (levelName == names.SOURCE) vis = RetentionPolicy.SOURCE;
  3616                 else if (levelName == names.CLASS) vis = RetentionPolicy.CLASS;
  3617                 else if (levelName == names.RUNTIME) vis = RetentionPolicy.RUNTIME;
  3618                 else ;// /* fail soft */ throw new AssertionError(levelName);
  3621         return vis;
  3623     // </editor-fold>

mercurial