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

Fri, 10 Dec 2010 15:23:42 +0000

author
mcimadamore
date
Fri, 10 Dec 2010 15:23:42 +0000
changeset 786
2ca5866a8dfb
parent 780
1d625fbe6c22
child 787
b1c98bfd4709
permissions
-rw-r--r--

7005671: Regression: compiler accepts invalid cast from X[] to primitive array
Summary: regression in type conversion after 292 changes
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 (upcast ? giveWarning(a, b) :
  1037                                     giveWarning(b, a))
  1038                                     warnStack.head.warnUnchecked();
  1039                                 return true;
  1042                         if (isReifiable(s))
  1043                             return isSubtypeUnchecked(a, b);
  1044                         else
  1045                             return isSubtypeUnchecked(a, b, warnStack.head);
  1048                     // Sidecast
  1049                     if (s.tag == CLASS) {
  1050                         if ((s.tsym.flags() & INTERFACE) != 0) {
  1051                             return ((t.tsym.flags() & FINAL) == 0)
  1052                                 ? sideCast(t, s, warnStack.head)
  1053                                 : sideCastFinal(t, s, warnStack.head);
  1054                         } else if ((t.tsym.flags() & INTERFACE) != 0) {
  1055                             return ((s.tsym.flags() & FINAL) == 0)
  1056                                 ? sideCast(t, s, warnStack.head)
  1057                                 : sideCastFinal(t, s, warnStack.head);
  1058                         } else {
  1059                             // unrelated class types
  1060                             return false;
  1064                 return false;
  1067             @Override
  1068             public Boolean visitArrayType(ArrayType t, Type s) {
  1069                 switch (s.tag) {
  1070                 case ERROR:
  1071                 case BOT:
  1072                     return true;
  1073                 case TYPEVAR:
  1074                     if (isCastable(s, t, Warner.noWarnings)) {
  1075                         warnStack.head.warnUnchecked();
  1076                         return true;
  1077                     } else {
  1078                         return false;
  1080                 case CLASS:
  1081                     return isSubtype(t, s);
  1082                 case ARRAY:
  1083                     if (elemtype(t).tag <= lastBaseTag ||
  1084                             elemtype(s).tag <= lastBaseTag) {
  1085                         return elemtype(t).tag == elemtype(s).tag;
  1086                     } else {
  1087                         return visit(elemtype(t), elemtype(s));
  1089                 default:
  1090                     return false;
  1094             @Override
  1095             public Boolean visitTypeVar(TypeVar t, Type s) {
  1096                 switch (s.tag) {
  1097                 case ERROR:
  1098                 case BOT:
  1099                     return true;
  1100                 case TYPEVAR:
  1101                     if (isSubtype(t, s)) {
  1102                         return true;
  1103                     } else if (isCastable(t.bound, s, Warner.noWarnings)) {
  1104                         warnStack.head.warnUnchecked();
  1105                         return true;
  1106                     } else {
  1107                         return false;
  1109                 default:
  1110                     return isCastable(t.bound, s, warnStack.head);
  1114             @Override
  1115             public Boolean visitErrorType(ErrorType t, Type s) {
  1116                 return true;
  1118         };
  1119     // </editor-fold>
  1121     // <editor-fold defaultstate="collapsed" desc="disjointTypes">
  1122     public boolean disjointTypes(List<Type> ts, List<Type> ss) {
  1123         while (ts.tail != null && ss.tail != null) {
  1124             if (disjointType(ts.head, ss.head)) return true;
  1125             ts = ts.tail;
  1126             ss = ss.tail;
  1128         return false;
  1131     /**
  1132      * Two types or wildcards are considered disjoint if it can be
  1133      * proven that no type can be contained in both. It is
  1134      * conservative in that it is allowed to say that two types are
  1135      * not disjoint, even though they actually are.
  1137      * The type C<X> is castable to C<Y> exactly if X and Y are not
  1138      * disjoint.
  1139      */
  1140     public boolean disjointType(Type t, Type s) {
  1141         return disjointType.visit(t, s);
  1143     // where
  1144         private TypeRelation disjointType = new TypeRelation() {
  1146             private Set<TypePair> cache = new HashSet<TypePair>();
  1148             public Boolean visitType(Type t, Type s) {
  1149                 if (s.tag == WILDCARD)
  1150                     return visit(s, t);
  1151                 else
  1152                     return notSoftSubtypeRecursive(t, s) || notSoftSubtypeRecursive(s, t);
  1155             private boolean isCastableRecursive(Type t, Type s) {
  1156                 TypePair pair = new TypePair(t, s);
  1157                 if (cache.add(pair)) {
  1158                     try {
  1159                         return Types.this.isCastable(t, s);
  1160                     } finally {
  1161                         cache.remove(pair);
  1163                 } else {
  1164                     return true;
  1168             private boolean notSoftSubtypeRecursive(Type t, Type s) {
  1169                 TypePair pair = new TypePair(t, s);
  1170                 if (cache.add(pair)) {
  1171                     try {
  1172                         return Types.this.notSoftSubtype(t, s);
  1173                     } finally {
  1174                         cache.remove(pair);
  1176                 } else {
  1177                     return false;
  1181             @Override
  1182             public Boolean visitWildcardType(WildcardType t, Type s) {
  1183                 if (t.isUnbound())
  1184                     return false;
  1186                 if (s.tag != WILDCARD) {
  1187                     if (t.isExtendsBound())
  1188                         return notSoftSubtypeRecursive(s, t.type);
  1189                     else // isSuperBound()
  1190                         return notSoftSubtypeRecursive(t.type, s);
  1193                 if (s.isUnbound())
  1194                     return false;
  1196                 if (t.isExtendsBound()) {
  1197                     if (s.isExtendsBound())
  1198                         return !isCastableRecursive(t.type, upperBound(s));
  1199                     else if (s.isSuperBound())
  1200                         return notSoftSubtypeRecursive(lowerBound(s), t.type);
  1201                 } else if (t.isSuperBound()) {
  1202                     if (s.isExtendsBound())
  1203                         return notSoftSubtypeRecursive(t.type, upperBound(s));
  1205                 return false;
  1207         };
  1208     // </editor-fold>
  1210     // <editor-fold defaultstate="collapsed" desc="lowerBoundArgtypes">
  1211     /**
  1212      * Returns the lower bounds of the formals of a method.
  1213      */
  1214     public List<Type> lowerBoundArgtypes(Type t) {
  1215         return map(t.getParameterTypes(), lowerBoundMapping);
  1217     private final Mapping lowerBoundMapping = new Mapping("lowerBound") {
  1218             public Type apply(Type t) {
  1219                 return lowerBound(t);
  1221         };
  1222     // </editor-fold>
  1224     // <editor-fold defaultstate="collapsed" desc="notSoftSubtype">
  1225     /**
  1226      * This relation answers the question: is impossible that
  1227      * something of type `t' can be a subtype of `s'? This is
  1228      * different from the question "is `t' not a subtype of `s'?"
  1229      * when type variables are involved: Integer is not a subtype of T
  1230      * where <T extends Number> but it is not true that Integer cannot
  1231      * possibly be a subtype of T.
  1232      */
  1233     public boolean notSoftSubtype(Type t, Type s) {
  1234         if (t == s) return false;
  1235         if (t.tag == TYPEVAR) {
  1236             TypeVar tv = (TypeVar) t;
  1237             return !isCastable(tv.bound,
  1238                                relaxBound(s),
  1239                                Warner.noWarnings);
  1241         if (s.tag != WILDCARD)
  1242             s = upperBound(s);
  1244         return !isSubtype(t, relaxBound(s));
  1247     private Type relaxBound(Type t) {
  1248         if (t.tag == TYPEVAR) {
  1249             while (t.tag == TYPEVAR)
  1250                 t = t.getUpperBound();
  1251             t = rewriteQuantifiers(t, true, true);
  1253         return t;
  1255     // </editor-fold>
  1257     // <editor-fold defaultstate="collapsed" desc="isReifiable">
  1258     public boolean isReifiable(Type t) {
  1259         return isReifiable.visit(t);
  1261     // where
  1262         private UnaryVisitor<Boolean> isReifiable = new UnaryVisitor<Boolean>() {
  1264             public Boolean visitType(Type t, Void ignored) {
  1265                 return true;
  1268             @Override
  1269             public Boolean visitClassType(ClassType t, Void ignored) {
  1270                 if (t.isCompound())
  1271                     return false;
  1272                 else {
  1273                     if (!t.isParameterized())
  1274                         return true;
  1276                     for (Type param : t.allparams()) {
  1277                         if (!param.isUnbound())
  1278                             return false;
  1280                     return true;
  1284             @Override
  1285             public Boolean visitArrayType(ArrayType t, Void ignored) {
  1286                 return visit(t.elemtype);
  1289             @Override
  1290             public Boolean visitTypeVar(TypeVar t, Void ignored) {
  1291                 return false;
  1293         };
  1294     // </editor-fold>
  1296     // <editor-fold defaultstate="collapsed" desc="Array Utils">
  1297     public boolean isArray(Type t) {
  1298         while (t.tag == WILDCARD)
  1299             t = upperBound(t);
  1300         return t.tag == ARRAY;
  1303     /**
  1304      * The element type of an array.
  1305      */
  1306     public Type elemtype(Type t) {
  1307         switch (t.tag) {
  1308         case WILDCARD:
  1309             return elemtype(upperBound(t));
  1310         case ARRAY:
  1311             return ((ArrayType)t).elemtype;
  1312         case FORALL:
  1313             return elemtype(((ForAll)t).qtype);
  1314         case ERROR:
  1315             return t;
  1316         default:
  1317             return null;
  1321     /**
  1322      * Mapping to take element type of an arraytype
  1323      */
  1324     private Mapping elemTypeFun = new Mapping ("elemTypeFun") {
  1325         public Type apply(Type t) { return elemtype(t); }
  1326     };
  1328     /**
  1329      * The number of dimensions of an array type.
  1330      */
  1331     public int dimensions(Type t) {
  1332         int result = 0;
  1333         while (t.tag == ARRAY) {
  1334             result++;
  1335             t = elemtype(t);
  1337         return result;
  1339     // </editor-fold>
  1341     // <editor-fold defaultstate="collapsed" desc="asSuper">
  1342     /**
  1343      * Return the (most specific) base type of t that starts with the
  1344      * given symbol.  If none exists, return null.
  1346      * @param t a type
  1347      * @param sym a symbol
  1348      */
  1349     public Type asSuper(Type t, Symbol sym) {
  1350         return asSuper.visit(t, sym);
  1352     // where
  1353         private SimpleVisitor<Type,Symbol> asSuper = new SimpleVisitor<Type,Symbol>() {
  1355             public Type visitType(Type t, Symbol sym) {
  1356                 return null;
  1359             @Override
  1360             public Type visitClassType(ClassType t, Symbol sym) {
  1361                 if (t.tsym == sym)
  1362                     return t;
  1364                 Type st = supertype(t);
  1365                 if (st.tag == CLASS || st.tag == TYPEVAR || st.tag == ERROR) {
  1366                     Type x = asSuper(st, sym);
  1367                     if (x != null)
  1368                         return x;
  1370                 if ((sym.flags() & INTERFACE) != 0) {
  1371                     for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
  1372                         Type x = asSuper(l.head, sym);
  1373                         if (x != null)
  1374                             return x;
  1377                 return null;
  1380             @Override
  1381             public Type visitArrayType(ArrayType t, Symbol sym) {
  1382                 return isSubtype(t, sym.type) ? sym.type : null;
  1385             @Override
  1386             public Type visitTypeVar(TypeVar t, Symbol sym) {
  1387                 if (t.tsym == sym)
  1388                     return t;
  1389                 else
  1390                     return asSuper(t.bound, sym);
  1393             @Override
  1394             public Type visitErrorType(ErrorType t, Symbol sym) {
  1395                 return t;
  1397         };
  1399     /**
  1400      * Return the base type of t or any of its outer types that starts
  1401      * with the given symbol.  If none exists, return null.
  1403      * @param t a type
  1404      * @param sym a symbol
  1405      */
  1406     public Type asOuterSuper(Type t, Symbol sym) {
  1407         switch (t.tag) {
  1408         case CLASS:
  1409             do {
  1410                 Type s = asSuper(t, sym);
  1411                 if (s != null) return s;
  1412                 t = t.getEnclosingType();
  1413             } while (t.tag == CLASS);
  1414             return null;
  1415         case ARRAY:
  1416             return isSubtype(t, sym.type) ? sym.type : null;
  1417         case TYPEVAR:
  1418             return asSuper(t, sym);
  1419         case ERROR:
  1420             return t;
  1421         default:
  1422             return null;
  1426     /**
  1427      * Return the base type of t or any of its enclosing types that
  1428      * starts with the given symbol.  If none exists, return null.
  1430      * @param t a type
  1431      * @param sym a symbol
  1432      */
  1433     public Type asEnclosingSuper(Type t, Symbol sym) {
  1434         switch (t.tag) {
  1435         case CLASS:
  1436             do {
  1437                 Type s = asSuper(t, sym);
  1438                 if (s != null) return s;
  1439                 Type outer = t.getEnclosingType();
  1440                 t = (outer.tag == CLASS) ? outer :
  1441                     (t.tsym.owner.enclClass() != null) ? t.tsym.owner.enclClass().type :
  1442                     Type.noType;
  1443             } while (t.tag == CLASS);
  1444             return null;
  1445         case ARRAY:
  1446             return isSubtype(t, sym.type) ? sym.type : null;
  1447         case TYPEVAR:
  1448             return asSuper(t, sym);
  1449         case ERROR:
  1450             return t;
  1451         default:
  1452             return null;
  1455     // </editor-fold>
  1457     // <editor-fold defaultstate="collapsed" desc="memberType">
  1458     /**
  1459      * The type of given symbol, seen as a member of t.
  1461      * @param t a type
  1462      * @param sym a symbol
  1463      */
  1464     public Type memberType(Type t, Symbol sym) {
  1465         return (sym.flags() & STATIC) != 0
  1466             ? sym.type
  1467             : memberType.visit(t, sym);
  1469     // where
  1470         private SimpleVisitor<Type,Symbol> memberType = new SimpleVisitor<Type,Symbol>() {
  1472             public Type visitType(Type t, Symbol sym) {
  1473                 return sym.type;
  1476             @Override
  1477             public Type visitWildcardType(WildcardType t, Symbol sym) {
  1478                 return memberType(upperBound(t), sym);
  1481             @Override
  1482             public Type visitClassType(ClassType t, Symbol sym) {
  1483                 Symbol owner = sym.owner;
  1484                 long flags = sym.flags();
  1485                 if (((flags & STATIC) == 0) && owner.type.isParameterized()) {
  1486                     Type base = asOuterSuper(t, owner);
  1487                     //if t is an intersection type T = CT & I1 & I2 ... & In
  1488                     //its supertypes CT, I1, ... In might contain wildcards
  1489                     //so we need to go through capture conversion
  1490                     base = t.isCompound() ? capture(base) : base;
  1491                     if (base != null) {
  1492                         List<Type> ownerParams = owner.type.allparams();
  1493                         List<Type> baseParams = base.allparams();
  1494                         if (ownerParams.nonEmpty()) {
  1495                             if (baseParams.isEmpty()) {
  1496                                 // then base is a raw type
  1497                                 return erasure(sym.type);
  1498                             } else {
  1499                                 return subst(sym.type, ownerParams, baseParams);
  1504                 return sym.type;
  1507             @Override
  1508             public Type visitTypeVar(TypeVar t, Symbol sym) {
  1509                 return memberType(t.bound, sym);
  1512             @Override
  1513             public Type visitErrorType(ErrorType t, Symbol sym) {
  1514                 return t;
  1516         };
  1517     // </editor-fold>
  1519     // <editor-fold defaultstate="collapsed" desc="isAssignable">
  1520     public boolean isAssignable(Type t, Type s) {
  1521         return isAssignable(t, s, Warner.noWarnings);
  1524     /**
  1525      * Is t assignable to s?<br>
  1526      * Equivalent to subtype except for constant values and raw
  1527      * types.<br>
  1528      * (not defined for Method and ForAll types)
  1529      */
  1530     public boolean isAssignable(Type t, Type s, Warner warn) {
  1531         if (t.tag == ERROR)
  1532             return true;
  1533         if (t.tag <= INT && t.constValue() != null) {
  1534             int value = ((Number)t.constValue()).intValue();
  1535             switch (s.tag) {
  1536             case BYTE:
  1537                 if (Byte.MIN_VALUE <= value && value <= Byte.MAX_VALUE)
  1538                     return true;
  1539                 break;
  1540             case CHAR:
  1541                 if (Character.MIN_VALUE <= value && value <= Character.MAX_VALUE)
  1542                     return true;
  1543                 break;
  1544             case SHORT:
  1545                 if (Short.MIN_VALUE <= value && value <= Short.MAX_VALUE)
  1546                     return true;
  1547                 break;
  1548             case INT:
  1549                 return true;
  1550             case CLASS:
  1551                 switch (unboxedType(s).tag) {
  1552                 case BYTE:
  1553                 case CHAR:
  1554                 case SHORT:
  1555                     return isAssignable(t, unboxedType(s), warn);
  1557                 break;
  1560         return isConvertible(t, s, warn);
  1562     // </editor-fold>
  1564     // <editor-fold defaultstate="collapsed" desc="erasure">
  1565     /**
  1566      * The erasure of t {@code |t|} -- the type that results when all
  1567      * type parameters in t are deleted.
  1568      */
  1569     public Type erasure(Type t) {
  1570         return erasure(t, false);
  1572     //where
  1573     private Type erasure(Type t, boolean recurse) {
  1574         if (t.tag <= lastBaseTag)
  1575             return t; /* fast special case */
  1576         else
  1577             return erasure.visit(t, recurse);
  1579     // where
  1580         private SimpleVisitor<Type, Boolean> erasure = new SimpleVisitor<Type, Boolean>() {
  1581             public Type visitType(Type t, Boolean recurse) {
  1582                 if (t.tag <= lastBaseTag)
  1583                     return t; /*fast special case*/
  1584                 else
  1585                     return t.map(recurse ? erasureRecFun : erasureFun);
  1588             @Override
  1589             public Type visitWildcardType(WildcardType t, Boolean recurse) {
  1590                 return erasure(upperBound(t), recurse);
  1593             @Override
  1594             public Type visitClassType(ClassType t, Boolean recurse) {
  1595                 Type erased = t.tsym.erasure(Types.this);
  1596                 if (recurse) {
  1597                     erased = new ErasedClassType(erased.getEnclosingType(),erased.tsym);
  1599                 return erased;
  1602             @Override
  1603             public Type visitTypeVar(TypeVar t, Boolean recurse) {
  1604                 return erasure(t.bound, recurse);
  1607             @Override
  1608             public Type visitErrorType(ErrorType t, Boolean recurse) {
  1609                 return t;
  1611         };
  1613     private Mapping erasureFun = new Mapping ("erasure") {
  1614             public Type apply(Type t) { return erasure(t); }
  1615         };
  1617     private Mapping erasureRecFun = new Mapping ("erasureRecursive") {
  1618         public Type apply(Type t) { return erasureRecursive(t); }
  1619     };
  1621     public List<Type> erasure(List<Type> ts) {
  1622         return Type.map(ts, erasureFun);
  1625     public Type erasureRecursive(Type t) {
  1626         return erasure(t, true);
  1629     public List<Type> erasureRecursive(List<Type> ts) {
  1630         return Type.map(ts, erasureRecFun);
  1632     // </editor-fold>
  1634     // <editor-fold defaultstate="collapsed" desc="makeCompoundType">
  1635     /**
  1636      * Make a compound type from non-empty list of types
  1638      * @param bounds            the types from which the compound type is formed
  1639      * @param supertype         is objectType if all bounds are interfaces,
  1640      *                          null otherwise.
  1641      */
  1642     public Type makeCompoundType(List<Type> bounds,
  1643                                  Type supertype) {
  1644         ClassSymbol bc =
  1645             new ClassSymbol(ABSTRACT|PUBLIC|SYNTHETIC|COMPOUND|ACYCLIC,
  1646                             Type.moreInfo
  1647                                 ? names.fromString(bounds.toString())
  1648                                 : names.empty,
  1649                             syms.noSymbol);
  1650         if (bounds.head.tag == TYPEVAR)
  1651             // error condition, recover
  1652                 bc.erasure_field = syms.objectType;
  1653             else
  1654                 bc.erasure_field = erasure(bounds.head);
  1655             bc.members_field = new Scope(bc);
  1656         ClassType bt = (ClassType)bc.type;
  1657         bt.allparams_field = List.nil();
  1658         if (supertype != null) {
  1659             bt.supertype_field = supertype;
  1660             bt.interfaces_field = bounds;
  1661         } else {
  1662             bt.supertype_field = bounds.head;
  1663             bt.interfaces_field = bounds.tail;
  1665         assert bt.supertype_field.tsym.completer != null
  1666             || !bt.supertype_field.isInterface()
  1667             : bt.supertype_field;
  1668         return bt;
  1671     /**
  1672      * Same as {@link #makeCompoundType(List,Type)}, except that the
  1673      * second parameter is computed directly. Note that this might
  1674      * cause a symbol completion.  Hence, this version of
  1675      * makeCompoundType may not be called during a classfile read.
  1676      */
  1677     public Type makeCompoundType(List<Type> bounds) {
  1678         Type supertype = (bounds.head.tsym.flags() & INTERFACE) != 0 ?
  1679             supertype(bounds.head) : null;
  1680         return makeCompoundType(bounds, supertype);
  1683     /**
  1684      * A convenience wrapper for {@link #makeCompoundType(List)}; the
  1685      * arguments are converted to a list and passed to the other
  1686      * method.  Note that this might cause a symbol completion.
  1687      * Hence, this version of makeCompoundType may not be called
  1688      * during a classfile read.
  1689      */
  1690     public Type makeCompoundType(Type bound1, Type bound2) {
  1691         return makeCompoundType(List.of(bound1, bound2));
  1693     // </editor-fold>
  1695     // <editor-fold defaultstate="collapsed" desc="supertype">
  1696     public Type supertype(Type t) {
  1697         return supertype.visit(t);
  1699     // where
  1700         private UnaryVisitor<Type> supertype = new UnaryVisitor<Type>() {
  1702             public Type visitType(Type t, Void ignored) {
  1703                 // A note on wildcards: there is no good way to
  1704                 // determine a supertype for a super bounded wildcard.
  1705                 return null;
  1708             @Override
  1709             public Type visitClassType(ClassType t, Void ignored) {
  1710                 if (t.supertype_field == null) {
  1711                     Type supertype = ((ClassSymbol)t.tsym).getSuperclass();
  1712                     // An interface has no superclass; its supertype is Object.
  1713                     if (t.isInterface())
  1714                         supertype = ((ClassType)t.tsym.type).supertype_field;
  1715                     if (t.supertype_field == null) {
  1716                         List<Type> actuals = classBound(t).allparams();
  1717                         List<Type> formals = t.tsym.type.allparams();
  1718                         if (t.hasErasedSupertypes()) {
  1719                             t.supertype_field = erasureRecursive(supertype);
  1720                         } else if (formals.nonEmpty()) {
  1721                             t.supertype_field = subst(supertype, formals, actuals);
  1723                         else {
  1724                             t.supertype_field = supertype;
  1728                 return t.supertype_field;
  1731             /**
  1732              * The supertype is always a class type. If the type
  1733              * variable's bounds start with a class type, this is also
  1734              * the supertype.  Otherwise, the supertype is
  1735              * java.lang.Object.
  1736              */
  1737             @Override
  1738             public Type visitTypeVar(TypeVar t, Void ignored) {
  1739                 if (t.bound.tag == TYPEVAR ||
  1740                     (!t.bound.isCompound() && !t.bound.isInterface())) {
  1741                     return t.bound;
  1742                 } else {
  1743                     return supertype(t.bound);
  1747             @Override
  1748             public Type visitArrayType(ArrayType t, Void ignored) {
  1749                 if (t.elemtype.isPrimitive() || isSameType(t.elemtype, syms.objectType))
  1750                     return arraySuperType();
  1751                 else
  1752                     return new ArrayType(supertype(t.elemtype), t.tsym);
  1755             @Override
  1756             public Type visitErrorType(ErrorType t, Void ignored) {
  1757                 return t;
  1759         };
  1760     // </editor-fold>
  1762     // <editor-fold defaultstate="collapsed" desc="interfaces">
  1763     /**
  1764      * Return the interfaces implemented by this class.
  1765      */
  1766     public List<Type> interfaces(Type t) {
  1767         return interfaces.visit(t);
  1769     // where
  1770         private UnaryVisitor<List<Type>> interfaces = new UnaryVisitor<List<Type>>() {
  1772             public List<Type> visitType(Type t, Void ignored) {
  1773                 return List.nil();
  1776             @Override
  1777             public List<Type> visitClassType(ClassType t, Void ignored) {
  1778                 if (t.interfaces_field == null) {
  1779                     List<Type> interfaces = ((ClassSymbol)t.tsym).getInterfaces();
  1780                     if (t.interfaces_field == null) {
  1781                         // If t.interfaces_field is null, then t must
  1782                         // be a parameterized type (not to be confused
  1783                         // with a generic type declaration).
  1784                         // Terminology:
  1785                         //    Parameterized type: List<String>
  1786                         //    Generic type declaration: class List<E> { ... }
  1787                         // So t corresponds to List<String> and
  1788                         // t.tsym.type corresponds to List<E>.
  1789                         // The reason t must be parameterized type is
  1790                         // that completion will happen as a side
  1791                         // effect of calling
  1792                         // ClassSymbol.getInterfaces.  Since
  1793                         // t.interfaces_field is null after
  1794                         // completion, we can assume that t is not the
  1795                         // type of a class/interface declaration.
  1796                         assert t != t.tsym.type : t.toString();
  1797                         List<Type> actuals = t.allparams();
  1798                         List<Type> formals = t.tsym.type.allparams();
  1799                         if (t.hasErasedSupertypes()) {
  1800                             t.interfaces_field = erasureRecursive(interfaces);
  1801                         } else if (formals.nonEmpty()) {
  1802                             t.interfaces_field =
  1803                                 upperBounds(subst(interfaces, formals, actuals));
  1805                         else {
  1806                             t.interfaces_field = interfaces;
  1810                 return t.interfaces_field;
  1813             @Override
  1814             public List<Type> visitTypeVar(TypeVar t, Void ignored) {
  1815                 if (t.bound.isCompound())
  1816                     return interfaces(t.bound);
  1818                 if (t.bound.isInterface())
  1819                     return List.of(t.bound);
  1821                 return List.nil();
  1823         };
  1824     // </editor-fold>
  1826     // <editor-fold defaultstate="collapsed" desc="isDerivedRaw">
  1827     Map<Type,Boolean> isDerivedRawCache = new HashMap<Type,Boolean>();
  1829     public boolean isDerivedRaw(Type t) {
  1830         Boolean result = isDerivedRawCache.get(t);
  1831         if (result == null) {
  1832             result = isDerivedRawInternal(t);
  1833             isDerivedRawCache.put(t, result);
  1835         return result;
  1838     public boolean isDerivedRawInternal(Type t) {
  1839         if (t.isErroneous())
  1840             return false;
  1841         return
  1842             t.isRaw() ||
  1843             supertype(t) != null && isDerivedRaw(supertype(t)) ||
  1844             isDerivedRaw(interfaces(t));
  1847     public boolean isDerivedRaw(List<Type> ts) {
  1848         List<Type> l = ts;
  1849         while (l.nonEmpty() && !isDerivedRaw(l.head)) l = l.tail;
  1850         return l.nonEmpty();
  1852     // </editor-fold>
  1854     // <editor-fold defaultstate="collapsed" desc="setBounds">
  1855     /**
  1856      * Set the bounds field of the given type variable to reflect a
  1857      * (possibly multiple) list of bounds.
  1858      * @param t                 a type variable
  1859      * @param bounds            the bounds, must be nonempty
  1860      * @param supertype         is objectType if all bounds are interfaces,
  1861      *                          null otherwise.
  1862      */
  1863     public void setBounds(TypeVar t, List<Type> bounds, Type supertype) {
  1864         if (bounds.tail.isEmpty())
  1865             t.bound = bounds.head;
  1866         else
  1867             t.bound = makeCompoundType(bounds, supertype);
  1868         t.rank_field = -1;
  1871     /**
  1872      * Same as {@link #setBounds(Type.TypeVar,List,Type)}, except that
  1873      * third parameter is computed directly, as follows: if all
  1874      * all bounds are interface types, the computed supertype is Object,
  1875      * otherwise the supertype is simply left null (in this case, the supertype
  1876      * is assumed to be the head of the bound list passed as second argument).
  1877      * Note that this check might cause a symbol completion. Hence, this version of
  1878      * setBounds may not be called during a classfile read.
  1879      */
  1880     public void setBounds(TypeVar t, List<Type> bounds) {
  1881         Type supertype = (bounds.head.tsym.flags() & INTERFACE) != 0 ?
  1882             syms.objectType : null;
  1883         setBounds(t, bounds, supertype);
  1884         t.rank_field = -1;
  1886     // </editor-fold>
  1888     // <editor-fold defaultstate="collapsed" desc="getBounds">
  1889     /**
  1890      * Return list of bounds of the given type variable.
  1891      */
  1892     public List<Type> getBounds(TypeVar t) {
  1893         if (t.bound.isErroneous() || !t.bound.isCompound())
  1894             return List.of(t.bound);
  1895         else if ((erasure(t).tsym.flags() & INTERFACE) == 0)
  1896             return interfaces(t).prepend(supertype(t));
  1897         else
  1898             // No superclass was given in bounds.
  1899             // In this case, supertype is Object, erasure is first interface.
  1900             return interfaces(t);
  1902     // </editor-fold>
  1904     // <editor-fold defaultstate="collapsed" desc="classBound">
  1905     /**
  1906      * If the given type is a (possibly selected) type variable,
  1907      * return the bounding class of this type, otherwise return the
  1908      * type itself.
  1909      */
  1910     public Type classBound(Type t) {
  1911         return classBound.visit(t);
  1913     // where
  1914         private UnaryVisitor<Type> classBound = new UnaryVisitor<Type>() {
  1916             public Type visitType(Type t, Void ignored) {
  1917                 return t;
  1920             @Override
  1921             public Type visitClassType(ClassType t, Void ignored) {
  1922                 Type outer1 = classBound(t.getEnclosingType());
  1923                 if (outer1 != t.getEnclosingType())
  1924                     return new ClassType(outer1, t.getTypeArguments(), t.tsym);
  1925                 else
  1926                     return t;
  1929             @Override
  1930             public Type visitTypeVar(TypeVar t, Void ignored) {
  1931                 return classBound(supertype(t));
  1934             @Override
  1935             public Type visitErrorType(ErrorType t, Void ignored) {
  1936                 return t;
  1938         };
  1939     // </editor-fold>
  1941     // <editor-fold defaultstate="collapsed" desc="sub signature / override equivalence">
  1942     /**
  1943      * Returns true iff the first signature is a <em>sub
  1944      * signature</em> of the other.  This is <b>not</b> an equivalence
  1945      * relation.
  1947      * @see "The Java Language Specification, Third Ed. (8.4.2)."
  1948      * @see #overrideEquivalent(Type t, Type s)
  1949      * @param t first signature (possibly raw).
  1950      * @param s second signature (could be subjected to erasure).
  1951      * @return true if t is a sub signature of s.
  1952      */
  1953     public boolean isSubSignature(Type t, Type s) {
  1954         return hasSameArgs(t, s) || hasSameArgs(t, erasure(s));
  1957     /**
  1958      * Returns true iff these signatures are related by <em>override
  1959      * equivalence</em>.  This is the natural extension of
  1960      * isSubSignature to an equivalence relation.
  1962      * @see "The Java Language Specification, Third Ed. (8.4.2)."
  1963      * @see #isSubSignature(Type t, Type s)
  1964      * @param t a signature (possible raw, could be subjected to
  1965      * erasure).
  1966      * @param s a signature (possible raw, could be subjected to
  1967      * erasure).
  1968      * @return true if either argument is a sub signature of the other.
  1969      */
  1970     public boolean overrideEquivalent(Type t, Type s) {
  1971         return hasSameArgs(t, s) ||
  1972             hasSameArgs(t, erasure(s)) || hasSameArgs(erasure(t), s);
  1975     // <editor-fold defaultstate="collapsed" desc="Determining method implementation in given site">
  1976     class ImplementationCache {
  1978         private WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>> _map =
  1979                 new WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>>();
  1981         class Entry {
  1982             final MethodSymbol cachedImpl;
  1983             final Filter<Symbol> implFilter;
  1984             final boolean checkResult;
  1985             final Scope.ScopeCounter scopeCounter;
  1987             public Entry(MethodSymbol cachedImpl,
  1988                     Filter<Symbol> scopeFilter,
  1989                     boolean checkResult,
  1990                     Scope.ScopeCounter scopeCounter) {
  1991                 this.cachedImpl = cachedImpl;
  1992                 this.implFilter = scopeFilter;
  1993                 this.checkResult = checkResult;
  1994                 this.scopeCounter = scopeCounter;
  1997             boolean matches(Filter<Symbol> scopeFilter, boolean checkResult, Scope.ScopeCounter scopeCounter) {
  1998                 return this.implFilter == scopeFilter &&
  1999                         this.checkResult == checkResult &&
  2000                         this.scopeCounter.val() >= scopeCounter.val();
  2004         MethodSymbol get(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter, Scope.ScopeCounter scopeCounter) {
  2005             SoftReference<Map<TypeSymbol, Entry>> ref_cache = _map.get(ms);
  2006             Map<TypeSymbol, Entry> cache = ref_cache != null ? ref_cache.get() : null;
  2007             if (cache == null) {
  2008                 cache = new HashMap<TypeSymbol, Entry>();
  2009                 _map.put(ms, new SoftReference<Map<TypeSymbol, Entry>>(cache));
  2011             Entry e = cache.get(origin);
  2012             if (e == null ||
  2013                     !e.matches(implFilter, checkResult, scopeCounter)) {
  2014                 MethodSymbol impl = implementationInternal(ms, origin, Types.this, checkResult, implFilter);
  2015                 cache.put(origin, new Entry(impl, implFilter, checkResult, scopeCounter));
  2016                 return impl;
  2018             else {
  2019                 return e.cachedImpl;
  2023         private MethodSymbol implementationInternal(MethodSymbol ms, TypeSymbol origin, Types types, boolean checkResult, Filter<Symbol> implFilter) {
  2024             for (Type t = origin.type; t.tag == CLASS || t.tag == TYPEVAR; t = types.supertype(t)) {
  2025                 while (t.tag == TYPEVAR)
  2026                     t = t.getUpperBound();
  2027                 TypeSymbol c = t.tsym;
  2028                 for (Scope.Entry e = c.members().lookup(ms.name, implFilter);
  2029                      e.scope != null;
  2030                      e = e.next(implFilter)) {
  2031                     if (e.sym != null &&
  2032                              e.sym.overrides(ms, origin, types, checkResult))
  2033                         return (MethodSymbol)e.sym;
  2036             return null;
  2040     private ImplementationCache implCache = new ImplementationCache();
  2042     public MethodSymbol implementation(MethodSymbol ms, TypeSymbol origin, Types types, boolean checkResult, Filter<Symbol> implFilter) {
  2043         return implCache.get(ms, origin, checkResult, implFilter, scopeCounter);
  2045     // </editor-fold>
  2047     /**
  2048      * Does t have the same arguments as s?  It is assumed that both
  2049      * types are (possibly polymorphic) method types.  Monomorphic
  2050      * method types "have the same arguments", if their argument lists
  2051      * are equal.  Polymorphic method types "have the same arguments",
  2052      * if they have the same arguments after renaming all type
  2053      * variables of one to corresponding type variables in the other,
  2054      * where correspondence is by position in the type parameter list.
  2055      */
  2056     public boolean hasSameArgs(Type t, Type s) {
  2057         return hasSameArgs.visit(t, s);
  2059     // where
  2060         private TypeRelation hasSameArgs = new TypeRelation() {
  2062             public Boolean visitType(Type t, Type s) {
  2063                 throw new AssertionError();
  2066             @Override
  2067             public Boolean visitMethodType(MethodType t, Type s) {
  2068                 return s.tag == METHOD
  2069                     && containsTypeEquivalent(t.argtypes, s.getParameterTypes());
  2072             @Override
  2073             public Boolean visitForAll(ForAll t, Type s) {
  2074                 if (s.tag != FORALL)
  2075                     return false;
  2077                 ForAll forAll = (ForAll)s;
  2078                 return hasSameBounds(t, forAll)
  2079                     && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
  2082             @Override
  2083             public Boolean visitErrorType(ErrorType t, Type s) {
  2084                 return false;
  2086         };
  2087     // </editor-fold>
  2089     // <editor-fold defaultstate="collapsed" desc="subst">
  2090     public List<Type> subst(List<Type> ts,
  2091                             List<Type> from,
  2092                             List<Type> to) {
  2093         return new Subst(from, to).subst(ts);
  2096     /**
  2097      * Substitute all occurrences of a type in `from' with the
  2098      * corresponding type in `to' in 't'. Match lists `from' and `to'
  2099      * from the right: If lists have different length, discard leading
  2100      * elements of the longer list.
  2101      */
  2102     public Type subst(Type t, List<Type> from, List<Type> to) {
  2103         return new Subst(from, to).subst(t);
  2106     private class Subst extends UnaryVisitor<Type> {
  2107         List<Type> from;
  2108         List<Type> to;
  2110         public Subst(List<Type> from, List<Type> to) {
  2111             int fromLength = from.length();
  2112             int toLength = to.length();
  2113             while (fromLength > toLength) {
  2114                 fromLength--;
  2115                 from = from.tail;
  2117             while (fromLength < toLength) {
  2118                 toLength--;
  2119                 to = to.tail;
  2121             this.from = from;
  2122             this.to = to;
  2125         Type subst(Type t) {
  2126             if (from.tail == null)
  2127                 return t;
  2128             else
  2129                 return visit(t);
  2132         List<Type> subst(List<Type> ts) {
  2133             if (from.tail == null)
  2134                 return ts;
  2135             boolean wild = false;
  2136             if (ts.nonEmpty() && from.nonEmpty()) {
  2137                 Type head1 = subst(ts.head);
  2138                 List<Type> tail1 = subst(ts.tail);
  2139                 if (head1 != ts.head || tail1 != ts.tail)
  2140                     return tail1.prepend(head1);
  2142             return ts;
  2145         public Type visitType(Type t, Void ignored) {
  2146             return t;
  2149         @Override
  2150         public Type visitMethodType(MethodType t, Void ignored) {
  2151             List<Type> argtypes = subst(t.argtypes);
  2152             Type restype = subst(t.restype);
  2153             List<Type> thrown = subst(t.thrown);
  2154             if (argtypes == t.argtypes &&
  2155                 restype == t.restype &&
  2156                 thrown == t.thrown)
  2157                 return t;
  2158             else
  2159                 return new MethodType(argtypes, restype, thrown, t.tsym);
  2162         @Override
  2163         public Type visitTypeVar(TypeVar t, Void ignored) {
  2164             for (List<Type> from = this.from, to = this.to;
  2165                  from.nonEmpty();
  2166                  from = from.tail, to = to.tail) {
  2167                 if (t == from.head) {
  2168                     return to.head.withTypeVar(t);
  2171             return t;
  2174         @Override
  2175         public Type visitClassType(ClassType t, Void ignored) {
  2176             if (!t.isCompound()) {
  2177                 List<Type> typarams = t.getTypeArguments();
  2178                 List<Type> typarams1 = subst(typarams);
  2179                 Type outer = t.getEnclosingType();
  2180                 Type outer1 = subst(outer);
  2181                 if (typarams1 == typarams && outer1 == outer)
  2182                     return t;
  2183                 else
  2184                     return new ClassType(outer1, typarams1, t.tsym);
  2185             } else {
  2186                 Type st = subst(supertype(t));
  2187                 List<Type> is = upperBounds(subst(interfaces(t)));
  2188                 if (st == supertype(t) && is == interfaces(t))
  2189                     return t;
  2190                 else
  2191                     return makeCompoundType(is.prepend(st));
  2195         @Override
  2196         public Type visitWildcardType(WildcardType t, Void ignored) {
  2197             Type bound = t.type;
  2198             if (t.kind != BoundKind.UNBOUND)
  2199                 bound = subst(bound);
  2200             if (bound == t.type) {
  2201                 return t;
  2202             } else {
  2203                 if (t.isExtendsBound() && bound.isExtendsBound())
  2204                     bound = upperBound(bound);
  2205                 return new WildcardType(bound, t.kind, syms.boundClass, t.bound);
  2209         @Override
  2210         public Type visitArrayType(ArrayType t, Void ignored) {
  2211             Type elemtype = subst(t.elemtype);
  2212             if (elemtype == t.elemtype)
  2213                 return t;
  2214             else
  2215                 return new ArrayType(upperBound(elemtype), t.tsym);
  2218         @Override
  2219         public Type visitForAll(ForAll t, Void ignored) {
  2220             List<Type> tvars1 = substBounds(t.tvars, from, to);
  2221             Type qtype1 = subst(t.qtype);
  2222             if (tvars1 == t.tvars && qtype1 == t.qtype) {
  2223                 return t;
  2224             } else if (tvars1 == t.tvars) {
  2225                 return new ForAll(tvars1, qtype1);
  2226             } else {
  2227                 return new ForAll(tvars1, Types.this.subst(qtype1, t.tvars, tvars1));
  2231         @Override
  2232         public Type visitErrorType(ErrorType t, Void ignored) {
  2233             return t;
  2237     public List<Type> substBounds(List<Type> tvars,
  2238                                   List<Type> from,
  2239                                   List<Type> to) {
  2240         if (tvars.isEmpty())
  2241             return tvars;
  2242         ListBuffer<Type> newBoundsBuf = lb();
  2243         boolean changed = false;
  2244         // calculate new bounds
  2245         for (Type t : tvars) {
  2246             TypeVar tv = (TypeVar) t;
  2247             Type bound = subst(tv.bound, from, to);
  2248             if (bound != tv.bound)
  2249                 changed = true;
  2250             newBoundsBuf.append(bound);
  2252         if (!changed)
  2253             return tvars;
  2254         ListBuffer<Type> newTvars = lb();
  2255         // create new type variables without bounds
  2256         for (Type t : tvars) {
  2257             newTvars.append(new TypeVar(t.tsym, null, syms.botType));
  2259         // the new bounds should use the new type variables in place
  2260         // of the old
  2261         List<Type> newBounds = newBoundsBuf.toList();
  2262         from = tvars;
  2263         to = newTvars.toList();
  2264         for (; !newBounds.isEmpty(); newBounds = newBounds.tail) {
  2265             newBounds.head = subst(newBounds.head, from, to);
  2267         newBounds = newBoundsBuf.toList();
  2268         // set the bounds of new type variables to the new bounds
  2269         for (Type t : newTvars.toList()) {
  2270             TypeVar tv = (TypeVar) t;
  2271             tv.bound = newBounds.head;
  2272             newBounds = newBounds.tail;
  2274         return newTvars.toList();
  2277     public TypeVar substBound(TypeVar t, List<Type> from, List<Type> to) {
  2278         Type bound1 = subst(t.bound, from, to);
  2279         if (bound1 == t.bound)
  2280             return t;
  2281         else {
  2282             // create new type variable without bounds
  2283             TypeVar tv = new TypeVar(t.tsym, null, syms.botType);
  2284             // the new bound should use the new type variable in place
  2285             // of the old
  2286             tv.bound = subst(bound1, List.<Type>of(t), List.<Type>of(tv));
  2287             return tv;
  2290     // </editor-fold>
  2292     // <editor-fold defaultstate="collapsed" desc="hasSameBounds">
  2293     /**
  2294      * Does t have the same bounds for quantified variables as s?
  2295      */
  2296     boolean hasSameBounds(ForAll t, ForAll s) {
  2297         List<Type> l1 = t.tvars;
  2298         List<Type> l2 = s.tvars;
  2299         while (l1.nonEmpty() && l2.nonEmpty() &&
  2300                isSameType(l1.head.getUpperBound(),
  2301                           subst(l2.head.getUpperBound(),
  2302                                 s.tvars,
  2303                                 t.tvars))) {
  2304             l1 = l1.tail;
  2305             l2 = l2.tail;
  2307         return l1.isEmpty() && l2.isEmpty();
  2309     // </editor-fold>
  2311     // <editor-fold defaultstate="collapsed" desc="newInstances">
  2312     /** Create new vector of type variables from list of variables
  2313      *  changing all recursive bounds from old to new list.
  2314      */
  2315     public List<Type> newInstances(List<Type> tvars) {
  2316         List<Type> tvars1 = Type.map(tvars, newInstanceFun);
  2317         for (List<Type> l = tvars1; l.nonEmpty(); l = l.tail) {
  2318             TypeVar tv = (TypeVar) l.head;
  2319             tv.bound = subst(tv.bound, tvars, tvars1);
  2321         return tvars1;
  2323     static private Mapping newInstanceFun = new Mapping("newInstanceFun") {
  2324             public Type apply(Type t) { return new TypeVar(t.tsym, t.getUpperBound(), t.getLowerBound()); }
  2325         };
  2326     // </editor-fold>
  2328     // <editor-fold defaultstate="collapsed" desc="createErrorType">
  2329     public Type createErrorType(Type originalType) {
  2330         return new ErrorType(originalType, syms.errSymbol);
  2333     public Type createErrorType(ClassSymbol c, Type originalType) {
  2334         return new ErrorType(c, originalType);
  2337     public Type createErrorType(Name name, TypeSymbol container, Type originalType) {
  2338         return new ErrorType(name, container, originalType);
  2340     // </editor-fold>
  2342     // <editor-fold defaultstate="collapsed" desc="rank">
  2343     /**
  2344      * The rank of a class is the length of the longest path between
  2345      * the class and java.lang.Object in the class inheritance
  2346      * graph. Undefined for all but reference types.
  2347      */
  2348     public int rank(Type t) {
  2349         switch(t.tag) {
  2350         case CLASS: {
  2351             ClassType cls = (ClassType)t;
  2352             if (cls.rank_field < 0) {
  2353                 Name fullname = cls.tsym.getQualifiedName();
  2354                 if (fullname == names.java_lang_Object)
  2355                     cls.rank_field = 0;
  2356                 else {
  2357                     int r = rank(supertype(cls));
  2358                     for (List<Type> l = interfaces(cls);
  2359                          l.nonEmpty();
  2360                          l = l.tail) {
  2361                         if (rank(l.head) > r)
  2362                             r = rank(l.head);
  2364                     cls.rank_field = r + 1;
  2367             return cls.rank_field;
  2369         case TYPEVAR: {
  2370             TypeVar tvar = (TypeVar)t;
  2371             if (tvar.rank_field < 0) {
  2372                 int r = rank(supertype(tvar));
  2373                 for (List<Type> l = interfaces(tvar);
  2374                      l.nonEmpty();
  2375                      l = l.tail) {
  2376                     if (rank(l.head) > r) r = rank(l.head);
  2378                 tvar.rank_field = r + 1;
  2380             return tvar.rank_field;
  2382         case ERROR:
  2383             return 0;
  2384         default:
  2385             throw new AssertionError();
  2388     // </editor-fold>
  2390     /**
  2391      * Helper method for generating a string representation of a given type
  2392      * accordingly to a given locale
  2393      */
  2394     public String toString(Type t, Locale locale) {
  2395         return Printer.createStandardPrinter(messages).visit(t, locale);
  2398     /**
  2399      * Helper method for generating a string representation of a given type
  2400      * accordingly to a given locale
  2401      */
  2402     public String toString(Symbol t, Locale locale) {
  2403         return Printer.createStandardPrinter(messages).visit(t, locale);
  2406     // <editor-fold defaultstate="collapsed" desc="toString">
  2407     /**
  2408      * This toString is slightly more descriptive than the one on Type.
  2410      * @deprecated Types.toString(Type t, Locale l) provides better support
  2411      * for localization
  2412      */
  2413     @Deprecated
  2414     public String toString(Type t) {
  2415         if (t.tag == FORALL) {
  2416             ForAll forAll = (ForAll)t;
  2417             return typaramsString(forAll.tvars) + forAll.qtype;
  2419         return "" + t;
  2421     // where
  2422         private String typaramsString(List<Type> tvars) {
  2423             StringBuffer s = new StringBuffer();
  2424             s.append('<');
  2425             boolean first = true;
  2426             for (Type t : tvars) {
  2427                 if (!first) s.append(", ");
  2428                 first = false;
  2429                 appendTyparamString(((TypeVar)t), s);
  2431             s.append('>');
  2432             return s.toString();
  2434         private void appendTyparamString(TypeVar t, StringBuffer buf) {
  2435             buf.append(t);
  2436             if (t.bound == null ||
  2437                 t.bound.tsym.getQualifiedName() == names.java_lang_Object)
  2438                 return;
  2439             buf.append(" extends "); // Java syntax; no need for i18n
  2440             Type bound = t.bound;
  2441             if (!bound.isCompound()) {
  2442                 buf.append(bound);
  2443             } else if ((erasure(t).tsym.flags() & INTERFACE) == 0) {
  2444                 buf.append(supertype(t));
  2445                 for (Type intf : interfaces(t)) {
  2446                     buf.append('&');
  2447                     buf.append(intf);
  2449             } else {
  2450                 // No superclass was given in bounds.
  2451                 // In this case, supertype is Object, erasure is first interface.
  2452                 boolean first = true;
  2453                 for (Type intf : interfaces(t)) {
  2454                     if (!first) buf.append('&');
  2455                     first = false;
  2456                     buf.append(intf);
  2460     // </editor-fold>
  2462     // <editor-fold defaultstate="collapsed" desc="Determining least upper bounds of types">
  2463     /**
  2464      * A cache for closures.
  2466      * <p>A closure is a list of all the supertypes and interfaces of
  2467      * a class or interface type, ordered by ClassSymbol.precedes
  2468      * (that is, subclasses come first, arbitrary but fixed
  2469      * otherwise).
  2470      */
  2471     private Map<Type,List<Type>> closureCache = new HashMap<Type,List<Type>>();
  2473     /**
  2474      * Returns the closure of a class or interface type.
  2475      */
  2476     public List<Type> closure(Type t) {
  2477         List<Type> cl = closureCache.get(t);
  2478         if (cl == null) {
  2479             Type st = supertype(t);
  2480             if (!t.isCompound()) {
  2481                 if (st.tag == CLASS) {
  2482                     cl = insert(closure(st), t);
  2483                 } else if (st.tag == TYPEVAR) {
  2484                     cl = closure(st).prepend(t);
  2485                 } else {
  2486                     cl = List.of(t);
  2488             } else {
  2489                 cl = closure(supertype(t));
  2491             for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail)
  2492                 cl = union(cl, closure(l.head));
  2493             closureCache.put(t, cl);
  2495         return cl;
  2498     /**
  2499      * Insert a type in a closure
  2500      */
  2501     public List<Type> insert(List<Type> cl, Type t) {
  2502         if (cl.isEmpty() || t.tsym.precedes(cl.head.tsym, this)) {
  2503             return cl.prepend(t);
  2504         } else if (cl.head.tsym.precedes(t.tsym, this)) {
  2505             return insert(cl.tail, t).prepend(cl.head);
  2506         } else {
  2507             return cl;
  2511     /**
  2512      * Form the union of two closures
  2513      */
  2514     public List<Type> union(List<Type> cl1, List<Type> cl2) {
  2515         if (cl1.isEmpty()) {
  2516             return cl2;
  2517         } else if (cl2.isEmpty()) {
  2518             return cl1;
  2519         } else if (cl1.head.tsym.precedes(cl2.head.tsym, this)) {
  2520             return union(cl1.tail, cl2).prepend(cl1.head);
  2521         } else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) {
  2522             return union(cl1, cl2.tail).prepend(cl2.head);
  2523         } else {
  2524             return union(cl1.tail, cl2.tail).prepend(cl1.head);
  2528     /**
  2529      * Intersect two closures
  2530      */
  2531     public List<Type> intersect(List<Type> cl1, List<Type> cl2) {
  2532         if (cl1 == cl2)
  2533             return cl1;
  2534         if (cl1.isEmpty() || cl2.isEmpty())
  2535             return List.nil();
  2536         if (cl1.head.tsym.precedes(cl2.head.tsym, this))
  2537             return intersect(cl1.tail, cl2);
  2538         if (cl2.head.tsym.precedes(cl1.head.tsym, this))
  2539             return intersect(cl1, cl2.tail);
  2540         if (isSameType(cl1.head, cl2.head))
  2541             return intersect(cl1.tail, cl2.tail).prepend(cl1.head);
  2542         if (cl1.head.tsym == cl2.head.tsym &&
  2543             cl1.head.tag == CLASS && cl2.head.tag == CLASS) {
  2544             if (cl1.head.isParameterized() && cl2.head.isParameterized()) {
  2545                 Type merge = merge(cl1.head,cl2.head);
  2546                 return intersect(cl1.tail, cl2.tail).prepend(merge);
  2548             if (cl1.head.isRaw() || cl2.head.isRaw())
  2549                 return intersect(cl1.tail, cl2.tail).prepend(erasure(cl1.head));
  2551         return intersect(cl1.tail, cl2.tail);
  2553     // where
  2554         class TypePair {
  2555             final Type t1;
  2556             final Type t2;
  2557             TypePair(Type t1, Type t2) {
  2558                 this.t1 = t1;
  2559                 this.t2 = t2;
  2561             @Override
  2562             public int hashCode() {
  2563                 return 127 * Types.hashCode(t1) + Types.hashCode(t2);
  2565             @Override
  2566             public boolean equals(Object obj) {
  2567                 if (!(obj instanceof TypePair))
  2568                     return false;
  2569                 TypePair typePair = (TypePair)obj;
  2570                 return isSameType(t1, typePair.t1)
  2571                     && isSameType(t2, typePair.t2);
  2574         Set<TypePair> mergeCache = new HashSet<TypePair>();
  2575         private Type merge(Type c1, Type c2) {
  2576             ClassType class1 = (ClassType) c1;
  2577             List<Type> act1 = class1.getTypeArguments();
  2578             ClassType class2 = (ClassType) c2;
  2579             List<Type> act2 = class2.getTypeArguments();
  2580             ListBuffer<Type> merged = new ListBuffer<Type>();
  2581             List<Type> typarams = class1.tsym.type.getTypeArguments();
  2583             while (act1.nonEmpty() && act2.nonEmpty() && typarams.nonEmpty()) {
  2584                 if (containsType(act1.head, act2.head)) {
  2585                     merged.append(act1.head);
  2586                 } else if (containsType(act2.head, act1.head)) {
  2587                     merged.append(act2.head);
  2588                 } else {
  2589                     TypePair pair = new TypePair(c1, c2);
  2590                     Type m;
  2591                     if (mergeCache.add(pair)) {
  2592                         m = new WildcardType(lub(upperBound(act1.head),
  2593                                                  upperBound(act2.head)),
  2594                                              BoundKind.EXTENDS,
  2595                                              syms.boundClass);
  2596                         mergeCache.remove(pair);
  2597                     } else {
  2598                         m = new WildcardType(syms.objectType,
  2599                                              BoundKind.UNBOUND,
  2600                                              syms.boundClass);
  2602                     merged.append(m.withTypeVar(typarams.head));
  2604                 act1 = act1.tail;
  2605                 act2 = act2.tail;
  2606                 typarams = typarams.tail;
  2608             assert(act1.isEmpty() && act2.isEmpty() && typarams.isEmpty());
  2609             return new ClassType(class1.getEnclosingType(), merged.toList(), class1.tsym);
  2612     /**
  2613      * Return the minimum type of a closure, a compound type if no
  2614      * unique minimum exists.
  2615      */
  2616     private Type compoundMin(List<Type> cl) {
  2617         if (cl.isEmpty()) return syms.objectType;
  2618         List<Type> compound = closureMin(cl);
  2619         if (compound.isEmpty())
  2620             return null;
  2621         else if (compound.tail.isEmpty())
  2622             return compound.head;
  2623         else
  2624             return makeCompoundType(compound);
  2627     /**
  2628      * Return the minimum types of a closure, suitable for computing
  2629      * compoundMin or glb.
  2630      */
  2631     private List<Type> closureMin(List<Type> cl) {
  2632         ListBuffer<Type> classes = lb();
  2633         ListBuffer<Type> interfaces = lb();
  2634         while (!cl.isEmpty()) {
  2635             Type current = cl.head;
  2636             if (current.isInterface())
  2637                 interfaces.append(current);
  2638             else
  2639                 classes.append(current);
  2640             ListBuffer<Type> candidates = lb();
  2641             for (Type t : cl.tail) {
  2642                 if (!isSubtypeNoCapture(current, t))
  2643                     candidates.append(t);
  2645             cl = candidates.toList();
  2647         return classes.appendList(interfaces).toList();
  2650     /**
  2651      * Return the least upper bound of pair of types.  if the lub does
  2652      * not exist return null.
  2653      */
  2654     public Type lub(Type t1, Type t2) {
  2655         return lub(List.of(t1, t2));
  2658     /**
  2659      * Return the least upper bound (lub) of set of types.  If the lub
  2660      * does not exist return the type of null (bottom).
  2661      */
  2662     public Type lub(List<Type> ts) {
  2663         final int ARRAY_BOUND = 1;
  2664         final int CLASS_BOUND = 2;
  2665         int boundkind = 0;
  2666         for (Type t : ts) {
  2667             switch (t.tag) {
  2668             case CLASS:
  2669                 boundkind |= CLASS_BOUND;
  2670                 break;
  2671             case ARRAY:
  2672                 boundkind |= ARRAY_BOUND;
  2673                 break;
  2674             case  TYPEVAR:
  2675                 do {
  2676                     t = t.getUpperBound();
  2677                 } while (t.tag == TYPEVAR);
  2678                 if (t.tag == ARRAY) {
  2679                     boundkind |= ARRAY_BOUND;
  2680                 } else {
  2681                     boundkind |= CLASS_BOUND;
  2683                 break;
  2684             default:
  2685                 if (t.isPrimitive())
  2686                     return syms.errType;
  2689         switch (boundkind) {
  2690         case 0:
  2691             return syms.botType;
  2693         case ARRAY_BOUND:
  2694             // calculate lub(A[], B[])
  2695             List<Type> elements = Type.map(ts, elemTypeFun);
  2696             for (Type t : elements) {
  2697                 if (t.isPrimitive()) {
  2698                     // if a primitive type is found, then return
  2699                     // arraySuperType unless all the types are the
  2700                     // same
  2701                     Type first = ts.head;
  2702                     for (Type s : ts.tail) {
  2703                         if (!isSameType(first, s)) {
  2704                              // lub(int[], B[]) is Cloneable & Serializable
  2705                             return arraySuperType();
  2708                     // all the array types are the same, return one
  2709                     // lub(int[], int[]) is int[]
  2710                     return first;
  2713             // lub(A[], B[]) is lub(A, B)[]
  2714             return new ArrayType(lub(elements), syms.arrayClass);
  2716         case CLASS_BOUND:
  2717             // calculate lub(A, B)
  2718             while (ts.head.tag != CLASS && ts.head.tag != TYPEVAR)
  2719                 ts = ts.tail;
  2720             assert !ts.isEmpty();
  2721             List<Type> cl = closure(ts.head);
  2722             for (Type t : ts.tail) {
  2723                 if (t.tag == CLASS || t.tag == TYPEVAR)
  2724                     cl = intersect(cl, closure(t));
  2726             return compoundMin(cl);
  2728         default:
  2729             // calculate lub(A, B[])
  2730             List<Type> classes = List.of(arraySuperType());
  2731             for (Type t : ts) {
  2732                 if (t.tag != ARRAY) // Filter out any arrays
  2733                     classes = classes.prepend(t);
  2735             // lub(A, B[]) is lub(A, arraySuperType)
  2736             return lub(classes);
  2739     // where
  2740         private Type arraySuperType = null;
  2741         private Type arraySuperType() {
  2742             // initialized lazily to avoid problems during compiler startup
  2743             if (arraySuperType == null) {
  2744                 synchronized (this) {
  2745                     if (arraySuperType == null) {
  2746                         // JLS 10.8: all arrays implement Cloneable and Serializable.
  2747                         arraySuperType = makeCompoundType(List.of(syms.serializableType,
  2748                                                                   syms.cloneableType),
  2749                                                           syms.objectType);
  2753             return arraySuperType;
  2755     // </editor-fold>
  2757     // <editor-fold defaultstate="collapsed" desc="Greatest lower bound">
  2758     public Type glb(List<Type> ts) {
  2759         Type t1 = ts.head;
  2760         for (Type t2 : ts.tail) {
  2761             if (t1.isErroneous())
  2762                 return t1;
  2763             t1 = glb(t1, t2);
  2765         return t1;
  2767     //where
  2768     public Type glb(Type t, Type s) {
  2769         if (s == null)
  2770             return t;
  2771         else if (t.isPrimitive() || s.isPrimitive())
  2772             return syms.errType;
  2773         else if (isSubtypeNoCapture(t, s))
  2774             return t;
  2775         else if (isSubtypeNoCapture(s, t))
  2776             return s;
  2778         List<Type> closure = union(closure(t), closure(s));
  2779         List<Type> bounds = closureMin(closure);
  2781         if (bounds.isEmpty()) {             // length == 0
  2782             return syms.objectType;
  2783         } else if (bounds.tail.isEmpty()) { // length == 1
  2784             return bounds.head;
  2785         } else {                            // length > 1
  2786             int classCount = 0;
  2787             for (Type bound : bounds)
  2788                 if (!bound.isInterface())
  2789                     classCount++;
  2790             if (classCount > 1)
  2791                 return createErrorType(t);
  2793         return makeCompoundType(bounds);
  2795     // </editor-fold>
  2797     // <editor-fold defaultstate="collapsed" desc="hashCode">
  2798     /**
  2799      * Compute a hash code on a type.
  2800      */
  2801     public static int hashCode(Type t) {
  2802         return hashCode.visit(t);
  2804     // where
  2805         private static final UnaryVisitor<Integer> hashCode = new UnaryVisitor<Integer>() {
  2807             public Integer visitType(Type t, Void ignored) {
  2808                 return t.tag;
  2811             @Override
  2812             public Integer visitClassType(ClassType t, Void ignored) {
  2813                 int result = visit(t.getEnclosingType());
  2814                 result *= 127;
  2815                 result += t.tsym.flatName().hashCode();
  2816                 for (Type s : t.getTypeArguments()) {
  2817                     result *= 127;
  2818                     result += visit(s);
  2820                 return result;
  2823             @Override
  2824             public Integer visitWildcardType(WildcardType t, Void ignored) {
  2825                 int result = t.kind.hashCode();
  2826                 if (t.type != null) {
  2827                     result *= 127;
  2828                     result += visit(t.type);
  2830                 return result;
  2833             @Override
  2834             public Integer visitArrayType(ArrayType t, Void ignored) {
  2835                 return visit(t.elemtype) + 12;
  2838             @Override
  2839             public Integer visitTypeVar(TypeVar t, Void ignored) {
  2840                 return System.identityHashCode(t.tsym);
  2843             @Override
  2844             public Integer visitUndetVar(UndetVar t, Void ignored) {
  2845                 return System.identityHashCode(t);
  2848             @Override
  2849             public Integer visitErrorType(ErrorType t, Void ignored) {
  2850                 return 0;
  2852         };
  2853     // </editor-fold>
  2855     // <editor-fold defaultstate="collapsed" desc="Return-Type-Substitutable">
  2856     /**
  2857      * Does t have a result that is a subtype of the result type of s,
  2858      * suitable for covariant returns?  It is assumed that both types
  2859      * are (possibly polymorphic) method types.  Monomorphic method
  2860      * types are handled in the obvious way.  Polymorphic method types
  2861      * require renaming all type variables of one to corresponding
  2862      * type variables in the other, where correspondence is by
  2863      * position in the type parameter list. */
  2864     public boolean resultSubtype(Type t, Type s, Warner warner) {
  2865         List<Type> tvars = t.getTypeArguments();
  2866         List<Type> svars = s.getTypeArguments();
  2867         Type tres = t.getReturnType();
  2868         Type sres = subst(s.getReturnType(), svars, tvars);
  2869         return covariantReturnType(tres, sres, warner);
  2872     /**
  2873      * Return-Type-Substitutable.
  2874      * @see <a href="http://java.sun.com/docs/books/jls/">The Java
  2875      * Language Specification, Third Ed. (8.4.5)</a>
  2876      */
  2877     public boolean returnTypeSubstitutable(Type r1, Type r2) {
  2878         if (hasSameArgs(r1, r2))
  2879             return resultSubtype(r1, r2, Warner.noWarnings);
  2880         else
  2881             return covariantReturnType(r1.getReturnType(),
  2882                                        erasure(r2.getReturnType()),
  2883                                        Warner.noWarnings);
  2886     public boolean returnTypeSubstitutable(Type r1,
  2887                                            Type r2, Type r2res,
  2888                                            Warner warner) {
  2889         if (isSameType(r1.getReturnType(), r2res))
  2890             return true;
  2891         if (r1.getReturnType().isPrimitive() || r2res.isPrimitive())
  2892             return false;
  2894         if (hasSameArgs(r1, r2))
  2895             return covariantReturnType(r1.getReturnType(), r2res, warner);
  2896         if (!source.allowCovariantReturns())
  2897             return false;
  2898         if (isSubtypeUnchecked(r1.getReturnType(), r2res, warner))
  2899             return true;
  2900         if (!isSubtype(r1.getReturnType(), erasure(r2res)))
  2901             return false;
  2902         warner.warnUnchecked();
  2903         return true;
  2906     /**
  2907      * Is t an appropriate return type in an overrider for a
  2908      * method that returns s?
  2909      */
  2910     public boolean covariantReturnType(Type t, Type s, Warner warner) {
  2911         return
  2912             isSameType(t, s) ||
  2913             source.allowCovariantReturns() &&
  2914             !t.isPrimitive() &&
  2915             !s.isPrimitive() &&
  2916             isAssignable(t, s, warner);
  2918     // </editor-fold>
  2920     // <editor-fold defaultstate="collapsed" desc="Box/unbox support">
  2921     /**
  2922      * Return the class that boxes the given primitive.
  2923      */
  2924     public ClassSymbol boxedClass(Type t) {
  2925         return reader.enterClass(syms.boxedName[t.tag]);
  2928     /**
  2929      * Return the boxed type if 't' is primitive, otherwise return 't' itself.
  2930      */
  2931     public Type boxedTypeOrType(Type t) {
  2932         return t.isPrimitive() ?
  2933             boxedClass(t).type :
  2934             t;
  2937     /**
  2938      * Return the primitive type corresponding to a boxed type.
  2939      */
  2940     public Type unboxedType(Type t) {
  2941         if (allowBoxing) {
  2942             for (int i=0; i<syms.boxedName.length; i++) {
  2943                 Name box = syms.boxedName[i];
  2944                 if (box != null &&
  2945                     asSuper(t, reader.enterClass(box)) != null)
  2946                     return syms.typeOfTag[i];
  2949         return Type.noType;
  2951     // </editor-fold>
  2953     // <editor-fold defaultstate="collapsed" desc="Capture conversion">
  2954     /*
  2955      * JLS 3rd Ed. 5.1.10 Capture Conversion:
  2957      * Let G name a generic type declaration with n formal type
  2958      * parameters A1 ... An with corresponding bounds U1 ... Un. There
  2959      * exists a capture conversion from G<T1 ... Tn> to G<S1 ... Sn>,
  2960      * where, for 1 <= i <= n:
  2962      * + If Ti is a wildcard type argument (4.5.1) of the form ? then
  2963      *   Si is a fresh type variable whose upper bound is
  2964      *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is the null
  2965      *   type.
  2967      * + If Ti is a wildcard type argument of the form ? extends Bi,
  2968      *   then Si is a fresh type variable whose upper bound is
  2969      *   glb(Bi, Ui[A1 := S1, ..., An := Sn]) and whose lower bound is
  2970      *   the null type, where glb(V1,... ,Vm) is V1 & ... & Vm. It is
  2971      *   a compile-time error if for any two classes (not interfaces)
  2972      *   Vi and Vj,Vi is not a subclass of Vj or vice versa.
  2974      * + If Ti is a wildcard type argument of the form ? super Bi,
  2975      *   then Si is a fresh type variable whose upper bound is
  2976      *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is Bi.
  2978      * + Otherwise, Si = Ti.
  2980      * Capture conversion on any type other than a parameterized type
  2981      * (4.5) acts as an identity conversion (5.1.1). Capture
  2982      * conversions never require a special action at run time and
  2983      * therefore never throw an exception at run time.
  2985      * Capture conversion is not applied recursively.
  2986      */
  2987     /**
  2988      * Capture conversion as specified by JLS 3rd Ed.
  2989      */
  2991     public List<Type> capture(List<Type> ts) {
  2992         List<Type> buf = List.nil();
  2993         for (Type t : ts) {
  2994             buf = buf.prepend(capture(t));
  2996         return buf.reverse();
  2998     public Type capture(Type t) {
  2999         if (t.tag != CLASS)
  3000             return t;
  3001         if (t.getEnclosingType() != Type.noType) {
  3002             Type capturedEncl = capture(t.getEnclosingType());
  3003             if (capturedEncl != t.getEnclosingType()) {
  3004                 Type type1 = memberType(capturedEncl, t.tsym);
  3005                 t = subst(type1, t.tsym.type.getTypeArguments(), t.getTypeArguments());
  3008         ClassType cls = (ClassType)t;
  3009         if (cls.isRaw() || !cls.isParameterized())
  3010             return cls;
  3012         ClassType G = (ClassType)cls.asElement().asType();
  3013         List<Type> A = G.getTypeArguments();
  3014         List<Type> T = cls.getTypeArguments();
  3015         List<Type> S = freshTypeVariables(T);
  3017         List<Type> currentA = A;
  3018         List<Type> currentT = T;
  3019         List<Type> currentS = S;
  3020         boolean captured = false;
  3021         while (!currentA.isEmpty() &&
  3022                !currentT.isEmpty() &&
  3023                !currentS.isEmpty()) {
  3024             if (currentS.head != currentT.head) {
  3025                 captured = true;
  3026                 WildcardType Ti = (WildcardType)currentT.head;
  3027                 Type Ui = currentA.head.getUpperBound();
  3028                 CapturedType Si = (CapturedType)currentS.head;
  3029                 if (Ui == null)
  3030                     Ui = syms.objectType;
  3031                 switch (Ti.kind) {
  3032                 case UNBOUND:
  3033                     Si.bound = subst(Ui, A, S);
  3034                     Si.lower = syms.botType;
  3035                     break;
  3036                 case EXTENDS:
  3037                     Si.bound = glb(Ti.getExtendsBound(), subst(Ui, A, S));
  3038                     Si.lower = syms.botType;
  3039                     break;
  3040                 case SUPER:
  3041                     Si.bound = subst(Ui, A, S);
  3042                     Si.lower = Ti.getSuperBound();
  3043                     break;
  3045                 if (Si.bound == Si.lower)
  3046                     currentS.head = Si.bound;
  3048             currentA = currentA.tail;
  3049             currentT = currentT.tail;
  3050             currentS = currentS.tail;
  3052         if (!currentA.isEmpty() || !currentT.isEmpty() || !currentS.isEmpty())
  3053             return erasure(t); // some "rare" type involved
  3055         if (captured)
  3056             return new ClassType(cls.getEnclosingType(), S, cls.tsym);
  3057         else
  3058             return t;
  3060     // where
  3061         public List<Type> freshTypeVariables(List<Type> types) {
  3062             ListBuffer<Type> result = lb();
  3063             for (Type t : types) {
  3064                 if (t.tag == WILDCARD) {
  3065                     Type bound = ((WildcardType)t).getExtendsBound();
  3066                     if (bound == null)
  3067                         bound = syms.objectType;
  3068                     result.append(new CapturedType(capturedName,
  3069                                                    syms.noSymbol,
  3070                                                    bound,
  3071                                                    syms.botType,
  3072                                                    (WildcardType)t));
  3073                 } else {
  3074                     result.append(t);
  3077             return result.toList();
  3079     // </editor-fold>
  3081     // <editor-fold defaultstate="collapsed" desc="Internal utility methods">
  3082     private List<Type> upperBounds(List<Type> ss) {
  3083         if (ss.isEmpty()) return ss;
  3084         Type head = upperBound(ss.head);
  3085         List<Type> tail = upperBounds(ss.tail);
  3086         if (head != ss.head || tail != ss.tail)
  3087             return tail.prepend(head);
  3088         else
  3089             return ss;
  3092     private boolean sideCast(Type from, Type to, Warner warn) {
  3093         // We are casting from type $from$ to type $to$, which are
  3094         // non-final unrelated types.  This method
  3095         // tries to reject a cast by transferring type parameters
  3096         // from $to$ to $from$ by common superinterfaces.
  3097         boolean reverse = false;
  3098         Type target = to;
  3099         if ((to.tsym.flags() & INTERFACE) == 0) {
  3100             assert (from.tsym.flags() & INTERFACE) != 0;
  3101             reverse = true;
  3102             to = from;
  3103             from = target;
  3105         List<Type> commonSupers = superClosure(to, erasure(from));
  3106         boolean giveWarning = commonSupers.isEmpty();
  3107         // The arguments to the supers could be unified here to
  3108         // get a more accurate analysis
  3109         while (commonSupers.nonEmpty()) {
  3110             Type t1 = asSuper(from, commonSupers.head.tsym);
  3111             Type t2 = commonSupers.head; // same as asSuper(to, commonSupers.head.tsym);
  3112             if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
  3113                 return false;
  3114             giveWarning = giveWarning || (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2));
  3115             commonSupers = commonSupers.tail;
  3117         if (giveWarning && !isReifiable(reverse ? from : to))
  3118             warn.warnUnchecked();
  3119         if (!source.allowCovariantReturns())
  3120             // reject if there is a common method signature with
  3121             // incompatible return types.
  3122             chk.checkCompatibleAbstracts(warn.pos(), from, to);
  3123         return true;
  3126     private boolean sideCastFinal(Type from, Type to, Warner warn) {
  3127         // We are casting from type $from$ to type $to$, which are
  3128         // unrelated types one of which is final and the other of
  3129         // which is an interface.  This method
  3130         // tries to reject a cast by transferring type parameters
  3131         // from the final class to the interface.
  3132         boolean reverse = false;
  3133         Type target = to;
  3134         if ((to.tsym.flags() & INTERFACE) == 0) {
  3135             assert (from.tsym.flags() & INTERFACE) != 0;
  3136             reverse = true;
  3137             to = from;
  3138             from = target;
  3140         assert (from.tsym.flags() & FINAL) != 0;
  3141         Type t1 = asSuper(from, to.tsym);
  3142         if (t1 == null) return false;
  3143         Type t2 = to;
  3144         if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
  3145             return false;
  3146         if (!source.allowCovariantReturns())
  3147             // reject if there is a common method signature with
  3148             // incompatible return types.
  3149             chk.checkCompatibleAbstracts(warn.pos(), from, to);
  3150         if (!isReifiable(target) &&
  3151             (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2)))
  3152             warn.warnUnchecked();
  3153         return true;
  3156     private boolean giveWarning(Type from, Type to) {
  3157         Type subFrom = asSub(from, to.tsym);
  3158         return to.isParameterized() &&
  3159                 (!(isUnbounded(to) ||
  3160                 isSubtype(from, to) ||
  3161                 ((subFrom != null) && containsType(to.allparams(), subFrom.allparams()))));
  3164     private List<Type> superClosure(Type t, Type s) {
  3165         List<Type> cl = List.nil();
  3166         for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
  3167             if (isSubtype(s, erasure(l.head))) {
  3168                 cl = insert(cl, l.head);
  3169             } else {
  3170                 cl = union(cl, superClosure(l.head, s));
  3173         return cl;
  3176     private boolean containsTypeEquivalent(Type t, Type s) {
  3177         return
  3178             isSameType(t, s) || // shortcut
  3179             containsType(t, s) && containsType(s, t);
  3182     // <editor-fold defaultstate="collapsed" desc="adapt">
  3183     /**
  3184      * Adapt a type by computing a substitution which maps a source
  3185      * type to a target type.
  3187      * @param source    the source type
  3188      * @param target    the target type
  3189      * @param from      the type variables of the computed substitution
  3190      * @param to        the types of the computed substitution.
  3191      */
  3192     public void adapt(Type source,
  3193                        Type target,
  3194                        ListBuffer<Type> from,
  3195                        ListBuffer<Type> to) throws AdaptFailure {
  3196         new Adapter(from, to).adapt(source, target);
  3199     class Adapter extends SimpleVisitor<Void, Type> {
  3201         ListBuffer<Type> from;
  3202         ListBuffer<Type> to;
  3203         Map<Symbol,Type> mapping;
  3205         Adapter(ListBuffer<Type> from, ListBuffer<Type> to) {
  3206             this.from = from;
  3207             this.to = to;
  3208             mapping = new HashMap<Symbol,Type>();
  3211         public void adapt(Type source, Type target) throws AdaptFailure {
  3212             visit(source, target);
  3213             List<Type> fromList = from.toList();
  3214             List<Type> toList = to.toList();
  3215             while (!fromList.isEmpty()) {
  3216                 Type val = mapping.get(fromList.head.tsym);
  3217                 if (toList.head != val)
  3218                     toList.head = val;
  3219                 fromList = fromList.tail;
  3220                 toList = toList.tail;
  3224         @Override
  3225         public Void visitClassType(ClassType source, Type target) throws AdaptFailure {
  3226             if (target.tag == CLASS)
  3227                 adaptRecursive(source.allparams(), target.allparams());
  3228             return null;
  3231         @Override
  3232         public Void visitArrayType(ArrayType source, Type target) throws AdaptFailure {
  3233             if (target.tag == ARRAY)
  3234                 adaptRecursive(elemtype(source), elemtype(target));
  3235             return null;
  3238         @Override
  3239         public Void visitWildcardType(WildcardType source, Type target) throws AdaptFailure {
  3240             if (source.isExtendsBound())
  3241                 adaptRecursive(upperBound(source), upperBound(target));
  3242             else if (source.isSuperBound())
  3243                 adaptRecursive(lowerBound(source), lowerBound(target));
  3244             return null;
  3247         @Override
  3248         public Void visitTypeVar(TypeVar source, Type target) throws AdaptFailure {
  3249             // Check to see if there is
  3250             // already a mapping for $source$, in which case
  3251             // the old mapping will be merged with the new
  3252             Type val = mapping.get(source.tsym);
  3253             if (val != null) {
  3254                 if (val.isSuperBound() && target.isSuperBound()) {
  3255                     val = isSubtype(lowerBound(val), lowerBound(target))
  3256                         ? target : val;
  3257                 } else if (val.isExtendsBound() && target.isExtendsBound()) {
  3258                     val = isSubtype(upperBound(val), upperBound(target))
  3259                         ? val : target;
  3260                 } else if (!isSameType(val, target)) {
  3261                     throw new AdaptFailure();
  3263             } else {
  3264                 val = target;
  3265                 from.append(source);
  3266                 to.append(target);
  3268             mapping.put(source.tsym, val);
  3269             return null;
  3272         @Override
  3273         public Void visitType(Type source, Type target) {
  3274             return null;
  3277         private Set<TypePair> cache = new HashSet<TypePair>();
  3279         private void adaptRecursive(Type source, Type target) {
  3280             TypePair pair = new TypePair(source, target);
  3281             if (cache.add(pair)) {
  3282                 try {
  3283                     visit(source, target);
  3284                 } finally {
  3285                     cache.remove(pair);
  3290         private void adaptRecursive(List<Type> source, List<Type> target) {
  3291             if (source.length() == target.length()) {
  3292                 while (source.nonEmpty()) {
  3293                     adaptRecursive(source.head, target.head);
  3294                     source = source.tail;
  3295                     target = target.tail;
  3301     public static class AdaptFailure extends RuntimeException {
  3302         static final long serialVersionUID = -7490231548272701566L;
  3305     private void adaptSelf(Type t,
  3306                            ListBuffer<Type> from,
  3307                            ListBuffer<Type> to) {
  3308         try {
  3309             //if (t.tsym.type != t)
  3310                 adapt(t.tsym.type, t, from, to);
  3311         } catch (AdaptFailure ex) {
  3312             // Adapt should never fail calculating a mapping from
  3313             // t.tsym.type to t as there can be no merge problem.
  3314             throw new AssertionError(ex);
  3317     // </editor-fold>
  3319     /**
  3320      * Rewrite all type variables (universal quantifiers) in the given
  3321      * type to wildcards (existential quantifiers).  This is used to
  3322      * determine if a cast is allowed.  For example, if high is true
  3323      * and {@code T <: Number}, then {@code List<T>} is rewritten to
  3324      * {@code List<?  extends Number>}.  Since {@code List<Integer> <:
  3325      * List<? extends Number>} a {@code List<T>} can be cast to {@code
  3326      * List<Integer>} with a warning.
  3327      * @param t a type
  3328      * @param high if true return an upper bound; otherwise a lower
  3329      * bound
  3330      * @param rewriteTypeVars only rewrite captured wildcards if false;
  3331      * otherwise rewrite all type variables
  3332      * @return the type rewritten with wildcards (existential
  3333      * quantifiers) only
  3334      */
  3335     private Type rewriteQuantifiers(Type t, boolean high, boolean rewriteTypeVars) {
  3336         return new Rewriter(high, rewriteTypeVars).visit(t);
  3339     class Rewriter extends UnaryVisitor<Type> {
  3341         boolean high;
  3342         boolean rewriteTypeVars;
  3344         Rewriter(boolean high, boolean rewriteTypeVars) {
  3345             this.high = high;
  3346             this.rewriteTypeVars = rewriteTypeVars;
  3349         @Override
  3350         public Type visitClassType(ClassType t, Void s) {
  3351             ListBuffer<Type> rewritten = new ListBuffer<Type>();
  3352             boolean changed = false;
  3353             for (Type arg : t.allparams()) {
  3354                 Type bound = visit(arg);
  3355                 if (arg != bound) {
  3356                     changed = true;
  3358                 rewritten.append(bound);
  3360             if (changed)
  3361                 return subst(t.tsym.type,
  3362                         t.tsym.type.allparams(),
  3363                         rewritten.toList());
  3364             else
  3365                 return t;
  3368         public Type visitType(Type t, Void s) {
  3369             return high ? upperBound(t) : lowerBound(t);
  3372         @Override
  3373         public Type visitCapturedType(CapturedType t, Void s) {
  3374             Type bound = visitWildcardType(t.wildcard, null);
  3375             return (bound.contains(t)) ?
  3376                     erasure(bound) :
  3377                     bound;
  3380         @Override
  3381         public Type visitTypeVar(TypeVar t, Void s) {
  3382             if (rewriteTypeVars) {
  3383                 Type bound = high ?
  3384                     (t.bound.contains(t) ?
  3385                         erasure(t.bound) :
  3386                         visit(t.bound)) :
  3387                     syms.botType;
  3388                 return rewriteAsWildcardType(bound, t);
  3390             else
  3391                 return t;
  3394         @Override
  3395         public Type visitWildcardType(WildcardType t, Void s) {
  3396             Type bound = high ? t.getExtendsBound() :
  3397                                 t.getSuperBound();
  3398             if (bound == null)
  3399             bound = high ? syms.objectType : syms.botType;
  3400             return rewriteAsWildcardType(visit(bound), t.bound);
  3403         private Type rewriteAsWildcardType(Type bound, TypeVar formal) {
  3404             return high ?
  3405                 makeExtendsWildcard(B(bound), formal) :
  3406                 makeSuperWildcard(B(bound), formal);
  3409         Type B(Type t) {
  3410             while (t.tag == WILDCARD) {
  3411                 WildcardType w = (WildcardType)t;
  3412                 t = high ?
  3413                     w.getExtendsBound() :
  3414                     w.getSuperBound();
  3415                 if (t == null) {
  3416                     t = high ? syms.objectType : syms.botType;
  3419             return t;
  3424     /**
  3425      * Create a wildcard with the given upper (extends) bound; create
  3426      * an unbounded wildcard if bound is Object.
  3428      * @param bound the upper bound
  3429      * @param formal the formal type parameter that will be
  3430      * substituted by the wildcard
  3431      */
  3432     private WildcardType makeExtendsWildcard(Type bound, TypeVar formal) {
  3433         if (bound == syms.objectType) {
  3434             return new WildcardType(syms.objectType,
  3435                                     BoundKind.UNBOUND,
  3436                                     syms.boundClass,
  3437                                     formal);
  3438         } else {
  3439             return new WildcardType(bound,
  3440                                     BoundKind.EXTENDS,
  3441                                     syms.boundClass,
  3442                                     formal);
  3446     /**
  3447      * Create a wildcard with the given lower (super) bound; create an
  3448      * unbounded wildcard if bound is bottom (type of {@code null}).
  3450      * @param bound the lower bound
  3451      * @param formal the formal type parameter that will be
  3452      * substituted by the wildcard
  3453      */
  3454     private WildcardType makeSuperWildcard(Type bound, TypeVar formal) {
  3455         if (bound.tag == BOT) {
  3456             return new WildcardType(syms.objectType,
  3457                                     BoundKind.UNBOUND,
  3458                                     syms.boundClass,
  3459                                     formal);
  3460         } else {
  3461             return new WildcardType(bound,
  3462                                     BoundKind.SUPER,
  3463                                     syms.boundClass,
  3464                                     formal);
  3468     /**
  3469      * A wrapper for a type that allows use in sets.
  3470      */
  3471     class SingletonType {
  3472         final Type t;
  3473         SingletonType(Type t) {
  3474             this.t = t;
  3476         public int hashCode() {
  3477             return Types.hashCode(t);
  3479         public boolean equals(Object obj) {
  3480             return (obj instanceof SingletonType) &&
  3481                 isSameType(t, ((SingletonType)obj).t);
  3483         public String toString() {
  3484             return t.toString();
  3487     // </editor-fold>
  3489     // <editor-fold defaultstate="collapsed" desc="Visitors">
  3490     /**
  3491      * A default visitor for types.  All visitor methods except
  3492      * visitType are implemented by delegating to visitType.  Concrete
  3493      * subclasses must provide an implementation of visitType and can
  3494      * override other methods as needed.
  3496      * @param <R> the return type of the operation implemented by this
  3497      * visitor; use Void if no return type is needed.
  3498      * @param <S> the type of the second argument (the first being the
  3499      * type itself) of the operation implemented by this visitor; use
  3500      * Void if a second argument is not needed.
  3501      */
  3502     public static abstract class DefaultTypeVisitor<R,S> implements Type.Visitor<R,S> {
  3503         final public R visit(Type t, S s)               { return t.accept(this, s); }
  3504         public R visitClassType(ClassType t, S s)       { return visitType(t, s); }
  3505         public R visitWildcardType(WildcardType t, S s) { return visitType(t, s); }
  3506         public R visitArrayType(ArrayType t, S s)       { return visitType(t, s); }
  3507         public R visitMethodType(MethodType t, S s)     { return visitType(t, s); }
  3508         public R visitPackageType(PackageType t, S s)   { return visitType(t, s); }
  3509         public R visitTypeVar(TypeVar t, S s)           { return visitType(t, s); }
  3510         public R visitCapturedType(CapturedType t, S s) { return visitType(t, s); }
  3511         public R visitForAll(ForAll t, S s)             { return visitType(t, s); }
  3512         public R visitUndetVar(UndetVar t, S s)         { return visitType(t, s); }
  3513         public R visitErrorType(ErrorType t, S s)       { return visitType(t, s); }
  3516     /**
  3517      * A default visitor for symbols.  All visitor methods except
  3518      * visitSymbol are implemented by delegating to visitSymbol.  Concrete
  3519      * subclasses must provide an implementation of visitSymbol and can
  3520      * override other methods as needed.
  3522      * @param <R> the return type of the operation implemented by this
  3523      * visitor; use Void if no return type is needed.
  3524      * @param <S> the type of the second argument (the first being the
  3525      * symbol itself) of the operation implemented by this visitor; use
  3526      * Void if a second argument is not needed.
  3527      */
  3528     public static abstract class DefaultSymbolVisitor<R,S> implements Symbol.Visitor<R,S> {
  3529         final public R visit(Symbol s, S arg)                   { return s.accept(this, arg); }
  3530         public R visitClassSymbol(ClassSymbol s, S arg)         { return visitSymbol(s, arg); }
  3531         public R visitMethodSymbol(MethodSymbol s, S arg)       { return visitSymbol(s, arg); }
  3532         public R visitOperatorSymbol(OperatorSymbol s, S arg)   { return visitSymbol(s, arg); }
  3533         public R visitPackageSymbol(PackageSymbol s, S arg)     { return visitSymbol(s, arg); }
  3534         public R visitTypeSymbol(TypeSymbol s, S arg)           { return visitSymbol(s, arg); }
  3535         public R visitVarSymbol(VarSymbol s, S arg)             { return visitSymbol(s, arg); }
  3538     /**
  3539      * A <em>simple</em> visitor for types.  This visitor is simple as
  3540      * captured wildcards, for-all types (generic methods), and
  3541      * undetermined type variables (part of inference) are hidden.
  3542      * Captured wildcards are hidden by treating them as type
  3543      * variables and the rest are hidden by visiting their qtypes.
  3545      * @param <R> the return type of the operation implemented by this
  3546      * visitor; use Void if no return type is needed.
  3547      * @param <S> the type of the second argument (the first being the
  3548      * type itself) of the operation implemented by this visitor; use
  3549      * Void if a second argument is not needed.
  3550      */
  3551     public static abstract class SimpleVisitor<R,S> extends DefaultTypeVisitor<R,S> {
  3552         @Override
  3553         public R visitCapturedType(CapturedType t, S s) {
  3554             return visitTypeVar(t, s);
  3556         @Override
  3557         public R visitForAll(ForAll t, S s) {
  3558             return visit(t.qtype, s);
  3560         @Override
  3561         public R visitUndetVar(UndetVar t, S s) {
  3562             return visit(t.qtype, s);
  3566     /**
  3567      * A plain relation on types.  That is a 2-ary function on the
  3568      * form Type&nbsp;&times;&nbsp;Type&nbsp;&rarr;&nbsp;Boolean.
  3569      * <!-- In plain text: Type x Type -> Boolean -->
  3570      */
  3571     public static abstract class TypeRelation extends SimpleVisitor<Boolean,Type> {}
  3573     /**
  3574      * A convenience visitor for implementing operations that only
  3575      * require one argument (the type itself), that is, unary
  3576      * operations.
  3578      * @param <R> the return type of the operation implemented by this
  3579      * visitor; use Void if no return type is needed.
  3580      */
  3581     public static abstract class UnaryVisitor<R> extends SimpleVisitor<R,Void> {
  3582         final public R visit(Type t) { return t.accept(this, null); }
  3585     /**
  3586      * A visitor for implementing a mapping from types to types.  The
  3587      * default behavior of this class is to implement the identity
  3588      * mapping (mapping a type to itself).  This can be overridden in
  3589      * subclasses.
  3591      * @param <S> the type of the second argument (the first being the
  3592      * type itself) of this mapping; use Void if a second argument is
  3593      * not needed.
  3594      */
  3595     public static class MapVisitor<S> extends DefaultTypeVisitor<Type,S> {
  3596         final public Type visit(Type t) { return t.accept(this, null); }
  3597         public Type visitType(Type t, S s) { return t; }
  3599     // </editor-fold>
  3602     // <editor-fold defaultstate="collapsed" desc="Annotation support">
  3604     public RetentionPolicy getRetention(Attribute.Compound a) {
  3605         RetentionPolicy vis = RetentionPolicy.CLASS; // the default
  3606         Attribute.Compound c = a.type.tsym.attribute(syms.retentionType.tsym);
  3607         if (c != null) {
  3608             Attribute value = c.member(names.value);
  3609             if (value != null && value instanceof Attribute.Enum) {
  3610                 Name levelName = ((Attribute.Enum)value).value.name;
  3611                 if (levelName == names.SOURCE) vis = RetentionPolicy.SOURCE;
  3612                 else if (levelName == names.CLASS) vis = RetentionPolicy.CLASS;
  3613                 else if (levelName == names.RUNTIME) vis = RetentionPolicy.RUNTIME;
  3614                 else ;// /* fail soft */ throw new AssertionError(levelName);
  3617         return vis;
  3619     // </editor-fold>

mercurial