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

Mon, 17 Oct 2011 12:54:33 +0100

author
mcimadamore
date
Mon, 17 Oct 2011 12:54:33 +0100
changeset 1108
b5d0b8effc85
parent 1093
c0835c8489b0
child 1177
70d92518063e
permissions
-rw-r--r--

7097436: Project Coin: duplicate varargs warnings on method annotated with @SafeVarargs
Summary: Duplicate aliasing check during subtyping leads to spurious varargs diagnostic
Reviewed-by: jjg

     1 /*
     2  * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    26 package com.sun.tools.javac.code;
    28 import java.lang.ref.SoftReference;
    29 import java.util.*;
    31 import com.sun.tools.javac.util.*;
    32 import com.sun.tools.javac.util.List;
    34 import com.sun.tools.javac.jvm.ClassReader;
    35 import com.sun.tools.javac.code.Attribute.RetentionPolicy;
    36 import com.sun.tools.javac.code.Lint.LintCategory;
    37 import com.sun.tools.javac.comp.Check;
    39 import static com.sun.tools.javac.code.Scope.*;
    40 import static com.sun.tools.javac.code.Type.*;
    41 import static com.sun.tools.javac.code.TypeTags.*;
    42 import static com.sun.tools.javac.code.Symbol.*;
    43 import static com.sun.tools.javac.code.Flags.*;
    44 import static com.sun.tools.javac.code.BoundKind.*;
    45 import static com.sun.tools.javac.util.ListBuffer.lb;
    47 /**
    48  * Utility class containing various operations on types.
    49  *
    50  * <p>Unless other names are more illustrative, the following naming
    51  * conventions should be observed in this file:
    52  *
    53  * <dl>
    54  * <dt>t</dt>
    55  * <dd>If the first argument to an operation is a type, it should be named t.</dd>
    56  * <dt>s</dt>
    57  * <dd>Similarly, if the second argument to an operation is a type, it should be named s.</dd>
    58  * <dt>ts</dt>
    59  * <dd>If an operations takes a list of types, the first should be named ts.</dd>
    60  * <dt>ss</dt>
    61  * <dd>A second list of types should be named ss.</dd>
    62  * </dl>
    63  *
    64  * <p><b>This is NOT part of any supported API.
    65  * If you write code that depends on this, you do so at your own risk.
    66  * This code and its internal interfaces are subject to change or
    67  * deletion without notice.</b>
    68  */
    69 public class Types {
    70     protected static final Context.Key<Types> typesKey =
    71         new Context.Key<Types>();
    73     final Symtab syms;
    74     final JavacMessages messages;
    75     final Names names;
    76     final boolean allowBoxing;
    77     final boolean allowCovariantReturns;
    78     final boolean allowObjectToPrimitiveCast;
    79     final ClassReader reader;
    80     final Check chk;
    81     List<Warner> warnStack = List.nil();
    82     final Name capturedName;
    84     // <editor-fold defaultstate="collapsed" desc="Instantiating">
    85     public static Types instance(Context context) {
    86         Types instance = context.get(typesKey);
    87         if (instance == null)
    88             instance = new Types(context);
    89         return instance;
    90     }
    92     protected Types(Context context) {
    93         context.put(typesKey, this);
    94         syms = Symtab.instance(context);
    95         names = Names.instance(context);
    96         Source source = Source.instance(context);
    97         allowBoxing = source.allowBoxing();
    98         allowCovariantReturns = source.allowCovariantReturns();
    99         allowObjectToPrimitiveCast = source.allowObjectToPrimitiveCast();
   100         reader = ClassReader.instance(context);
   101         chk = Check.instance(context);
   102         capturedName = names.fromString("<captured wildcard>");
   103         messages = JavacMessages.instance(context);
   104     }
   105     // </editor-fold>
   107     // <editor-fold defaultstate="collapsed" desc="upperBound">
   108     /**
   109      * The "rvalue conversion".<br>
   110      * The upper bound of most types is the type
   111      * itself.  Wildcards, on the other hand have upper
   112      * and lower bounds.
   113      * @param t a type
   114      * @return the upper bound of the given type
   115      */
   116     public Type upperBound(Type t) {
   117         return upperBound.visit(t);
   118     }
   119     // where
   120         private final MapVisitor<Void> upperBound = new MapVisitor<Void>() {
   122             @Override
   123             public Type visitWildcardType(WildcardType t, Void ignored) {
   124                 if (t.isSuperBound())
   125                     return t.bound == null ? syms.objectType : t.bound.bound;
   126                 else
   127                     return visit(t.type);
   128             }
   130             @Override
   131             public Type visitCapturedType(CapturedType t, Void ignored) {
   132                 return visit(t.bound);
   133             }
   134         };
   135     // </editor-fold>
   137     // <editor-fold defaultstate="collapsed" desc="lowerBound">
   138     /**
   139      * The "lvalue conversion".<br>
   140      * The lower bound of most types is the type
   141      * itself.  Wildcards, on the other hand have upper
   142      * and lower bounds.
   143      * @param t a type
   144      * @return the lower bound of the given type
   145      */
   146     public Type lowerBound(Type t) {
   147         return lowerBound.visit(t);
   148     }
   149     // where
   150         private final MapVisitor<Void> lowerBound = new MapVisitor<Void>() {
   152             @Override
   153             public Type visitWildcardType(WildcardType t, Void ignored) {
   154                 return t.isExtendsBound() ? syms.botType : visit(t.type);
   155             }
   157             @Override
   158             public Type visitCapturedType(CapturedType t, Void ignored) {
   159                 return visit(t.getLowerBound());
   160             }
   161         };
   162     // </editor-fold>
   164     // <editor-fold defaultstate="collapsed" desc="isUnbounded">
   165     /**
   166      * Checks that all the arguments to a class are unbounded
   167      * wildcards or something else that doesn't make any restrictions
   168      * on the arguments. If a class isUnbounded, a raw super- or
   169      * subclass can be cast to it without a warning.
   170      * @param t a type
   171      * @return true iff the given type is unbounded or raw
   172      */
   173     public boolean isUnbounded(Type t) {
   174         return isUnbounded.visit(t);
   175     }
   176     // where
   177         private final UnaryVisitor<Boolean> isUnbounded = new UnaryVisitor<Boolean>() {
   179             public Boolean visitType(Type t, Void ignored) {
   180                 return true;
   181             }
   183             @Override
   184             public Boolean visitClassType(ClassType t, Void ignored) {
   185                 List<Type> parms = t.tsym.type.allparams();
   186                 List<Type> args = t.allparams();
   187                 while (parms.nonEmpty()) {
   188                     WildcardType unb = new WildcardType(syms.objectType,
   189                                                         BoundKind.UNBOUND,
   190                                                         syms.boundClass,
   191                                                         (TypeVar)parms.head);
   192                     if (!containsType(args.head, unb))
   193                         return false;
   194                     parms = parms.tail;
   195                     args = args.tail;
   196                 }
   197                 return true;
   198             }
   199         };
   200     // </editor-fold>
   202     // <editor-fold defaultstate="collapsed" desc="asSub">
   203     /**
   204      * Return the least specific subtype of t that starts with symbol
   205      * sym.  If none exists, return null.  The least specific subtype
   206      * is determined as follows:
   207      *
   208      * <p>If there is exactly one parameterized instance of sym that is a
   209      * subtype of t, that parameterized instance is returned.<br>
   210      * Otherwise, if the plain type or raw type `sym' is a subtype of
   211      * type t, the type `sym' itself is returned.  Otherwise, null is
   212      * returned.
   213      */
   214     public Type asSub(Type t, Symbol sym) {
   215         return asSub.visit(t, sym);
   216     }
   217     // where
   218         private final SimpleVisitor<Type,Symbol> asSub = new SimpleVisitor<Type,Symbol>() {
   220             public Type visitType(Type t, Symbol sym) {
   221                 return null;
   222             }
   224             @Override
   225             public Type visitClassType(ClassType t, Symbol sym) {
   226                 if (t.tsym == sym)
   227                     return t;
   228                 Type base = asSuper(sym.type, t.tsym);
   229                 if (base == null)
   230                     return null;
   231                 ListBuffer<Type> from = new ListBuffer<Type>();
   232                 ListBuffer<Type> to = new ListBuffer<Type>();
   233                 try {
   234                     adapt(base, t, from, to);
   235                 } catch (AdaptFailure ex) {
   236                     return null;
   237                 }
   238                 Type res = subst(sym.type, from.toList(), to.toList());
   239                 if (!isSubtype(res, t))
   240                     return null;
   241                 ListBuffer<Type> openVars = new ListBuffer<Type>();
   242                 for (List<Type> l = sym.type.allparams();
   243                      l.nonEmpty(); l = l.tail)
   244                     if (res.contains(l.head) && !t.contains(l.head))
   245                         openVars.append(l.head);
   246                 if (openVars.nonEmpty()) {
   247                     if (t.isRaw()) {
   248                         // The subtype of a raw type is raw
   249                         res = erasure(res);
   250                     } else {
   251                         // Unbound type arguments default to ?
   252                         List<Type> opens = openVars.toList();
   253                         ListBuffer<Type> qs = new ListBuffer<Type>();
   254                         for (List<Type> iter = opens; iter.nonEmpty(); iter = iter.tail) {
   255                             qs.append(new WildcardType(syms.objectType, BoundKind.UNBOUND, syms.boundClass, (TypeVar) iter.head));
   256                         }
   257                         res = subst(res, opens, qs.toList());
   258                     }
   259                 }
   260                 return res;
   261             }
   263             @Override
   264             public Type visitErrorType(ErrorType t, Symbol sym) {
   265                 return t;
   266             }
   267         };
   268     // </editor-fold>
   270     // <editor-fold defaultstate="collapsed" desc="isConvertible">
   271     /**
   272      * Is t a subtype of or convertible via boxing/unboxing
   273      * conversion to s?
   274      */
   275     public boolean isConvertible(Type t, Type s, Warner warn) {
   276         if (t.tag == ERROR)
   277             return true;
   278         boolean tPrimitive = t.isPrimitive();
   279         boolean sPrimitive = s.isPrimitive();
   280         if (tPrimitive == sPrimitive) {
   281             return isSubtypeUnchecked(t, s, warn);
   282         }
   283         if (!allowBoxing) return false;
   284         return tPrimitive
   285             ? isSubtype(boxedClass(t).type, s)
   286             : isSubtype(unboxedType(t), s);
   287     }
   289     /**
   290      * Is t a subtype of or convertiable via boxing/unboxing
   291      * convertions to s?
   292      */
   293     public boolean isConvertible(Type t, Type s) {
   294         return isConvertible(t, s, Warner.noWarnings);
   295     }
   296     // </editor-fold>
   298     // <editor-fold defaultstate="collapsed" desc="isSubtype">
   299     /**
   300      * Is t an unchecked subtype of s?
   301      */
   302     public boolean isSubtypeUnchecked(Type t, Type s) {
   303         return isSubtypeUnchecked(t, s, Warner.noWarnings);
   304     }
   305     /**
   306      * Is t an unchecked subtype of s?
   307      */
   308     public boolean isSubtypeUnchecked(Type t, Type s, Warner warn) {
   309         boolean result = isSubtypeUncheckedInternal(t, s, warn);
   310         if (result) {
   311             checkUnsafeVarargsConversion(t, s, warn);
   312         }
   313         return result;
   314     }
   315     //where
   316         private boolean isSubtypeUncheckedInternal(Type t, Type s, Warner warn) {
   317             if (t.tag == ARRAY && s.tag == ARRAY) {
   318                 if (((ArrayType)t).elemtype.tag <= lastBaseTag) {
   319                     return isSameType(elemtype(t), elemtype(s));
   320                 } else {
   321                     return isSubtypeUnchecked(elemtype(t), elemtype(s), warn);
   322                 }
   323             } else if (isSubtype(t, s)) {
   324                 return true;
   325             }
   326             else if (t.tag == TYPEVAR) {
   327                 return isSubtypeUnchecked(t.getUpperBound(), s, warn);
   328             }
   329             else if (s.tag == UNDETVAR) {
   330                 UndetVar uv = (UndetVar)s;
   331                 if (uv.inst != null)
   332                     return isSubtypeUnchecked(t, uv.inst, warn);
   333             }
   334             else if (!s.isRaw()) {
   335                 Type t2 = asSuper(t, s.tsym);
   336                 if (t2 != null && t2.isRaw()) {
   337                     if (isReifiable(s))
   338                         warn.silentWarn(LintCategory.UNCHECKED);
   339                     else
   340                         warn.warn(LintCategory.UNCHECKED);
   341                     return true;
   342                 }
   343             }
   344             return false;
   345         }
   347         private void checkUnsafeVarargsConversion(Type t, Type s, Warner warn) {
   348             if (t.tag != ARRAY || isReifiable(t)) return;
   349             ArrayType from = (ArrayType)t;
   350             boolean shouldWarn = false;
   351             switch (s.tag) {
   352                 case ARRAY:
   353                     ArrayType to = (ArrayType)s;
   354                     shouldWarn = from.isVarargs() &&
   355                             !to.isVarargs() &&
   356                             !isReifiable(from);
   357                     break;
   358                 case CLASS:
   359                     shouldWarn = from.isVarargs();
   360                     break;
   361             }
   362             if (shouldWarn) {
   363                 warn.warn(LintCategory.VARARGS);
   364             }
   365         }
   367     /**
   368      * Is t a subtype of s?<br>
   369      * (not defined for Method and ForAll types)
   370      */
   371     final public boolean isSubtype(Type t, Type s) {
   372         return isSubtype(t, s, true);
   373     }
   374     final public boolean isSubtypeNoCapture(Type t, Type s) {
   375         return isSubtype(t, s, false);
   376     }
   377     public boolean isSubtype(Type t, Type s, boolean capture) {
   378         if (t == s)
   379             return true;
   381         if (s.tag >= firstPartialTag)
   382             return isSuperType(s, t);
   384         if (s.isCompound()) {
   385             for (Type s2 : interfaces(s).prepend(supertype(s))) {
   386                 if (!isSubtype(t, s2, capture))
   387                     return false;
   388             }
   389             return true;
   390         }
   392         Type lower = lowerBound(s);
   393         if (s != lower)
   394             return isSubtype(capture ? capture(t) : t, lower, false);
   396         return isSubtype.visit(capture ? capture(t) : t, s);
   397     }
   398     // where
   399         private TypeRelation isSubtype = new TypeRelation()
   400         {
   401             public Boolean visitType(Type t, Type s) {
   402                 switch (t.tag) {
   403                 case BYTE: case CHAR:
   404                     return (t.tag == s.tag ||
   405                               t.tag + 2 <= s.tag && s.tag <= DOUBLE);
   406                 case SHORT: case INT: case LONG: case FLOAT: case DOUBLE:
   407                     return t.tag <= s.tag && s.tag <= DOUBLE;
   408                 case BOOLEAN: case VOID:
   409                     return t.tag == s.tag;
   410                 case TYPEVAR:
   411                     return isSubtypeNoCapture(t.getUpperBound(), s);
   412                 case BOT:
   413                     return
   414                         s.tag == BOT || s.tag == CLASS ||
   415                         s.tag == ARRAY || s.tag == TYPEVAR;
   416                 case WILDCARD: //we shouldn't be here - avoids crash (see 7034495)
   417                 case NONE:
   418                     return false;
   419                 default:
   420                     throw new AssertionError("isSubtype " + t.tag);
   421                 }
   422             }
   424             private Set<TypePair> cache = new HashSet<TypePair>();
   426             private boolean containsTypeRecursive(Type t, Type s) {
   427                 TypePair pair = new TypePair(t, s);
   428                 if (cache.add(pair)) {
   429                     try {
   430                         return containsType(t.getTypeArguments(),
   431                                             s.getTypeArguments());
   432                     } finally {
   433                         cache.remove(pair);
   434                     }
   435                 } else {
   436                     return containsType(t.getTypeArguments(),
   437                                         rewriteSupers(s).getTypeArguments());
   438                 }
   439             }
   441             private Type rewriteSupers(Type t) {
   442                 if (!t.isParameterized())
   443                     return t;
   444                 ListBuffer<Type> from = lb();
   445                 ListBuffer<Type> to = lb();
   446                 adaptSelf(t, from, to);
   447                 if (from.isEmpty())
   448                     return t;
   449                 ListBuffer<Type> rewrite = lb();
   450                 boolean changed = false;
   451                 for (Type orig : to.toList()) {
   452                     Type s = rewriteSupers(orig);
   453                     if (s.isSuperBound() && !s.isExtendsBound()) {
   454                         s = new WildcardType(syms.objectType,
   455                                              BoundKind.UNBOUND,
   456                                              syms.boundClass);
   457                         changed = true;
   458                     } else if (s != orig) {
   459                         s = new WildcardType(upperBound(s),
   460                                              BoundKind.EXTENDS,
   461                                              syms.boundClass);
   462                         changed = true;
   463                     }
   464                     rewrite.append(s);
   465                 }
   466                 if (changed)
   467                     return subst(t.tsym.type, from.toList(), rewrite.toList());
   468                 else
   469                     return t;
   470             }
   472             @Override
   473             public Boolean visitClassType(ClassType t, Type s) {
   474                 Type sup = asSuper(t, s.tsym);
   475                 return sup != null
   476                     && sup.tsym == s.tsym
   477                     // You're not allowed to write
   478                     //     Vector<Object> vec = new Vector<String>();
   479                     // But with wildcards you can write
   480                     //     Vector<? extends Object> vec = new Vector<String>();
   481                     // which means that subtype checking must be done
   482                     // here instead of same-type checking (via containsType).
   483                     && (!s.isParameterized() || containsTypeRecursive(s, sup))
   484                     && isSubtypeNoCapture(sup.getEnclosingType(),
   485                                           s.getEnclosingType());
   486             }
   488             @Override
   489             public Boolean visitArrayType(ArrayType t, Type s) {
   490                 if (s.tag == ARRAY) {
   491                     if (t.elemtype.tag <= lastBaseTag)
   492                         return isSameType(t.elemtype, elemtype(s));
   493                     else
   494                         return isSubtypeNoCapture(t.elemtype, elemtype(s));
   495                 }
   497                 if (s.tag == CLASS) {
   498                     Name sname = s.tsym.getQualifiedName();
   499                     return sname == names.java_lang_Object
   500                         || sname == names.java_lang_Cloneable
   501                         || sname == names.java_io_Serializable;
   502                 }
   504                 return false;
   505             }
   507             @Override
   508             public Boolean visitUndetVar(UndetVar t, Type s) {
   509                 //todo: test against origin needed? or replace with substitution?
   510                 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN) {
   511                     return true;
   512                 } else if (s.tag == BOT) {
   513                     //if 's' is 'null' there's no instantiated type U for which
   514                     //U <: s (but 'null' itself, which is not a valid type)
   515                     return false;
   516                 }
   518                 if (t.inst != null)
   519                     return isSubtypeNoCapture(t.inst, s); // TODO: ", warn"?
   521                 t.hibounds = t.hibounds.prepend(s);
   522                 return true;
   523             }
   525             @Override
   526             public Boolean visitErrorType(ErrorType t, Type s) {
   527                 return true;
   528             }
   529         };
   531     /**
   532      * Is t a subtype of every type in given list `ts'?<br>
   533      * (not defined for Method and ForAll types)<br>
   534      * Allows unchecked conversions.
   535      */
   536     public boolean isSubtypeUnchecked(Type t, List<Type> ts, Warner warn) {
   537         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
   538             if (!isSubtypeUnchecked(t, l.head, warn))
   539                 return false;
   540         return true;
   541     }
   543     /**
   544      * Are corresponding elements of ts subtypes of ss?  If lists are
   545      * of different length, return false.
   546      */
   547     public boolean isSubtypes(List<Type> ts, List<Type> ss) {
   548         while (ts.tail != null && ss.tail != null
   549                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   550                isSubtype(ts.head, ss.head)) {
   551             ts = ts.tail;
   552             ss = ss.tail;
   553         }
   554         return ts.tail == null && ss.tail == null;
   555         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   556     }
   558     /**
   559      * Are corresponding elements of ts subtypes of ss, allowing
   560      * unchecked conversions?  If lists are of different length,
   561      * return false.
   562      **/
   563     public boolean isSubtypesUnchecked(List<Type> ts, List<Type> ss, Warner warn) {
   564         while (ts.tail != null && ss.tail != null
   565                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   566                isSubtypeUnchecked(ts.head, ss.head, warn)) {
   567             ts = ts.tail;
   568             ss = ss.tail;
   569         }
   570         return ts.tail == null && ss.tail == null;
   571         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   572     }
   573     // </editor-fold>
   575     // <editor-fold defaultstate="collapsed" desc="isSuperType">
   576     /**
   577      * Is t a supertype of s?
   578      */
   579     public boolean isSuperType(Type t, Type s) {
   580         switch (t.tag) {
   581         case ERROR:
   582             return true;
   583         case UNDETVAR: {
   584             UndetVar undet = (UndetVar)t;
   585             if (t == s ||
   586                 undet.qtype == s ||
   587                 s.tag == ERROR ||
   588                 s.tag == BOT) return true;
   589             if (undet.inst != null)
   590                 return isSubtype(s, undet.inst);
   591             undet.lobounds = undet.lobounds.prepend(s);
   592             return true;
   593         }
   594         default:
   595             return isSubtype(s, t);
   596         }
   597     }
   598     // </editor-fold>
   600     // <editor-fold defaultstate="collapsed" desc="isSameType">
   601     /**
   602      * Are corresponding elements of the lists the same type?  If
   603      * lists are of different length, return false.
   604      */
   605     public boolean isSameTypes(List<Type> ts, List<Type> ss) {
   606         while (ts.tail != null && ss.tail != null
   607                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   608                isSameType(ts.head, ss.head)) {
   609             ts = ts.tail;
   610             ss = ss.tail;
   611         }
   612         return ts.tail == null && ss.tail == null;
   613         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   614     }
   616     /**
   617      * Is t the same type as s?
   618      */
   619     public boolean isSameType(Type t, Type s) {
   620         return isSameType.visit(t, s);
   621     }
   622     // where
   623         private TypeRelation isSameType = new TypeRelation() {
   625             public Boolean visitType(Type t, Type s) {
   626                 if (t == s)
   627                     return true;
   629                 if (s.tag >= firstPartialTag)
   630                     return visit(s, t);
   632                 switch (t.tag) {
   633                 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
   634                 case DOUBLE: case BOOLEAN: case VOID: case BOT: case NONE:
   635                     return t.tag == s.tag;
   636                 case TYPEVAR: {
   637                     if (s.tag == TYPEVAR) {
   638                         //type-substitution does not preserve type-var types
   639                         //check that type var symbols and bounds are indeed the same
   640                         return t.tsym == s.tsym &&
   641                                 visit(t.getUpperBound(), s.getUpperBound());
   642                     }
   643                     else {
   644                         //special case for s == ? super X, where upper(s) = u
   645                         //check that u == t, where u has been set by Type.withTypeVar
   646                         return s.isSuperBound() &&
   647                                 !s.isExtendsBound() &&
   648                                 visit(t, upperBound(s));
   649                     }
   650                 }
   651                 default:
   652                     throw new AssertionError("isSameType " + t.tag);
   653                 }
   654             }
   656             @Override
   657             public Boolean visitWildcardType(WildcardType t, Type s) {
   658                 if (s.tag >= firstPartialTag)
   659                     return visit(s, t);
   660                 else
   661                     return false;
   662             }
   664             @Override
   665             public Boolean visitClassType(ClassType t, Type s) {
   666                 if (t == s)
   667                     return true;
   669                 if (s.tag >= firstPartialTag)
   670                     return visit(s, t);
   672                 if (s.isSuperBound() && !s.isExtendsBound())
   673                     return visit(t, upperBound(s)) && visit(t, lowerBound(s));
   675                 if (t.isCompound() && s.isCompound()) {
   676                     if (!visit(supertype(t), supertype(s)))
   677                         return false;
   679                     HashSet<SingletonType> set = new HashSet<SingletonType>();
   680                     for (Type x : interfaces(t))
   681                         set.add(new SingletonType(x));
   682                     for (Type x : interfaces(s)) {
   683                         if (!set.remove(new SingletonType(x)))
   684                             return false;
   685                     }
   686                     return (set.isEmpty());
   687                 }
   688                 return t.tsym == s.tsym
   689                     && visit(t.getEnclosingType(), s.getEnclosingType())
   690                     && containsTypeEquivalent(t.getTypeArguments(), s.getTypeArguments());
   691             }
   693             @Override
   694             public Boolean visitArrayType(ArrayType t, Type s) {
   695                 if (t == s)
   696                     return true;
   698                 if (s.tag >= firstPartialTag)
   699                     return visit(s, t);
   701                 return s.tag == ARRAY
   702                     && containsTypeEquivalent(t.elemtype, elemtype(s));
   703             }
   705             @Override
   706             public Boolean visitMethodType(MethodType t, Type s) {
   707                 // isSameType for methods does not take thrown
   708                 // exceptions into account!
   709                 return hasSameArgs(t, s) && visit(t.getReturnType(), s.getReturnType());
   710             }
   712             @Override
   713             public Boolean visitPackageType(PackageType t, Type s) {
   714                 return t == s;
   715             }
   717             @Override
   718             public Boolean visitForAll(ForAll t, Type s) {
   719                 if (s.tag != FORALL)
   720                     return false;
   722                 ForAll forAll = (ForAll)s;
   723                 return hasSameBounds(t, forAll)
   724                     && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
   725             }
   727             @Override
   728             public Boolean visitUndetVar(UndetVar t, Type s) {
   729                 if (s.tag == WILDCARD)
   730                     // FIXME, this might be leftovers from before capture conversion
   731                     return false;
   733                 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN)
   734                     return true;
   736                 if (t.inst != null)
   737                     return visit(t.inst, s);
   739                 t.inst = fromUnknownFun.apply(s);
   740                 for (List<Type> l = t.lobounds; l.nonEmpty(); l = l.tail) {
   741                     if (!isSubtype(l.head, t.inst))
   742                         return false;
   743                 }
   744                 for (List<Type> l = t.hibounds; l.nonEmpty(); l = l.tail) {
   745                     if (!isSubtype(t.inst, l.head))
   746                         return false;
   747                 }
   748                 return true;
   749             }
   751             @Override
   752             public Boolean visitErrorType(ErrorType t, Type s) {
   753                 return true;
   754             }
   755         };
   756     // </editor-fold>
   758     // <editor-fold defaultstate="collapsed" desc="fromUnknownFun">
   759     /**
   760      * A mapping that turns all unknown types in this type to fresh
   761      * unknown variables.
   762      */
   763     public Mapping fromUnknownFun = new Mapping("fromUnknownFun") {
   764             public Type apply(Type t) {
   765                 if (t.tag == UNKNOWN) return new UndetVar(t);
   766                 else return t.map(this);
   767             }
   768         };
   769     // </editor-fold>
   771     // <editor-fold defaultstate="collapsed" desc="Contains Type">
   772     public boolean containedBy(Type t, Type s) {
   773         switch (t.tag) {
   774         case UNDETVAR:
   775             if (s.tag == WILDCARD) {
   776                 UndetVar undetvar = (UndetVar)t;
   777                 WildcardType wt = (WildcardType)s;
   778                 switch(wt.kind) {
   779                     case UNBOUND: //similar to ? extends Object
   780                     case EXTENDS: {
   781                         Type bound = upperBound(s);
   782                         // We should check the new upper bound against any of the
   783                         // undetvar's lower bounds.
   784                         for (Type t2 : undetvar.lobounds) {
   785                             if (!isSubtype(t2, bound))
   786                                 return false;
   787                         }
   788                         undetvar.hibounds = undetvar.hibounds.prepend(bound);
   789                         break;
   790                     }
   791                     case SUPER: {
   792                         Type bound = lowerBound(s);
   793                         // We should check the new lower bound against any of the
   794                         // undetvar's lower bounds.
   795                         for (Type t2 : undetvar.hibounds) {
   796                             if (!isSubtype(bound, t2))
   797                                 return false;
   798                         }
   799                         undetvar.lobounds = undetvar.lobounds.prepend(bound);
   800                         break;
   801                     }
   802                 }
   803                 return true;
   804             } else {
   805                 return isSameType(t, s);
   806             }
   807         case ERROR:
   808             return true;
   809         default:
   810             return containsType(s, t);
   811         }
   812     }
   814     boolean containsType(List<Type> ts, List<Type> ss) {
   815         while (ts.nonEmpty() && ss.nonEmpty()
   816                && containsType(ts.head, ss.head)) {
   817             ts = ts.tail;
   818             ss = ss.tail;
   819         }
   820         return ts.isEmpty() && ss.isEmpty();
   821     }
   823     /**
   824      * Check if t contains s.
   825      *
   826      * <p>T contains S if:
   827      *
   828      * <p>{@code L(T) <: L(S) && U(S) <: U(T)}
   829      *
   830      * <p>This relation is only used by ClassType.isSubtype(), that
   831      * is,
   832      *
   833      * <p>{@code C<S> <: C<T> if T contains S.}
   834      *
   835      * <p>Because of F-bounds, this relation can lead to infinite
   836      * recursion.  Thus we must somehow break that recursion.  Notice
   837      * that containsType() is only called from ClassType.isSubtype().
   838      * Since the arguments have already been checked against their
   839      * bounds, we know:
   840      *
   841      * <p>{@code U(S) <: U(T) if T is "super" bound (U(T) *is* the bound)}
   842      *
   843      * <p>{@code L(T) <: L(S) if T is "extends" bound (L(T) is bottom)}
   844      *
   845      * @param t a type
   846      * @param s a type
   847      */
   848     public boolean containsType(Type t, Type s) {
   849         return containsType.visit(t, s);
   850     }
   851     // where
   852         private TypeRelation containsType = new TypeRelation() {
   854             private Type U(Type t) {
   855                 while (t.tag == WILDCARD) {
   856                     WildcardType w = (WildcardType)t;
   857                     if (w.isSuperBound())
   858                         return w.bound == null ? syms.objectType : w.bound.bound;
   859                     else
   860                         t = w.type;
   861                 }
   862                 return t;
   863             }
   865             private Type L(Type t) {
   866                 while (t.tag == WILDCARD) {
   867                     WildcardType w = (WildcardType)t;
   868                     if (w.isExtendsBound())
   869                         return syms.botType;
   870                     else
   871                         t = w.type;
   872                 }
   873                 return t;
   874             }
   876             public Boolean visitType(Type t, Type s) {
   877                 if (s.tag >= firstPartialTag)
   878                     return containedBy(s, t);
   879                 else
   880                     return isSameType(t, s);
   881             }
   883 //            void debugContainsType(WildcardType t, Type s) {
   884 //                System.err.println();
   885 //                System.err.format(" does %s contain %s?%n", t, s);
   886 //                System.err.format(" %s U(%s) <: U(%s) %s = %s%n",
   887 //                                  upperBound(s), s, t, U(t),
   888 //                                  t.isSuperBound()
   889 //                                  || isSubtypeNoCapture(upperBound(s), U(t)));
   890 //                System.err.format(" %s L(%s) <: L(%s) %s = %s%n",
   891 //                                  L(t), t, s, lowerBound(s),
   892 //                                  t.isExtendsBound()
   893 //                                  || isSubtypeNoCapture(L(t), lowerBound(s)));
   894 //                System.err.println();
   895 //            }
   897             @Override
   898             public Boolean visitWildcardType(WildcardType t, Type s) {
   899                 if (s.tag >= firstPartialTag)
   900                     return containedBy(s, t);
   901                 else {
   902 //                    debugContainsType(t, s);
   903                     return isSameWildcard(t, s)
   904                         || isCaptureOf(s, t)
   905                         || ((t.isExtendsBound() || isSubtypeNoCapture(L(t), lowerBound(s))) &&
   906                             (t.isSuperBound() || isSubtypeNoCapture(upperBound(s), U(t))));
   907                 }
   908             }
   910             @Override
   911             public Boolean visitUndetVar(UndetVar t, Type s) {
   912                 if (s.tag != WILDCARD)
   913                     return isSameType(t, s);
   914                 else
   915                     return false;
   916             }
   918             @Override
   919             public Boolean visitErrorType(ErrorType t, Type s) {
   920                 return true;
   921             }
   922         };
   924     public boolean isCaptureOf(Type s, WildcardType t) {
   925         if (s.tag != TYPEVAR || !((TypeVar)s).isCaptured())
   926             return false;
   927         return isSameWildcard(t, ((CapturedType)s).wildcard);
   928     }
   930     public boolean isSameWildcard(WildcardType t, Type s) {
   931         if (s.tag != WILDCARD)
   932             return false;
   933         WildcardType w = (WildcardType)s;
   934         return w.kind == t.kind && w.type == t.type;
   935     }
   937     public boolean containsTypeEquivalent(List<Type> ts, List<Type> ss) {
   938         while (ts.nonEmpty() && ss.nonEmpty()
   939                && containsTypeEquivalent(ts.head, ss.head)) {
   940             ts = ts.tail;
   941             ss = ss.tail;
   942         }
   943         return ts.isEmpty() && ss.isEmpty();
   944     }
   945     // </editor-fold>
   947     // <editor-fold defaultstate="collapsed" desc="isCastable">
   948     public boolean isCastable(Type t, Type s) {
   949         return isCastable(t, s, Warner.noWarnings);
   950     }
   952     /**
   953      * Is t is castable to s?<br>
   954      * s is assumed to be an erased type.<br>
   955      * (not defined for Method and ForAll types).
   956      */
   957     public boolean isCastable(Type t, Type s, Warner warn) {
   958         if (t == s)
   959             return true;
   961         if (t.isPrimitive() != s.isPrimitive())
   962             return allowBoxing && (
   963                     isConvertible(t, s, warn)
   964                     || (allowObjectToPrimitiveCast &&
   965                         s.isPrimitive() &&
   966                         isSubtype(boxedClass(s).type, t)));
   967         if (warn != warnStack.head) {
   968             try {
   969                 warnStack = warnStack.prepend(warn);
   970                 checkUnsafeVarargsConversion(t, s, warn);
   971                 return isCastable.visit(t,s);
   972             } finally {
   973                 warnStack = warnStack.tail;
   974             }
   975         } else {
   976             return isCastable.visit(t,s);
   977         }
   978     }
   979     // where
   980         private TypeRelation isCastable = new TypeRelation() {
   982             public Boolean visitType(Type t, Type s) {
   983                 if (s.tag == ERROR)
   984                     return true;
   986                 switch (t.tag) {
   987                 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
   988                 case DOUBLE:
   989                     return s.tag <= DOUBLE;
   990                 case BOOLEAN:
   991                     return s.tag == BOOLEAN;
   992                 case VOID:
   993                     return false;
   994                 case BOT:
   995                     return isSubtype(t, s);
   996                 default:
   997                     throw new AssertionError();
   998                 }
   999             }
  1001             @Override
  1002             public Boolean visitWildcardType(WildcardType t, Type s) {
  1003                 return isCastable(upperBound(t), s, warnStack.head);
  1006             @Override
  1007             public Boolean visitClassType(ClassType t, Type s) {
  1008                 if (s.tag == ERROR || s.tag == BOT)
  1009                     return true;
  1011                 if (s.tag == TYPEVAR) {
  1012                     if (isCastable(t, s.getUpperBound(), Warner.noWarnings)) {
  1013                         warnStack.head.warn(LintCategory.UNCHECKED);
  1014                         return true;
  1015                     } else {
  1016                         return false;
  1020                 if (t.isCompound()) {
  1021                     Warner oldWarner = warnStack.head;
  1022                     warnStack.head = Warner.noWarnings;
  1023                     if (!visit(supertype(t), s))
  1024                         return false;
  1025                     for (Type intf : interfaces(t)) {
  1026                         if (!visit(intf, s))
  1027                             return false;
  1029                     if (warnStack.head.hasLint(LintCategory.UNCHECKED))
  1030                         oldWarner.warn(LintCategory.UNCHECKED);
  1031                     return true;
  1034                 if (s.isCompound()) {
  1035                     // call recursively to reuse the above code
  1036                     return visitClassType((ClassType)s, t);
  1039                 if (s.tag == CLASS || s.tag == ARRAY) {
  1040                     boolean upcast;
  1041                     if ((upcast = isSubtype(erasure(t), erasure(s)))
  1042                         || isSubtype(erasure(s), erasure(t))) {
  1043                         if (!upcast && s.tag == ARRAY) {
  1044                             if (!isReifiable(s))
  1045                                 warnStack.head.warn(LintCategory.UNCHECKED);
  1046                             return true;
  1047                         } else if (s.isRaw()) {
  1048                             return true;
  1049                         } else if (t.isRaw()) {
  1050                             if (!isUnbounded(s))
  1051                                 warnStack.head.warn(LintCategory.UNCHECKED);
  1052                             return true;
  1054                         // Assume |a| <: |b|
  1055                         final Type a = upcast ? t : s;
  1056                         final Type b = upcast ? s : t;
  1057                         final boolean HIGH = true;
  1058                         final boolean LOW = false;
  1059                         final boolean DONT_REWRITE_TYPEVARS = false;
  1060                         Type aHigh = rewriteQuantifiers(a, HIGH, DONT_REWRITE_TYPEVARS);
  1061                         Type aLow  = rewriteQuantifiers(a, LOW,  DONT_REWRITE_TYPEVARS);
  1062                         Type bHigh = rewriteQuantifiers(b, HIGH, DONT_REWRITE_TYPEVARS);
  1063                         Type bLow  = rewriteQuantifiers(b, LOW,  DONT_REWRITE_TYPEVARS);
  1064                         Type lowSub = asSub(bLow, aLow.tsym);
  1065                         Type highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
  1066                         if (highSub == null) {
  1067                             final boolean REWRITE_TYPEVARS = true;
  1068                             aHigh = rewriteQuantifiers(a, HIGH, REWRITE_TYPEVARS);
  1069                             aLow  = rewriteQuantifiers(a, LOW,  REWRITE_TYPEVARS);
  1070                             bHigh = rewriteQuantifiers(b, HIGH, REWRITE_TYPEVARS);
  1071                             bLow  = rewriteQuantifiers(b, LOW,  REWRITE_TYPEVARS);
  1072                             lowSub = asSub(bLow, aLow.tsym);
  1073                             highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
  1075                         if (highSub != null) {
  1076                             if (!(a.tsym == highSub.tsym && a.tsym == lowSub.tsym)) {
  1077                                 Assert.error(a.tsym + " != " + highSub.tsym + " != " + lowSub.tsym);
  1079                             if (!disjointTypes(aHigh.allparams(), highSub.allparams())
  1080                                 && !disjointTypes(aHigh.allparams(), lowSub.allparams())
  1081                                 && !disjointTypes(aLow.allparams(), highSub.allparams())
  1082                                 && !disjointTypes(aLow.allparams(), lowSub.allparams())) {
  1083                                 if (upcast ? giveWarning(a, b) :
  1084                                     giveWarning(b, a))
  1085                                     warnStack.head.warn(LintCategory.UNCHECKED);
  1086                                 return true;
  1089                         if (isReifiable(s))
  1090                             return isSubtypeUnchecked(a, b);
  1091                         else
  1092                             return isSubtypeUnchecked(a, b, warnStack.head);
  1095                     // Sidecast
  1096                     if (s.tag == CLASS) {
  1097                         if ((s.tsym.flags() & INTERFACE) != 0) {
  1098                             return ((t.tsym.flags() & FINAL) == 0)
  1099                                 ? sideCast(t, s, warnStack.head)
  1100                                 : sideCastFinal(t, s, warnStack.head);
  1101                         } else if ((t.tsym.flags() & INTERFACE) != 0) {
  1102                             return ((s.tsym.flags() & FINAL) == 0)
  1103                                 ? sideCast(t, s, warnStack.head)
  1104                                 : sideCastFinal(t, s, warnStack.head);
  1105                         } else {
  1106                             // unrelated class types
  1107                             return false;
  1111                 return false;
  1114             @Override
  1115             public Boolean visitArrayType(ArrayType t, Type s) {
  1116                 switch (s.tag) {
  1117                 case ERROR:
  1118                 case BOT:
  1119                     return true;
  1120                 case TYPEVAR:
  1121                     if (isCastable(s, t, Warner.noWarnings)) {
  1122                         warnStack.head.warn(LintCategory.UNCHECKED);
  1123                         return true;
  1124                     } else {
  1125                         return false;
  1127                 case CLASS:
  1128                     return isSubtype(t, s);
  1129                 case ARRAY:
  1130                     if (elemtype(t).tag <= lastBaseTag ||
  1131                             elemtype(s).tag <= lastBaseTag) {
  1132                         return elemtype(t).tag == elemtype(s).tag;
  1133                     } else {
  1134                         return visit(elemtype(t), elemtype(s));
  1136                 default:
  1137                     return false;
  1141             @Override
  1142             public Boolean visitTypeVar(TypeVar t, Type s) {
  1143                 switch (s.tag) {
  1144                 case ERROR:
  1145                 case BOT:
  1146                     return true;
  1147                 case TYPEVAR:
  1148                     if (isSubtype(t, s)) {
  1149                         return true;
  1150                     } else if (isCastable(t.bound, s, Warner.noWarnings)) {
  1151                         warnStack.head.warn(LintCategory.UNCHECKED);
  1152                         return true;
  1153                     } else {
  1154                         return false;
  1156                 default:
  1157                     return isCastable(t.bound, s, warnStack.head);
  1161             @Override
  1162             public Boolean visitErrorType(ErrorType t, Type s) {
  1163                 return true;
  1165         };
  1166     // </editor-fold>
  1168     // <editor-fold defaultstate="collapsed" desc="disjointTypes">
  1169     public boolean disjointTypes(List<Type> ts, List<Type> ss) {
  1170         while (ts.tail != null && ss.tail != null) {
  1171             if (disjointType(ts.head, ss.head)) return true;
  1172             ts = ts.tail;
  1173             ss = ss.tail;
  1175         return false;
  1178     /**
  1179      * Two types or wildcards are considered disjoint if it can be
  1180      * proven that no type can be contained in both. It is
  1181      * conservative in that it is allowed to say that two types are
  1182      * not disjoint, even though they actually are.
  1184      * The type C<X> is castable to C<Y> exactly if X and Y are not
  1185      * disjoint.
  1186      */
  1187     public boolean disjointType(Type t, Type s) {
  1188         return disjointType.visit(t, s);
  1190     // where
  1191         private TypeRelation disjointType = new TypeRelation() {
  1193             private Set<TypePair> cache = new HashSet<TypePair>();
  1195             public Boolean visitType(Type t, Type s) {
  1196                 if (s.tag == WILDCARD)
  1197                     return visit(s, t);
  1198                 else
  1199                     return notSoftSubtypeRecursive(t, s) || notSoftSubtypeRecursive(s, t);
  1202             private boolean isCastableRecursive(Type t, Type s) {
  1203                 TypePair pair = new TypePair(t, s);
  1204                 if (cache.add(pair)) {
  1205                     try {
  1206                         return Types.this.isCastable(t, s);
  1207                     } finally {
  1208                         cache.remove(pair);
  1210                 } else {
  1211                     return true;
  1215             private boolean notSoftSubtypeRecursive(Type t, Type s) {
  1216                 TypePair pair = new TypePair(t, s);
  1217                 if (cache.add(pair)) {
  1218                     try {
  1219                         return Types.this.notSoftSubtype(t, s);
  1220                     } finally {
  1221                         cache.remove(pair);
  1223                 } else {
  1224                     return false;
  1228             @Override
  1229             public Boolean visitWildcardType(WildcardType t, Type s) {
  1230                 if (t.isUnbound())
  1231                     return false;
  1233                 if (s.tag != WILDCARD) {
  1234                     if (t.isExtendsBound())
  1235                         return notSoftSubtypeRecursive(s, t.type);
  1236                     else // isSuperBound()
  1237                         return notSoftSubtypeRecursive(t.type, s);
  1240                 if (s.isUnbound())
  1241                     return false;
  1243                 if (t.isExtendsBound()) {
  1244                     if (s.isExtendsBound())
  1245                         return !isCastableRecursive(t.type, upperBound(s));
  1246                     else if (s.isSuperBound())
  1247                         return notSoftSubtypeRecursive(lowerBound(s), t.type);
  1248                 } else if (t.isSuperBound()) {
  1249                     if (s.isExtendsBound())
  1250                         return notSoftSubtypeRecursive(t.type, upperBound(s));
  1252                 return false;
  1254         };
  1255     // </editor-fold>
  1257     // <editor-fold defaultstate="collapsed" desc="lowerBoundArgtypes">
  1258     /**
  1259      * Returns the lower bounds of the formals of a method.
  1260      */
  1261     public List<Type> lowerBoundArgtypes(Type t) {
  1262         return map(t.getParameterTypes(), lowerBoundMapping);
  1264     private final Mapping lowerBoundMapping = new Mapping("lowerBound") {
  1265             public Type apply(Type t) {
  1266                 return lowerBound(t);
  1268         };
  1269     // </editor-fold>
  1271     // <editor-fold defaultstate="collapsed" desc="notSoftSubtype">
  1272     /**
  1273      * This relation answers the question: is impossible that
  1274      * something of type `t' can be a subtype of `s'? This is
  1275      * different from the question "is `t' not a subtype of `s'?"
  1276      * when type variables are involved: Integer is not a subtype of T
  1277      * where <T extends Number> but it is not true that Integer cannot
  1278      * possibly be a subtype of T.
  1279      */
  1280     public boolean notSoftSubtype(Type t, Type s) {
  1281         if (t == s) return false;
  1282         if (t.tag == TYPEVAR) {
  1283             TypeVar tv = (TypeVar) t;
  1284             return !isCastable(tv.bound,
  1285                                relaxBound(s),
  1286                                Warner.noWarnings);
  1288         if (s.tag != WILDCARD)
  1289             s = upperBound(s);
  1291         return !isSubtype(t, relaxBound(s));
  1294     private Type relaxBound(Type t) {
  1295         if (t.tag == TYPEVAR) {
  1296             while (t.tag == TYPEVAR)
  1297                 t = t.getUpperBound();
  1298             t = rewriteQuantifiers(t, true, true);
  1300         return t;
  1302     // </editor-fold>
  1304     // <editor-fold defaultstate="collapsed" desc="isReifiable">
  1305     public boolean isReifiable(Type t) {
  1306         return isReifiable.visit(t);
  1308     // where
  1309         private UnaryVisitor<Boolean> isReifiable = new UnaryVisitor<Boolean>() {
  1311             public Boolean visitType(Type t, Void ignored) {
  1312                 return true;
  1315             @Override
  1316             public Boolean visitClassType(ClassType t, Void ignored) {
  1317                 if (t.isCompound())
  1318                     return false;
  1319                 else {
  1320                     if (!t.isParameterized())
  1321                         return true;
  1323                     for (Type param : t.allparams()) {
  1324                         if (!param.isUnbound())
  1325                             return false;
  1327                     return true;
  1331             @Override
  1332             public Boolean visitArrayType(ArrayType t, Void ignored) {
  1333                 return visit(t.elemtype);
  1336             @Override
  1337             public Boolean visitTypeVar(TypeVar t, Void ignored) {
  1338                 return false;
  1340         };
  1341     // </editor-fold>
  1343     // <editor-fold defaultstate="collapsed" desc="Array Utils">
  1344     public boolean isArray(Type t) {
  1345         while (t.tag == WILDCARD)
  1346             t = upperBound(t);
  1347         return t.tag == ARRAY;
  1350     /**
  1351      * The element type of an array.
  1352      */
  1353     public Type elemtype(Type t) {
  1354         switch (t.tag) {
  1355         case WILDCARD:
  1356             return elemtype(upperBound(t));
  1357         case ARRAY:
  1358             return ((ArrayType)t).elemtype;
  1359         case FORALL:
  1360             return elemtype(((ForAll)t).qtype);
  1361         case ERROR:
  1362             return t;
  1363         default:
  1364             return null;
  1368     public Type elemtypeOrType(Type t) {
  1369         Type elemtype = elemtype(t);
  1370         return elemtype != null ?
  1371             elemtype :
  1372             t;
  1375     /**
  1376      * Mapping to take element type of an arraytype
  1377      */
  1378     private Mapping elemTypeFun = new Mapping ("elemTypeFun") {
  1379         public Type apply(Type t) { return elemtype(t); }
  1380     };
  1382     /**
  1383      * The number of dimensions of an array type.
  1384      */
  1385     public int dimensions(Type t) {
  1386         int result = 0;
  1387         while (t.tag == ARRAY) {
  1388             result++;
  1389             t = elemtype(t);
  1391         return result;
  1393     // </editor-fold>
  1395     // <editor-fold defaultstate="collapsed" desc="asSuper">
  1396     /**
  1397      * Return the (most specific) base type of t that starts with the
  1398      * given symbol.  If none exists, return null.
  1400      * @param t a type
  1401      * @param sym a symbol
  1402      */
  1403     public Type asSuper(Type t, Symbol sym) {
  1404         return asSuper.visit(t, sym);
  1406     // where
  1407         private SimpleVisitor<Type,Symbol> asSuper = new SimpleVisitor<Type,Symbol>() {
  1409             public Type visitType(Type t, Symbol sym) {
  1410                 return null;
  1413             @Override
  1414             public Type visitClassType(ClassType t, Symbol sym) {
  1415                 if (t.tsym == sym)
  1416                     return t;
  1418                 Type st = supertype(t);
  1419                 if (st.tag == CLASS || st.tag == TYPEVAR || st.tag == ERROR) {
  1420                     Type x = asSuper(st, sym);
  1421                     if (x != null)
  1422                         return x;
  1424                 if ((sym.flags() & INTERFACE) != 0) {
  1425                     for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
  1426                         Type x = asSuper(l.head, sym);
  1427                         if (x != null)
  1428                             return x;
  1431                 return null;
  1434             @Override
  1435             public Type visitArrayType(ArrayType t, Symbol sym) {
  1436                 return isSubtype(t, sym.type) ? sym.type : null;
  1439             @Override
  1440             public Type visitTypeVar(TypeVar t, Symbol sym) {
  1441                 if (t.tsym == sym)
  1442                     return t;
  1443                 else
  1444                     return asSuper(t.bound, sym);
  1447             @Override
  1448             public Type visitErrorType(ErrorType t, Symbol sym) {
  1449                 return t;
  1451         };
  1453     /**
  1454      * Return the base type of t or any of its outer types that starts
  1455      * with the given symbol.  If none exists, return null.
  1457      * @param t a type
  1458      * @param sym a symbol
  1459      */
  1460     public Type asOuterSuper(Type t, Symbol sym) {
  1461         switch (t.tag) {
  1462         case CLASS:
  1463             do {
  1464                 Type s = asSuper(t, sym);
  1465                 if (s != null) return s;
  1466                 t = t.getEnclosingType();
  1467             } while (t.tag == CLASS);
  1468             return null;
  1469         case ARRAY:
  1470             return isSubtype(t, sym.type) ? sym.type : null;
  1471         case TYPEVAR:
  1472             return asSuper(t, sym);
  1473         case ERROR:
  1474             return t;
  1475         default:
  1476             return null;
  1480     /**
  1481      * Return the base type of t or any of its enclosing types that
  1482      * starts with the given symbol.  If none exists, return null.
  1484      * @param t a type
  1485      * @param sym a symbol
  1486      */
  1487     public Type asEnclosingSuper(Type t, Symbol sym) {
  1488         switch (t.tag) {
  1489         case CLASS:
  1490             do {
  1491                 Type s = asSuper(t, sym);
  1492                 if (s != null) return s;
  1493                 Type outer = t.getEnclosingType();
  1494                 t = (outer.tag == CLASS) ? outer :
  1495                     (t.tsym.owner.enclClass() != null) ? t.tsym.owner.enclClass().type :
  1496                     Type.noType;
  1497             } while (t.tag == CLASS);
  1498             return null;
  1499         case ARRAY:
  1500             return isSubtype(t, sym.type) ? sym.type : null;
  1501         case TYPEVAR:
  1502             return asSuper(t, sym);
  1503         case ERROR:
  1504             return t;
  1505         default:
  1506             return null;
  1509     // </editor-fold>
  1511     // <editor-fold defaultstate="collapsed" desc="memberType">
  1512     /**
  1513      * The type of given symbol, seen as a member of t.
  1515      * @param t a type
  1516      * @param sym a symbol
  1517      */
  1518     public Type memberType(Type t, Symbol sym) {
  1519         return (sym.flags() & STATIC) != 0
  1520             ? sym.type
  1521             : memberType.visit(t, sym);
  1523     // where
  1524         private SimpleVisitor<Type,Symbol> memberType = new SimpleVisitor<Type,Symbol>() {
  1526             public Type visitType(Type t, Symbol sym) {
  1527                 return sym.type;
  1530             @Override
  1531             public Type visitWildcardType(WildcardType t, Symbol sym) {
  1532                 return memberType(upperBound(t), sym);
  1535             @Override
  1536             public Type visitClassType(ClassType t, Symbol sym) {
  1537                 Symbol owner = sym.owner;
  1538                 long flags = sym.flags();
  1539                 if (((flags & STATIC) == 0) && owner.type.isParameterized()) {
  1540                     Type base = asOuterSuper(t, owner);
  1541                     //if t is an intersection type T = CT & I1 & I2 ... & In
  1542                     //its supertypes CT, I1, ... In might contain wildcards
  1543                     //so we need to go through capture conversion
  1544                     base = t.isCompound() ? capture(base) : base;
  1545                     if (base != null) {
  1546                         List<Type> ownerParams = owner.type.allparams();
  1547                         List<Type> baseParams = base.allparams();
  1548                         if (ownerParams.nonEmpty()) {
  1549                             if (baseParams.isEmpty()) {
  1550                                 // then base is a raw type
  1551                                 return erasure(sym.type);
  1552                             } else {
  1553                                 return subst(sym.type, ownerParams, baseParams);
  1558                 return sym.type;
  1561             @Override
  1562             public Type visitTypeVar(TypeVar t, Symbol sym) {
  1563                 return memberType(t.bound, sym);
  1566             @Override
  1567             public Type visitErrorType(ErrorType t, Symbol sym) {
  1568                 return t;
  1570         };
  1571     // </editor-fold>
  1573     // <editor-fold defaultstate="collapsed" desc="isAssignable">
  1574     public boolean isAssignable(Type t, Type s) {
  1575         return isAssignable(t, s, Warner.noWarnings);
  1578     /**
  1579      * Is t assignable to s?<br>
  1580      * Equivalent to subtype except for constant values and raw
  1581      * types.<br>
  1582      * (not defined for Method and ForAll types)
  1583      */
  1584     public boolean isAssignable(Type t, Type s, Warner warn) {
  1585         if (t.tag == ERROR)
  1586             return true;
  1587         if (t.tag <= INT && t.constValue() != null) {
  1588             int value = ((Number)t.constValue()).intValue();
  1589             switch (s.tag) {
  1590             case BYTE:
  1591                 if (Byte.MIN_VALUE <= value && value <= Byte.MAX_VALUE)
  1592                     return true;
  1593                 break;
  1594             case CHAR:
  1595                 if (Character.MIN_VALUE <= value && value <= Character.MAX_VALUE)
  1596                     return true;
  1597                 break;
  1598             case SHORT:
  1599                 if (Short.MIN_VALUE <= value && value <= Short.MAX_VALUE)
  1600                     return true;
  1601                 break;
  1602             case INT:
  1603                 return true;
  1604             case CLASS:
  1605                 switch (unboxedType(s).tag) {
  1606                 case BYTE:
  1607                 case CHAR:
  1608                 case SHORT:
  1609                     return isAssignable(t, unboxedType(s), warn);
  1611                 break;
  1614         return isConvertible(t, s, warn);
  1616     // </editor-fold>
  1618     // <editor-fold defaultstate="collapsed" desc="erasure">
  1619     /**
  1620      * The erasure of t {@code |t|} -- the type that results when all
  1621      * type parameters in t are deleted.
  1622      */
  1623     public Type erasure(Type t) {
  1624         return erasure(t, false);
  1626     //where
  1627     private Type erasure(Type t, boolean recurse) {
  1628         if (t.tag <= lastBaseTag)
  1629             return t; /* fast special case */
  1630         else
  1631             return erasure.visit(t, recurse);
  1633     // where
  1634         private SimpleVisitor<Type, Boolean> erasure = new SimpleVisitor<Type, Boolean>() {
  1635             public Type visitType(Type t, Boolean recurse) {
  1636                 if (t.tag <= lastBaseTag)
  1637                     return t; /*fast special case*/
  1638                 else
  1639                     return t.map(recurse ? erasureRecFun : erasureFun);
  1642             @Override
  1643             public Type visitWildcardType(WildcardType t, Boolean recurse) {
  1644                 return erasure(upperBound(t), recurse);
  1647             @Override
  1648             public Type visitClassType(ClassType t, Boolean recurse) {
  1649                 Type erased = t.tsym.erasure(Types.this);
  1650                 if (recurse) {
  1651                     erased = new ErasedClassType(erased.getEnclosingType(),erased.tsym);
  1653                 return erased;
  1656             @Override
  1657             public Type visitTypeVar(TypeVar t, Boolean recurse) {
  1658                 return erasure(t.bound, recurse);
  1661             @Override
  1662             public Type visitErrorType(ErrorType t, Boolean recurse) {
  1663                 return t;
  1665         };
  1667     private Mapping erasureFun = new Mapping ("erasure") {
  1668             public Type apply(Type t) { return erasure(t); }
  1669         };
  1671     private Mapping erasureRecFun = new Mapping ("erasureRecursive") {
  1672         public Type apply(Type t) { return erasureRecursive(t); }
  1673     };
  1675     public List<Type> erasure(List<Type> ts) {
  1676         return Type.map(ts, erasureFun);
  1679     public Type erasureRecursive(Type t) {
  1680         return erasure(t, true);
  1683     public List<Type> erasureRecursive(List<Type> ts) {
  1684         return Type.map(ts, erasureRecFun);
  1686     // </editor-fold>
  1688     // <editor-fold defaultstate="collapsed" desc="makeCompoundType">
  1689     /**
  1690      * Make a compound type from non-empty list of types
  1692      * @param bounds            the types from which the compound type is formed
  1693      * @param supertype         is objectType if all bounds are interfaces,
  1694      *                          null otherwise.
  1695      */
  1696     public Type makeCompoundType(List<Type> bounds,
  1697                                  Type supertype) {
  1698         ClassSymbol bc =
  1699             new ClassSymbol(ABSTRACT|PUBLIC|SYNTHETIC|COMPOUND|ACYCLIC,
  1700                             Type.moreInfo
  1701                                 ? names.fromString(bounds.toString())
  1702                                 : names.empty,
  1703                             syms.noSymbol);
  1704         if (bounds.head.tag == TYPEVAR)
  1705             // error condition, recover
  1706                 bc.erasure_field = syms.objectType;
  1707             else
  1708                 bc.erasure_field = erasure(bounds.head);
  1709             bc.members_field = new Scope(bc);
  1710         ClassType bt = (ClassType)bc.type;
  1711         bt.allparams_field = List.nil();
  1712         if (supertype != null) {
  1713             bt.supertype_field = supertype;
  1714             bt.interfaces_field = bounds;
  1715         } else {
  1716             bt.supertype_field = bounds.head;
  1717             bt.interfaces_field = bounds.tail;
  1719         Assert.check(bt.supertype_field.tsym.completer != null
  1720                 || !bt.supertype_field.isInterface(),
  1721             bt.supertype_field);
  1722         return bt;
  1725     /**
  1726      * Same as {@link #makeCompoundType(List,Type)}, except that the
  1727      * second parameter is computed directly. Note that this might
  1728      * cause a symbol completion.  Hence, this version of
  1729      * makeCompoundType may not be called during a classfile read.
  1730      */
  1731     public Type makeCompoundType(List<Type> bounds) {
  1732         Type supertype = (bounds.head.tsym.flags() & INTERFACE) != 0 ?
  1733             supertype(bounds.head) : null;
  1734         return makeCompoundType(bounds, supertype);
  1737     /**
  1738      * A convenience wrapper for {@link #makeCompoundType(List)}; the
  1739      * arguments are converted to a list and passed to the other
  1740      * method.  Note that this might cause a symbol completion.
  1741      * Hence, this version of makeCompoundType may not be called
  1742      * during a classfile read.
  1743      */
  1744     public Type makeCompoundType(Type bound1, Type bound2) {
  1745         return makeCompoundType(List.of(bound1, bound2));
  1747     // </editor-fold>
  1749     // <editor-fold defaultstate="collapsed" desc="supertype">
  1750     public Type supertype(Type t) {
  1751         return supertype.visit(t);
  1753     // where
  1754         private UnaryVisitor<Type> supertype = new UnaryVisitor<Type>() {
  1756             public Type visitType(Type t, Void ignored) {
  1757                 // A note on wildcards: there is no good way to
  1758                 // determine a supertype for a super bounded wildcard.
  1759                 return null;
  1762             @Override
  1763             public Type visitClassType(ClassType t, Void ignored) {
  1764                 if (t.supertype_field == null) {
  1765                     Type supertype = ((ClassSymbol)t.tsym).getSuperclass();
  1766                     // An interface has no superclass; its supertype is Object.
  1767                     if (t.isInterface())
  1768                         supertype = ((ClassType)t.tsym.type).supertype_field;
  1769                     if (t.supertype_field == null) {
  1770                         List<Type> actuals = classBound(t).allparams();
  1771                         List<Type> formals = t.tsym.type.allparams();
  1772                         if (t.hasErasedSupertypes()) {
  1773                             t.supertype_field = erasureRecursive(supertype);
  1774                         } else if (formals.nonEmpty()) {
  1775                             t.supertype_field = subst(supertype, formals, actuals);
  1777                         else {
  1778                             t.supertype_field = supertype;
  1782                 return t.supertype_field;
  1785             /**
  1786              * The supertype is always a class type. If the type
  1787              * variable's bounds start with a class type, this is also
  1788              * the supertype.  Otherwise, the supertype is
  1789              * java.lang.Object.
  1790              */
  1791             @Override
  1792             public Type visitTypeVar(TypeVar t, Void ignored) {
  1793                 if (t.bound.tag == TYPEVAR ||
  1794                     (!t.bound.isCompound() && !t.bound.isInterface())) {
  1795                     return t.bound;
  1796                 } else {
  1797                     return supertype(t.bound);
  1801             @Override
  1802             public Type visitArrayType(ArrayType t, Void ignored) {
  1803                 if (t.elemtype.isPrimitive() || isSameType(t.elemtype, syms.objectType))
  1804                     return arraySuperType();
  1805                 else
  1806                     return new ArrayType(supertype(t.elemtype), t.tsym);
  1809             @Override
  1810             public Type visitErrorType(ErrorType t, Void ignored) {
  1811                 return t;
  1813         };
  1814     // </editor-fold>
  1816     // <editor-fold defaultstate="collapsed" desc="interfaces">
  1817     /**
  1818      * Return the interfaces implemented by this class.
  1819      */
  1820     public List<Type> interfaces(Type t) {
  1821         return interfaces.visit(t);
  1823     // where
  1824         private UnaryVisitor<List<Type>> interfaces = new UnaryVisitor<List<Type>>() {
  1826             public List<Type> visitType(Type t, Void ignored) {
  1827                 return List.nil();
  1830             @Override
  1831             public List<Type> visitClassType(ClassType t, Void ignored) {
  1832                 if (t.interfaces_field == null) {
  1833                     List<Type> interfaces = ((ClassSymbol)t.tsym).getInterfaces();
  1834                     if (t.interfaces_field == null) {
  1835                         // If t.interfaces_field is null, then t must
  1836                         // be a parameterized type (not to be confused
  1837                         // with a generic type declaration).
  1838                         // Terminology:
  1839                         //    Parameterized type: List<String>
  1840                         //    Generic type declaration: class List<E> { ... }
  1841                         // So t corresponds to List<String> and
  1842                         // t.tsym.type corresponds to List<E>.
  1843                         // The reason t must be parameterized type is
  1844                         // that completion will happen as a side
  1845                         // effect of calling
  1846                         // ClassSymbol.getInterfaces.  Since
  1847                         // t.interfaces_field is null after
  1848                         // completion, we can assume that t is not the
  1849                         // type of a class/interface declaration.
  1850                         Assert.check(t != t.tsym.type, t);
  1851                         List<Type> actuals = t.allparams();
  1852                         List<Type> formals = t.tsym.type.allparams();
  1853                         if (t.hasErasedSupertypes()) {
  1854                             t.interfaces_field = erasureRecursive(interfaces);
  1855                         } else if (formals.nonEmpty()) {
  1856                             t.interfaces_field =
  1857                                 upperBounds(subst(interfaces, formals, actuals));
  1859                         else {
  1860                             t.interfaces_field = interfaces;
  1864                 return t.interfaces_field;
  1867             @Override
  1868             public List<Type> visitTypeVar(TypeVar t, Void ignored) {
  1869                 if (t.bound.isCompound())
  1870                     return interfaces(t.bound);
  1872                 if (t.bound.isInterface())
  1873                     return List.of(t.bound);
  1875                 return List.nil();
  1877         };
  1878     // </editor-fold>
  1880     // <editor-fold defaultstate="collapsed" desc="isDerivedRaw">
  1881     Map<Type,Boolean> isDerivedRawCache = new HashMap<Type,Boolean>();
  1883     public boolean isDerivedRaw(Type t) {
  1884         Boolean result = isDerivedRawCache.get(t);
  1885         if (result == null) {
  1886             result = isDerivedRawInternal(t);
  1887             isDerivedRawCache.put(t, result);
  1889         return result;
  1892     public boolean isDerivedRawInternal(Type t) {
  1893         if (t.isErroneous())
  1894             return false;
  1895         return
  1896             t.isRaw() ||
  1897             supertype(t) != null && isDerivedRaw(supertype(t)) ||
  1898             isDerivedRaw(interfaces(t));
  1901     public boolean isDerivedRaw(List<Type> ts) {
  1902         List<Type> l = ts;
  1903         while (l.nonEmpty() && !isDerivedRaw(l.head)) l = l.tail;
  1904         return l.nonEmpty();
  1906     // </editor-fold>
  1908     // <editor-fold defaultstate="collapsed" desc="setBounds">
  1909     /**
  1910      * Set the bounds field of the given type variable to reflect a
  1911      * (possibly multiple) list of bounds.
  1912      * @param t                 a type variable
  1913      * @param bounds            the bounds, must be nonempty
  1914      * @param supertype         is objectType if all bounds are interfaces,
  1915      *                          null otherwise.
  1916      */
  1917     public void setBounds(TypeVar t, List<Type> bounds, Type supertype) {
  1918         if (bounds.tail.isEmpty())
  1919             t.bound = bounds.head;
  1920         else
  1921             t.bound = makeCompoundType(bounds, supertype);
  1922         t.rank_field = -1;
  1925     /**
  1926      * Same as {@link #setBounds(Type.TypeVar,List,Type)}, except that
  1927      * third parameter is computed directly, as follows: if all
  1928      * all bounds are interface types, the computed supertype is Object,
  1929      * otherwise the supertype is simply left null (in this case, the supertype
  1930      * is assumed to be the head of the bound list passed as second argument).
  1931      * Note that this check might cause a symbol completion. Hence, this version of
  1932      * setBounds may not be called during a classfile read.
  1933      */
  1934     public void setBounds(TypeVar t, List<Type> bounds) {
  1935         Type supertype = (bounds.head.tsym.flags() & INTERFACE) != 0 ?
  1936             syms.objectType : null;
  1937         setBounds(t, bounds, supertype);
  1938         t.rank_field = -1;
  1940     // </editor-fold>
  1942     // <editor-fold defaultstate="collapsed" desc="getBounds">
  1943     /**
  1944      * Return list of bounds of the given type variable.
  1945      */
  1946     public List<Type> getBounds(TypeVar t) {
  1947         if (t.bound.isErroneous() || !t.bound.isCompound())
  1948             return List.of(t.bound);
  1949         else if ((erasure(t).tsym.flags() & INTERFACE) == 0)
  1950             return interfaces(t).prepend(supertype(t));
  1951         else
  1952             // No superclass was given in bounds.
  1953             // In this case, supertype is Object, erasure is first interface.
  1954             return interfaces(t);
  1956     // </editor-fold>
  1958     // <editor-fold defaultstate="collapsed" desc="classBound">
  1959     /**
  1960      * If the given type is a (possibly selected) type variable,
  1961      * return the bounding class of this type, otherwise return the
  1962      * type itself.
  1963      */
  1964     public Type classBound(Type t) {
  1965         return classBound.visit(t);
  1967     // where
  1968         private UnaryVisitor<Type> classBound = new UnaryVisitor<Type>() {
  1970             public Type visitType(Type t, Void ignored) {
  1971                 return t;
  1974             @Override
  1975             public Type visitClassType(ClassType t, Void ignored) {
  1976                 Type outer1 = classBound(t.getEnclosingType());
  1977                 if (outer1 != t.getEnclosingType())
  1978                     return new ClassType(outer1, t.getTypeArguments(), t.tsym);
  1979                 else
  1980                     return t;
  1983             @Override
  1984             public Type visitTypeVar(TypeVar t, Void ignored) {
  1985                 return classBound(supertype(t));
  1988             @Override
  1989             public Type visitErrorType(ErrorType t, Void ignored) {
  1990                 return t;
  1992         };
  1993     // </editor-fold>
  1995     // <editor-fold defaultstate="collapsed" desc="sub signature / override equivalence">
  1996     /**
  1997      * Returns true iff the first signature is a <em>sub
  1998      * signature</em> of the other.  This is <b>not</b> an equivalence
  1999      * relation.
  2001      * @jls section 8.4.2.
  2002      * @see #overrideEquivalent(Type t, Type s)
  2003      * @param t first signature (possibly raw).
  2004      * @param s second signature (could be subjected to erasure).
  2005      * @return true if t is a sub signature of s.
  2006      */
  2007     public boolean isSubSignature(Type t, Type s) {
  2008         return isSubSignature(t, s, true);
  2011     public boolean isSubSignature(Type t, Type s, boolean strict) {
  2012         return hasSameArgs(t, s, strict) || hasSameArgs(t, erasure(s), strict);
  2015     /**
  2016      * Returns true iff these signatures are related by <em>override
  2017      * equivalence</em>.  This is the natural extension of
  2018      * isSubSignature to an equivalence relation.
  2020      * @jls section 8.4.2.
  2021      * @see #isSubSignature(Type t, Type s)
  2022      * @param t a signature (possible raw, could be subjected to
  2023      * erasure).
  2024      * @param s a signature (possible raw, could be subjected to
  2025      * erasure).
  2026      * @return true if either argument is a sub signature of the other.
  2027      */
  2028     public boolean overrideEquivalent(Type t, Type s) {
  2029         return hasSameArgs(t, s) ||
  2030             hasSameArgs(t, erasure(s)) || hasSameArgs(erasure(t), s);
  2033     // <editor-fold defaultstate="collapsed" desc="Determining method implementation in given site">
  2034     class ImplementationCache {
  2036         private WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>> _map =
  2037                 new WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>>();
  2039         class Entry {
  2040             final MethodSymbol cachedImpl;
  2041             final Filter<Symbol> implFilter;
  2042             final boolean checkResult;
  2043             final int prevMark;
  2045             public Entry(MethodSymbol cachedImpl,
  2046                     Filter<Symbol> scopeFilter,
  2047                     boolean checkResult,
  2048                     int prevMark) {
  2049                 this.cachedImpl = cachedImpl;
  2050                 this.implFilter = scopeFilter;
  2051                 this.checkResult = checkResult;
  2052                 this.prevMark = prevMark;
  2055             boolean matches(Filter<Symbol> scopeFilter, boolean checkResult, int mark) {
  2056                 return this.implFilter == scopeFilter &&
  2057                         this.checkResult == checkResult &&
  2058                         this.prevMark == mark;
  2062         MethodSymbol get(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
  2063             SoftReference<Map<TypeSymbol, Entry>> ref_cache = _map.get(ms);
  2064             Map<TypeSymbol, Entry> cache = ref_cache != null ? ref_cache.get() : null;
  2065             if (cache == null) {
  2066                 cache = new HashMap<TypeSymbol, Entry>();
  2067                 _map.put(ms, new SoftReference<Map<TypeSymbol, Entry>>(cache));
  2069             Entry e = cache.get(origin);
  2070             CompoundScope members = membersClosure(origin.type, true);
  2071             if (e == null ||
  2072                     !e.matches(implFilter, checkResult, members.getMark())) {
  2073                 MethodSymbol impl = implementationInternal(ms, origin, checkResult, implFilter);
  2074                 cache.put(origin, new Entry(impl, implFilter, checkResult, members.getMark()));
  2075                 return impl;
  2077             else {
  2078                 return e.cachedImpl;
  2082         private MethodSymbol implementationInternal(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
  2083             for (Type t = origin.type; t.tag == CLASS || t.tag == TYPEVAR; t = supertype(t)) {
  2084                 while (t.tag == TYPEVAR)
  2085                     t = t.getUpperBound();
  2086                 TypeSymbol c = t.tsym;
  2087                 for (Scope.Entry e = c.members().lookup(ms.name, implFilter);
  2088                      e.scope != null;
  2089                      e = e.next(implFilter)) {
  2090                     if (e.sym != null &&
  2091                              e.sym.overrides(ms, origin, Types.this, checkResult))
  2092                         return (MethodSymbol)e.sym;
  2095             return null;
  2099     private ImplementationCache implCache = new ImplementationCache();
  2101     public MethodSymbol implementation(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
  2102         return implCache.get(ms, origin, checkResult, implFilter);
  2104     // </editor-fold>
  2106     // <editor-fold defaultstate="collapsed" desc="compute transitive closure of all members in given site">
  2107     class MembersClosureCache extends SimpleVisitor<CompoundScope, Boolean> {
  2109         private WeakHashMap<TypeSymbol, Entry> _map =
  2110                 new WeakHashMap<TypeSymbol, Entry>();
  2112         class Entry {
  2113             final boolean skipInterfaces;
  2114             final CompoundScope compoundScope;
  2116             public Entry(boolean skipInterfaces, CompoundScope compoundScope) {
  2117                 this.skipInterfaces = skipInterfaces;
  2118                 this.compoundScope = compoundScope;
  2121             boolean matches(boolean skipInterfaces) {
  2122                 return this.skipInterfaces == skipInterfaces;
  2126         List<TypeSymbol> seenTypes = List.nil();
  2128         /** members closure visitor methods **/
  2130         public CompoundScope visitType(Type t, Boolean skipInterface) {
  2131             return null;
  2134         @Override
  2135         public CompoundScope visitClassType(ClassType t, Boolean skipInterface) {
  2136             if (seenTypes.contains(t.tsym)) {
  2137                 //this is possible when an interface is implemented in multiple
  2138                 //superclasses, or when a classs hierarchy is circular - in such
  2139                 //cases we don't need to recurse (empty scope is returned)
  2140                 return new CompoundScope(t.tsym);
  2142             try {
  2143                 seenTypes = seenTypes.prepend(t.tsym);
  2144                 ClassSymbol csym = (ClassSymbol)t.tsym;
  2145                 Entry e = _map.get(csym);
  2146                 if (e == null || !e.matches(skipInterface)) {
  2147                     CompoundScope membersClosure = new CompoundScope(csym);
  2148                     if (!skipInterface) {
  2149                         for (Type i : interfaces(t)) {
  2150                             membersClosure.addSubScope(visit(i, skipInterface));
  2153                     membersClosure.addSubScope(visit(supertype(t), skipInterface));
  2154                     membersClosure.addSubScope(csym.members());
  2155                     e = new Entry(skipInterface, membersClosure);
  2156                     _map.put(csym, e);
  2158                 return e.compoundScope;
  2160             finally {
  2161                 seenTypes = seenTypes.tail;
  2165         @Override
  2166         public CompoundScope visitTypeVar(TypeVar t, Boolean skipInterface) {
  2167             return visit(t.getUpperBound(), skipInterface);
  2171     private MembersClosureCache membersCache = new MembersClosureCache();
  2173     public CompoundScope membersClosure(Type site, boolean skipInterface) {
  2174         return membersCache.visit(site, skipInterface);
  2176     // </editor-fold>
  2178     /**
  2179      * Does t have the same arguments as s?  It is assumed that both
  2180      * types are (possibly polymorphic) method types.  Monomorphic
  2181      * method types "have the same arguments", if their argument lists
  2182      * are equal.  Polymorphic method types "have the same arguments",
  2183      * if they have the same arguments after renaming all type
  2184      * variables of one to corresponding type variables in the other,
  2185      * where correspondence is by position in the type parameter list.
  2186      */
  2187     public boolean hasSameArgs(Type t, Type s) {
  2188         return hasSameArgs(t, s, true);
  2191     public boolean hasSameArgs(Type t, Type s, boolean strict) {
  2192         return hasSameArgs(t, s, strict ? hasSameArgs_strict : hasSameArgs_nonstrict);
  2195     private boolean hasSameArgs(Type t, Type s, TypeRelation hasSameArgs) {
  2196         return hasSameArgs.visit(t, s);
  2198     // where
  2199         private class HasSameArgs extends TypeRelation {
  2201             boolean strict;
  2203             public HasSameArgs(boolean strict) {
  2204                 this.strict = strict;
  2207             public Boolean visitType(Type t, Type s) {
  2208                 throw new AssertionError();
  2211             @Override
  2212             public Boolean visitMethodType(MethodType t, Type s) {
  2213                 return s.tag == METHOD
  2214                     && containsTypeEquivalent(t.argtypes, s.getParameterTypes());
  2217             @Override
  2218             public Boolean visitForAll(ForAll t, Type s) {
  2219                 if (s.tag != FORALL)
  2220                     return strict ? false : visitMethodType(t.asMethodType(), s);
  2222                 ForAll forAll = (ForAll)s;
  2223                 return hasSameBounds(t, forAll)
  2224                     && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
  2227             @Override
  2228             public Boolean visitErrorType(ErrorType t, Type s) {
  2229                 return false;
  2231         };
  2233         TypeRelation hasSameArgs_strict = new HasSameArgs(true);
  2234         TypeRelation hasSameArgs_nonstrict = new HasSameArgs(false);
  2236     // </editor-fold>
  2238     // <editor-fold defaultstate="collapsed" desc="subst">
  2239     public List<Type> subst(List<Type> ts,
  2240                             List<Type> from,
  2241                             List<Type> to) {
  2242         return new Subst(from, to).subst(ts);
  2245     /**
  2246      * Substitute all occurrences of a type in `from' with the
  2247      * corresponding type in `to' in 't'. Match lists `from' and `to'
  2248      * from the right: If lists have different length, discard leading
  2249      * elements of the longer list.
  2250      */
  2251     public Type subst(Type t, List<Type> from, List<Type> to) {
  2252         return new Subst(from, to).subst(t);
  2255     private class Subst extends UnaryVisitor<Type> {
  2256         List<Type> from;
  2257         List<Type> to;
  2259         public Subst(List<Type> from, List<Type> to) {
  2260             int fromLength = from.length();
  2261             int toLength = to.length();
  2262             while (fromLength > toLength) {
  2263                 fromLength--;
  2264                 from = from.tail;
  2266             while (fromLength < toLength) {
  2267                 toLength--;
  2268                 to = to.tail;
  2270             this.from = from;
  2271             this.to = to;
  2274         Type subst(Type t) {
  2275             if (from.tail == null)
  2276                 return t;
  2277             else
  2278                 return visit(t);
  2281         List<Type> subst(List<Type> ts) {
  2282             if (from.tail == null)
  2283                 return ts;
  2284             boolean wild = false;
  2285             if (ts.nonEmpty() && from.nonEmpty()) {
  2286                 Type head1 = subst(ts.head);
  2287                 List<Type> tail1 = subst(ts.tail);
  2288                 if (head1 != ts.head || tail1 != ts.tail)
  2289                     return tail1.prepend(head1);
  2291             return ts;
  2294         public Type visitType(Type t, Void ignored) {
  2295             return t;
  2298         @Override
  2299         public Type visitMethodType(MethodType t, Void ignored) {
  2300             List<Type> argtypes = subst(t.argtypes);
  2301             Type restype = subst(t.restype);
  2302             List<Type> thrown = subst(t.thrown);
  2303             if (argtypes == t.argtypes &&
  2304                 restype == t.restype &&
  2305                 thrown == t.thrown)
  2306                 return t;
  2307             else
  2308                 return new MethodType(argtypes, restype, thrown, t.tsym);
  2311         @Override
  2312         public Type visitTypeVar(TypeVar t, Void ignored) {
  2313             for (List<Type> from = this.from, to = this.to;
  2314                  from.nonEmpty();
  2315                  from = from.tail, to = to.tail) {
  2316                 if (t == from.head) {
  2317                     return to.head.withTypeVar(t);
  2320             return t;
  2323         @Override
  2324         public Type visitClassType(ClassType t, Void ignored) {
  2325             if (!t.isCompound()) {
  2326                 List<Type> typarams = t.getTypeArguments();
  2327                 List<Type> typarams1 = subst(typarams);
  2328                 Type outer = t.getEnclosingType();
  2329                 Type outer1 = subst(outer);
  2330                 if (typarams1 == typarams && outer1 == outer)
  2331                     return t;
  2332                 else
  2333                     return new ClassType(outer1, typarams1, t.tsym);
  2334             } else {
  2335                 Type st = subst(supertype(t));
  2336                 List<Type> is = upperBounds(subst(interfaces(t)));
  2337                 if (st == supertype(t) && is == interfaces(t))
  2338                     return t;
  2339                 else
  2340                     return makeCompoundType(is.prepend(st));
  2344         @Override
  2345         public Type visitWildcardType(WildcardType t, Void ignored) {
  2346             Type bound = t.type;
  2347             if (t.kind != BoundKind.UNBOUND)
  2348                 bound = subst(bound);
  2349             if (bound == t.type) {
  2350                 return t;
  2351             } else {
  2352                 if (t.isExtendsBound() && bound.isExtendsBound())
  2353                     bound = upperBound(bound);
  2354                 return new WildcardType(bound, t.kind, syms.boundClass, t.bound);
  2358         @Override
  2359         public Type visitArrayType(ArrayType t, Void ignored) {
  2360             Type elemtype = subst(t.elemtype);
  2361             if (elemtype == t.elemtype)
  2362                 return t;
  2363             else
  2364                 return new ArrayType(upperBound(elemtype), t.tsym);
  2367         @Override
  2368         public Type visitForAll(ForAll t, Void ignored) {
  2369             if (Type.containsAny(to, t.tvars)) {
  2370                 //perform alpha-renaming of free-variables in 't'
  2371                 //if 'to' types contain variables that are free in 't'
  2372                 List<Type> freevars = newInstances(t.tvars);
  2373                 t = new ForAll(freevars,
  2374                         Types.this.subst(t.qtype, t.tvars, freevars));
  2376             List<Type> tvars1 = substBounds(t.tvars, from, to);
  2377             Type qtype1 = subst(t.qtype);
  2378             if (tvars1 == t.tvars && qtype1 == t.qtype) {
  2379                 return t;
  2380             } else if (tvars1 == t.tvars) {
  2381                 return new ForAll(tvars1, qtype1);
  2382             } else {
  2383                 return new ForAll(tvars1, Types.this.subst(qtype1, t.tvars, tvars1));
  2387         @Override
  2388         public Type visitErrorType(ErrorType t, Void ignored) {
  2389             return t;
  2393     public List<Type> substBounds(List<Type> tvars,
  2394                                   List<Type> from,
  2395                                   List<Type> to) {
  2396         if (tvars.isEmpty())
  2397             return tvars;
  2398         ListBuffer<Type> newBoundsBuf = lb();
  2399         boolean changed = false;
  2400         // calculate new bounds
  2401         for (Type t : tvars) {
  2402             TypeVar tv = (TypeVar) t;
  2403             Type bound = subst(tv.bound, from, to);
  2404             if (bound != tv.bound)
  2405                 changed = true;
  2406             newBoundsBuf.append(bound);
  2408         if (!changed)
  2409             return tvars;
  2410         ListBuffer<Type> newTvars = lb();
  2411         // create new type variables without bounds
  2412         for (Type t : tvars) {
  2413             newTvars.append(new TypeVar(t.tsym, null, syms.botType));
  2415         // the new bounds should use the new type variables in place
  2416         // of the old
  2417         List<Type> newBounds = newBoundsBuf.toList();
  2418         from = tvars;
  2419         to = newTvars.toList();
  2420         for (; !newBounds.isEmpty(); newBounds = newBounds.tail) {
  2421             newBounds.head = subst(newBounds.head, from, to);
  2423         newBounds = newBoundsBuf.toList();
  2424         // set the bounds of new type variables to the new bounds
  2425         for (Type t : newTvars.toList()) {
  2426             TypeVar tv = (TypeVar) t;
  2427             tv.bound = newBounds.head;
  2428             newBounds = newBounds.tail;
  2430         return newTvars.toList();
  2433     public TypeVar substBound(TypeVar t, List<Type> from, List<Type> to) {
  2434         Type bound1 = subst(t.bound, from, to);
  2435         if (bound1 == t.bound)
  2436             return t;
  2437         else {
  2438             // create new type variable without bounds
  2439             TypeVar tv = new TypeVar(t.tsym, null, syms.botType);
  2440             // the new bound should use the new type variable in place
  2441             // of the old
  2442             tv.bound = subst(bound1, List.<Type>of(t), List.<Type>of(tv));
  2443             return tv;
  2446     // </editor-fold>
  2448     // <editor-fold defaultstate="collapsed" desc="hasSameBounds">
  2449     /**
  2450      * Does t have the same bounds for quantified variables as s?
  2451      */
  2452     boolean hasSameBounds(ForAll t, ForAll s) {
  2453         List<Type> l1 = t.tvars;
  2454         List<Type> l2 = s.tvars;
  2455         while (l1.nonEmpty() && l2.nonEmpty() &&
  2456                isSameType(l1.head.getUpperBound(),
  2457                           subst(l2.head.getUpperBound(),
  2458                                 s.tvars,
  2459                                 t.tvars))) {
  2460             l1 = l1.tail;
  2461             l2 = l2.tail;
  2463         return l1.isEmpty() && l2.isEmpty();
  2465     // </editor-fold>
  2467     // <editor-fold defaultstate="collapsed" desc="newInstances">
  2468     /** Create new vector of type variables from list of variables
  2469      *  changing all recursive bounds from old to new list.
  2470      */
  2471     public List<Type> newInstances(List<Type> tvars) {
  2472         List<Type> tvars1 = Type.map(tvars, newInstanceFun);
  2473         for (List<Type> l = tvars1; l.nonEmpty(); l = l.tail) {
  2474             TypeVar tv = (TypeVar) l.head;
  2475             tv.bound = subst(tv.bound, tvars, tvars1);
  2477         return tvars1;
  2479     static private Mapping newInstanceFun = new Mapping("newInstanceFun") {
  2480             public Type apply(Type t) { return new TypeVar(t.tsym, t.getUpperBound(), t.getLowerBound()); }
  2481         };
  2482     // </editor-fold>
  2484     public Type createMethodTypeWithParameters(Type original, List<Type> newParams) {
  2485         return original.accept(methodWithParameters, newParams);
  2487     // where
  2488         private final MapVisitor<List<Type>> methodWithParameters = new MapVisitor<List<Type>>() {
  2489             public Type visitType(Type t, List<Type> newParams) {
  2490                 throw new IllegalArgumentException("Not a method type: " + t);
  2492             public Type visitMethodType(MethodType t, List<Type> newParams) {
  2493                 return new MethodType(newParams, t.restype, t.thrown, t.tsym);
  2495             public Type visitForAll(ForAll t, List<Type> newParams) {
  2496                 return new ForAll(t.tvars, t.qtype.accept(this, newParams));
  2498         };
  2500     public Type createMethodTypeWithThrown(Type original, List<Type> newThrown) {
  2501         return original.accept(methodWithThrown, newThrown);
  2503     // where
  2504         private final MapVisitor<List<Type>> methodWithThrown = new MapVisitor<List<Type>>() {
  2505             public Type visitType(Type t, List<Type> newThrown) {
  2506                 throw new IllegalArgumentException("Not a method type: " + t);
  2508             public Type visitMethodType(MethodType t, List<Type> newThrown) {
  2509                 return new MethodType(t.argtypes, t.restype, newThrown, t.tsym);
  2511             public Type visitForAll(ForAll t, List<Type> newThrown) {
  2512                 return new ForAll(t.tvars, t.qtype.accept(this, newThrown));
  2514         };
  2516     public Type createMethodTypeWithReturn(Type original, Type newReturn) {
  2517         return original.accept(methodWithReturn, newReturn);
  2519     // where
  2520         private final MapVisitor<Type> methodWithReturn = new MapVisitor<Type>() {
  2521             public Type visitType(Type t, Type newReturn) {
  2522                 throw new IllegalArgumentException("Not a method type: " + t);
  2524             public Type visitMethodType(MethodType t, Type newReturn) {
  2525                 return new MethodType(t.argtypes, newReturn, t.thrown, t.tsym);
  2527             public Type visitForAll(ForAll t, Type newReturn) {
  2528                 return new ForAll(t.tvars, t.qtype.accept(this, newReturn));
  2530         };
  2532     // <editor-fold defaultstate="collapsed" desc="createErrorType">
  2533     public Type createErrorType(Type originalType) {
  2534         return new ErrorType(originalType, syms.errSymbol);
  2537     public Type createErrorType(ClassSymbol c, Type originalType) {
  2538         return new ErrorType(c, originalType);
  2541     public Type createErrorType(Name name, TypeSymbol container, Type originalType) {
  2542         return new ErrorType(name, container, originalType);
  2544     // </editor-fold>
  2546     // <editor-fold defaultstate="collapsed" desc="rank">
  2547     /**
  2548      * The rank of a class is the length of the longest path between
  2549      * the class and java.lang.Object in the class inheritance
  2550      * graph. Undefined for all but reference types.
  2551      */
  2552     public int rank(Type t) {
  2553         switch(t.tag) {
  2554         case CLASS: {
  2555             ClassType cls = (ClassType)t;
  2556             if (cls.rank_field < 0) {
  2557                 Name fullname = cls.tsym.getQualifiedName();
  2558                 if (fullname == names.java_lang_Object)
  2559                     cls.rank_field = 0;
  2560                 else {
  2561                     int r = rank(supertype(cls));
  2562                     for (List<Type> l = interfaces(cls);
  2563                          l.nonEmpty();
  2564                          l = l.tail) {
  2565                         if (rank(l.head) > r)
  2566                             r = rank(l.head);
  2568                     cls.rank_field = r + 1;
  2571             return cls.rank_field;
  2573         case TYPEVAR: {
  2574             TypeVar tvar = (TypeVar)t;
  2575             if (tvar.rank_field < 0) {
  2576                 int r = rank(supertype(tvar));
  2577                 for (List<Type> l = interfaces(tvar);
  2578                      l.nonEmpty();
  2579                      l = l.tail) {
  2580                     if (rank(l.head) > r) r = rank(l.head);
  2582                 tvar.rank_field = r + 1;
  2584             return tvar.rank_field;
  2586         case ERROR:
  2587             return 0;
  2588         default:
  2589             throw new AssertionError();
  2592     // </editor-fold>
  2594     /**
  2595      * Helper method for generating a string representation of a given type
  2596      * accordingly to a given locale
  2597      */
  2598     public String toString(Type t, Locale locale) {
  2599         return Printer.createStandardPrinter(messages).visit(t, locale);
  2602     /**
  2603      * Helper method for generating a string representation of a given type
  2604      * accordingly to a given locale
  2605      */
  2606     public String toString(Symbol t, Locale locale) {
  2607         return Printer.createStandardPrinter(messages).visit(t, locale);
  2610     // <editor-fold defaultstate="collapsed" desc="toString">
  2611     /**
  2612      * This toString is slightly more descriptive than the one on Type.
  2614      * @deprecated Types.toString(Type t, Locale l) provides better support
  2615      * for localization
  2616      */
  2617     @Deprecated
  2618     public String toString(Type t) {
  2619         if (t.tag == FORALL) {
  2620             ForAll forAll = (ForAll)t;
  2621             return typaramsString(forAll.tvars) + forAll.qtype;
  2623         return "" + t;
  2625     // where
  2626         private String typaramsString(List<Type> tvars) {
  2627             StringBuilder s = new StringBuilder();
  2628             s.append('<');
  2629             boolean first = true;
  2630             for (Type t : tvars) {
  2631                 if (!first) s.append(", ");
  2632                 first = false;
  2633                 appendTyparamString(((TypeVar)t), s);
  2635             s.append('>');
  2636             return s.toString();
  2638         private void appendTyparamString(TypeVar t, StringBuilder buf) {
  2639             buf.append(t);
  2640             if (t.bound == null ||
  2641                 t.bound.tsym.getQualifiedName() == names.java_lang_Object)
  2642                 return;
  2643             buf.append(" extends "); // Java syntax; no need for i18n
  2644             Type bound = t.bound;
  2645             if (!bound.isCompound()) {
  2646                 buf.append(bound);
  2647             } else if ((erasure(t).tsym.flags() & INTERFACE) == 0) {
  2648                 buf.append(supertype(t));
  2649                 for (Type intf : interfaces(t)) {
  2650                     buf.append('&');
  2651                     buf.append(intf);
  2653             } else {
  2654                 // No superclass was given in bounds.
  2655                 // In this case, supertype is Object, erasure is first interface.
  2656                 boolean first = true;
  2657                 for (Type intf : interfaces(t)) {
  2658                     if (!first) buf.append('&');
  2659                     first = false;
  2660                     buf.append(intf);
  2664     // </editor-fold>
  2666     // <editor-fold defaultstate="collapsed" desc="Determining least upper bounds of types">
  2667     /**
  2668      * A cache for closures.
  2670      * <p>A closure is a list of all the supertypes and interfaces of
  2671      * a class or interface type, ordered by ClassSymbol.precedes
  2672      * (that is, subclasses come first, arbitrary but fixed
  2673      * otherwise).
  2674      */
  2675     private Map<Type,List<Type>> closureCache = new HashMap<Type,List<Type>>();
  2677     /**
  2678      * Returns the closure of a class or interface type.
  2679      */
  2680     public List<Type> closure(Type t) {
  2681         List<Type> cl = closureCache.get(t);
  2682         if (cl == null) {
  2683             Type st = supertype(t);
  2684             if (!t.isCompound()) {
  2685                 if (st.tag == CLASS) {
  2686                     cl = insert(closure(st), t);
  2687                 } else if (st.tag == TYPEVAR) {
  2688                     cl = closure(st).prepend(t);
  2689                 } else {
  2690                     cl = List.of(t);
  2692             } else {
  2693                 cl = closure(supertype(t));
  2695             for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail)
  2696                 cl = union(cl, closure(l.head));
  2697             closureCache.put(t, cl);
  2699         return cl;
  2702     /**
  2703      * Insert a type in a closure
  2704      */
  2705     public List<Type> insert(List<Type> cl, Type t) {
  2706         if (cl.isEmpty() || t.tsym.precedes(cl.head.tsym, this)) {
  2707             return cl.prepend(t);
  2708         } else if (cl.head.tsym.precedes(t.tsym, this)) {
  2709             return insert(cl.tail, t).prepend(cl.head);
  2710         } else {
  2711             return cl;
  2715     /**
  2716      * Form the union of two closures
  2717      */
  2718     public List<Type> union(List<Type> cl1, List<Type> cl2) {
  2719         if (cl1.isEmpty()) {
  2720             return cl2;
  2721         } else if (cl2.isEmpty()) {
  2722             return cl1;
  2723         } else if (cl1.head.tsym.precedes(cl2.head.tsym, this)) {
  2724             return union(cl1.tail, cl2).prepend(cl1.head);
  2725         } else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) {
  2726             return union(cl1, cl2.tail).prepend(cl2.head);
  2727         } else {
  2728             return union(cl1.tail, cl2.tail).prepend(cl1.head);
  2732     /**
  2733      * Intersect two closures
  2734      */
  2735     public List<Type> intersect(List<Type> cl1, List<Type> cl2) {
  2736         if (cl1 == cl2)
  2737             return cl1;
  2738         if (cl1.isEmpty() || cl2.isEmpty())
  2739             return List.nil();
  2740         if (cl1.head.tsym.precedes(cl2.head.tsym, this))
  2741             return intersect(cl1.tail, cl2);
  2742         if (cl2.head.tsym.precedes(cl1.head.tsym, this))
  2743             return intersect(cl1, cl2.tail);
  2744         if (isSameType(cl1.head, cl2.head))
  2745             return intersect(cl1.tail, cl2.tail).prepend(cl1.head);
  2746         if (cl1.head.tsym == cl2.head.tsym &&
  2747             cl1.head.tag == CLASS && cl2.head.tag == CLASS) {
  2748             if (cl1.head.isParameterized() && cl2.head.isParameterized()) {
  2749                 Type merge = merge(cl1.head,cl2.head);
  2750                 return intersect(cl1.tail, cl2.tail).prepend(merge);
  2752             if (cl1.head.isRaw() || cl2.head.isRaw())
  2753                 return intersect(cl1.tail, cl2.tail).prepend(erasure(cl1.head));
  2755         return intersect(cl1.tail, cl2.tail);
  2757     // where
  2758         class TypePair {
  2759             final Type t1;
  2760             final Type t2;
  2761             TypePair(Type t1, Type t2) {
  2762                 this.t1 = t1;
  2763                 this.t2 = t2;
  2765             @Override
  2766             public int hashCode() {
  2767                 return 127 * Types.hashCode(t1) + Types.hashCode(t2);
  2769             @Override
  2770             public boolean equals(Object obj) {
  2771                 if (!(obj instanceof TypePair))
  2772                     return false;
  2773                 TypePair typePair = (TypePair)obj;
  2774                 return isSameType(t1, typePair.t1)
  2775                     && isSameType(t2, typePair.t2);
  2778         Set<TypePair> mergeCache = new HashSet<TypePair>();
  2779         private Type merge(Type c1, Type c2) {
  2780             ClassType class1 = (ClassType) c1;
  2781             List<Type> act1 = class1.getTypeArguments();
  2782             ClassType class2 = (ClassType) c2;
  2783             List<Type> act2 = class2.getTypeArguments();
  2784             ListBuffer<Type> merged = new ListBuffer<Type>();
  2785             List<Type> typarams = class1.tsym.type.getTypeArguments();
  2787             while (act1.nonEmpty() && act2.nonEmpty() && typarams.nonEmpty()) {
  2788                 if (containsType(act1.head, act2.head)) {
  2789                     merged.append(act1.head);
  2790                 } else if (containsType(act2.head, act1.head)) {
  2791                     merged.append(act2.head);
  2792                 } else {
  2793                     TypePair pair = new TypePair(c1, c2);
  2794                     Type m;
  2795                     if (mergeCache.add(pair)) {
  2796                         m = new WildcardType(lub(upperBound(act1.head),
  2797                                                  upperBound(act2.head)),
  2798                                              BoundKind.EXTENDS,
  2799                                              syms.boundClass);
  2800                         mergeCache.remove(pair);
  2801                     } else {
  2802                         m = new WildcardType(syms.objectType,
  2803                                              BoundKind.UNBOUND,
  2804                                              syms.boundClass);
  2806                     merged.append(m.withTypeVar(typarams.head));
  2808                 act1 = act1.tail;
  2809                 act2 = act2.tail;
  2810                 typarams = typarams.tail;
  2812             Assert.check(act1.isEmpty() && act2.isEmpty() && typarams.isEmpty());
  2813             return new ClassType(class1.getEnclosingType(), merged.toList(), class1.tsym);
  2816     /**
  2817      * Return the minimum type of a closure, a compound type if no
  2818      * unique minimum exists.
  2819      */
  2820     private Type compoundMin(List<Type> cl) {
  2821         if (cl.isEmpty()) return syms.objectType;
  2822         List<Type> compound = closureMin(cl);
  2823         if (compound.isEmpty())
  2824             return null;
  2825         else if (compound.tail.isEmpty())
  2826             return compound.head;
  2827         else
  2828             return makeCompoundType(compound);
  2831     /**
  2832      * Return the minimum types of a closure, suitable for computing
  2833      * compoundMin or glb.
  2834      */
  2835     private List<Type> closureMin(List<Type> cl) {
  2836         ListBuffer<Type> classes = lb();
  2837         ListBuffer<Type> interfaces = lb();
  2838         while (!cl.isEmpty()) {
  2839             Type current = cl.head;
  2840             if (current.isInterface())
  2841                 interfaces.append(current);
  2842             else
  2843                 classes.append(current);
  2844             ListBuffer<Type> candidates = lb();
  2845             for (Type t : cl.tail) {
  2846                 if (!isSubtypeNoCapture(current, t))
  2847                     candidates.append(t);
  2849             cl = candidates.toList();
  2851         return classes.appendList(interfaces).toList();
  2854     /**
  2855      * Return the least upper bound of pair of types.  if the lub does
  2856      * not exist return null.
  2857      */
  2858     public Type lub(Type t1, Type t2) {
  2859         return lub(List.of(t1, t2));
  2862     /**
  2863      * Return the least upper bound (lub) of set of types.  If the lub
  2864      * does not exist return the type of null (bottom).
  2865      */
  2866     public Type lub(List<Type> ts) {
  2867         final int ARRAY_BOUND = 1;
  2868         final int CLASS_BOUND = 2;
  2869         int boundkind = 0;
  2870         for (Type t : ts) {
  2871             switch (t.tag) {
  2872             case CLASS:
  2873                 boundkind |= CLASS_BOUND;
  2874                 break;
  2875             case ARRAY:
  2876                 boundkind |= ARRAY_BOUND;
  2877                 break;
  2878             case  TYPEVAR:
  2879                 do {
  2880                     t = t.getUpperBound();
  2881                 } while (t.tag == TYPEVAR);
  2882                 if (t.tag == ARRAY) {
  2883                     boundkind |= ARRAY_BOUND;
  2884                 } else {
  2885                     boundkind |= CLASS_BOUND;
  2887                 break;
  2888             default:
  2889                 if (t.isPrimitive())
  2890                     return syms.errType;
  2893         switch (boundkind) {
  2894         case 0:
  2895             return syms.botType;
  2897         case ARRAY_BOUND:
  2898             // calculate lub(A[], B[])
  2899             List<Type> elements = Type.map(ts, elemTypeFun);
  2900             for (Type t : elements) {
  2901                 if (t.isPrimitive()) {
  2902                     // if a primitive type is found, then return
  2903                     // arraySuperType unless all the types are the
  2904                     // same
  2905                     Type first = ts.head;
  2906                     for (Type s : ts.tail) {
  2907                         if (!isSameType(first, s)) {
  2908                              // lub(int[], B[]) is Cloneable & Serializable
  2909                             return arraySuperType();
  2912                     // all the array types are the same, return one
  2913                     // lub(int[], int[]) is int[]
  2914                     return first;
  2917             // lub(A[], B[]) is lub(A, B)[]
  2918             return new ArrayType(lub(elements), syms.arrayClass);
  2920         case CLASS_BOUND:
  2921             // calculate lub(A, B)
  2922             while (ts.head.tag != CLASS && ts.head.tag != TYPEVAR)
  2923                 ts = ts.tail;
  2924             Assert.check(!ts.isEmpty());
  2925             //step 1 - compute erased candidate set (EC)
  2926             List<Type> cl = erasedSupertypes(ts.head);
  2927             for (Type t : ts.tail) {
  2928                 if (t.tag == CLASS || t.tag == TYPEVAR)
  2929                     cl = intersect(cl, erasedSupertypes(t));
  2931             //step 2 - compute minimal erased candidate set (MEC)
  2932             List<Type> mec = closureMin(cl);
  2933             //step 3 - for each element G in MEC, compute lci(Inv(G))
  2934             List<Type> candidates = List.nil();
  2935             for (Type erasedSupertype : mec) {
  2936                 List<Type> lci = List.of(asSuper(ts.head, erasedSupertype.tsym));
  2937                 for (Type t : ts) {
  2938                     lci = intersect(lci, List.of(asSuper(t, erasedSupertype.tsym)));
  2940                 candidates = candidates.appendList(lci);
  2942             //step 4 - let MEC be { G1, G2 ... Gn }, then we have that
  2943             //lub = lci(Inv(G1)) & lci(Inv(G2)) & ... & lci(Inv(Gn))
  2944             return compoundMin(candidates);
  2946         default:
  2947             // calculate lub(A, B[])
  2948             List<Type> classes = List.of(arraySuperType());
  2949             for (Type t : ts) {
  2950                 if (t.tag != ARRAY) // Filter out any arrays
  2951                     classes = classes.prepend(t);
  2953             // lub(A, B[]) is lub(A, arraySuperType)
  2954             return lub(classes);
  2957     // where
  2958         List<Type> erasedSupertypes(Type t) {
  2959             ListBuffer<Type> buf = lb();
  2960             for (Type sup : closure(t)) {
  2961                 if (sup.tag == TYPEVAR) {
  2962                     buf.append(sup);
  2963                 } else {
  2964                     buf.append(erasure(sup));
  2967             return buf.toList();
  2970         private Type arraySuperType = null;
  2971         private Type arraySuperType() {
  2972             // initialized lazily to avoid problems during compiler startup
  2973             if (arraySuperType == null) {
  2974                 synchronized (this) {
  2975                     if (arraySuperType == null) {
  2976                         // JLS 10.8: all arrays implement Cloneable and Serializable.
  2977                         arraySuperType = makeCompoundType(List.of(syms.serializableType,
  2978                                                                   syms.cloneableType),
  2979                                                           syms.objectType);
  2983             return arraySuperType;
  2985     // </editor-fold>
  2987     // <editor-fold defaultstate="collapsed" desc="Greatest lower bound">
  2988     public Type glb(List<Type> ts) {
  2989         Type t1 = ts.head;
  2990         for (Type t2 : ts.tail) {
  2991             if (t1.isErroneous())
  2992                 return t1;
  2993             t1 = glb(t1, t2);
  2995         return t1;
  2997     //where
  2998     public Type glb(Type t, Type s) {
  2999         if (s == null)
  3000             return t;
  3001         else if (t.isPrimitive() || s.isPrimitive())
  3002             return syms.errType;
  3003         else if (isSubtypeNoCapture(t, s))
  3004             return t;
  3005         else if (isSubtypeNoCapture(s, t))
  3006             return s;
  3008         List<Type> closure = union(closure(t), closure(s));
  3009         List<Type> bounds = closureMin(closure);
  3011         if (bounds.isEmpty()) {             // length == 0
  3012             return syms.objectType;
  3013         } else if (bounds.tail.isEmpty()) { // length == 1
  3014             return bounds.head;
  3015         } else {                            // length > 1
  3016             int classCount = 0;
  3017             for (Type bound : bounds)
  3018                 if (!bound.isInterface())
  3019                     classCount++;
  3020             if (classCount > 1)
  3021                 return createErrorType(t);
  3023         return makeCompoundType(bounds);
  3025     // </editor-fold>
  3027     // <editor-fold defaultstate="collapsed" desc="hashCode">
  3028     /**
  3029      * Compute a hash code on a type.
  3030      */
  3031     public static int hashCode(Type t) {
  3032         return hashCode.visit(t);
  3034     // where
  3035         private static final UnaryVisitor<Integer> hashCode = new UnaryVisitor<Integer>() {
  3037             public Integer visitType(Type t, Void ignored) {
  3038                 return t.tag;
  3041             @Override
  3042             public Integer visitClassType(ClassType t, Void ignored) {
  3043                 int result = visit(t.getEnclosingType());
  3044                 result *= 127;
  3045                 result += t.tsym.flatName().hashCode();
  3046                 for (Type s : t.getTypeArguments()) {
  3047                     result *= 127;
  3048                     result += visit(s);
  3050                 return result;
  3053             @Override
  3054             public Integer visitWildcardType(WildcardType t, Void ignored) {
  3055                 int result = t.kind.hashCode();
  3056                 if (t.type != null) {
  3057                     result *= 127;
  3058                     result += visit(t.type);
  3060                 return result;
  3063             @Override
  3064             public Integer visitArrayType(ArrayType t, Void ignored) {
  3065                 return visit(t.elemtype) + 12;
  3068             @Override
  3069             public Integer visitTypeVar(TypeVar t, Void ignored) {
  3070                 return System.identityHashCode(t.tsym);
  3073             @Override
  3074             public Integer visitUndetVar(UndetVar t, Void ignored) {
  3075                 return System.identityHashCode(t);
  3078             @Override
  3079             public Integer visitErrorType(ErrorType t, Void ignored) {
  3080                 return 0;
  3082         };
  3083     // </editor-fold>
  3085     // <editor-fold defaultstate="collapsed" desc="Return-Type-Substitutable">
  3086     /**
  3087      * Does t have a result that is a subtype of the result type of s,
  3088      * suitable for covariant returns?  It is assumed that both types
  3089      * are (possibly polymorphic) method types.  Monomorphic method
  3090      * types are handled in the obvious way.  Polymorphic method types
  3091      * require renaming all type variables of one to corresponding
  3092      * type variables in the other, where correspondence is by
  3093      * position in the type parameter list. */
  3094     public boolean resultSubtype(Type t, Type s, Warner warner) {
  3095         List<Type> tvars = t.getTypeArguments();
  3096         List<Type> svars = s.getTypeArguments();
  3097         Type tres = t.getReturnType();
  3098         Type sres = subst(s.getReturnType(), svars, tvars);
  3099         return covariantReturnType(tres, sres, warner);
  3102     /**
  3103      * Return-Type-Substitutable.
  3104      * @jls section 8.4.5
  3105      */
  3106     public boolean returnTypeSubstitutable(Type r1, Type r2) {
  3107         if (hasSameArgs(r1, r2))
  3108             return resultSubtype(r1, r2, Warner.noWarnings);
  3109         else
  3110             return covariantReturnType(r1.getReturnType(),
  3111                                        erasure(r2.getReturnType()),
  3112                                        Warner.noWarnings);
  3115     public boolean returnTypeSubstitutable(Type r1,
  3116                                            Type r2, Type r2res,
  3117                                            Warner warner) {
  3118         if (isSameType(r1.getReturnType(), r2res))
  3119             return true;
  3120         if (r1.getReturnType().isPrimitive() || r2res.isPrimitive())
  3121             return false;
  3123         if (hasSameArgs(r1, r2))
  3124             return covariantReturnType(r1.getReturnType(), r2res, warner);
  3125         if (!allowCovariantReturns)
  3126             return false;
  3127         if (isSubtypeUnchecked(r1.getReturnType(), r2res, warner))
  3128             return true;
  3129         if (!isSubtype(r1.getReturnType(), erasure(r2res)))
  3130             return false;
  3131         warner.warn(LintCategory.UNCHECKED);
  3132         return true;
  3135     /**
  3136      * Is t an appropriate return type in an overrider for a
  3137      * method that returns s?
  3138      */
  3139     public boolean covariantReturnType(Type t, Type s, Warner warner) {
  3140         return
  3141             isSameType(t, s) ||
  3142             allowCovariantReturns &&
  3143             !t.isPrimitive() &&
  3144             !s.isPrimitive() &&
  3145             isAssignable(t, s, warner);
  3147     // </editor-fold>
  3149     // <editor-fold defaultstate="collapsed" desc="Box/unbox support">
  3150     /**
  3151      * Return the class that boxes the given primitive.
  3152      */
  3153     public ClassSymbol boxedClass(Type t) {
  3154         return reader.enterClass(syms.boxedName[t.tag]);
  3157     /**
  3158      * Return the boxed type if 't' is primitive, otherwise return 't' itself.
  3159      */
  3160     public Type boxedTypeOrType(Type t) {
  3161         return t.isPrimitive() ?
  3162             boxedClass(t).type :
  3163             t;
  3166     /**
  3167      * Return the primitive type corresponding to a boxed type.
  3168      */
  3169     public Type unboxedType(Type t) {
  3170         if (allowBoxing) {
  3171             for (int i=0; i<syms.boxedName.length; i++) {
  3172                 Name box = syms.boxedName[i];
  3173                 if (box != null &&
  3174                     asSuper(t, reader.enterClass(box)) != null)
  3175                     return syms.typeOfTag[i];
  3178         return Type.noType;
  3180     // </editor-fold>
  3182     // <editor-fold defaultstate="collapsed" desc="Capture conversion">
  3183     /*
  3184      * JLS 5.1.10 Capture Conversion:
  3186      * Let G name a generic type declaration with n formal type
  3187      * parameters A1 ... An with corresponding bounds U1 ... Un. There
  3188      * exists a capture conversion from G<T1 ... Tn> to G<S1 ... Sn>,
  3189      * where, for 1 <= i <= n:
  3191      * + If Ti is a wildcard type argument (4.5.1) of the form ? then
  3192      *   Si is a fresh type variable whose upper bound is
  3193      *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is the null
  3194      *   type.
  3196      * + If Ti is a wildcard type argument of the form ? extends Bi,
  3197      *   then Si is a fresh type variable whose upper bound is
  3198      *   glb(Bi, Ui[A1 := S1, ..., An := Sn]) and whose lower bound is
  3199      *   the null type, where glb(V1,... ,Vm) is V1 & ... & Vm. It is
  3200      *   a compile-time error if for any two classes (not interfaces)
  3201      *   Vi and Vj,Vi is not a subclass of Vj or vice versa.
  3203      * + If Ti is a wildcard type argument of the form ? super Bi,
  3204      *   then Si is a fresh type variable whose upper bound is
  3205      *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is Bi.
  3207      * + Otherwise, Si = Ti.
  3209      * Capture conversion on any type other than a parameterized type
  3210      * (4.5) acts as an identity conversion (5.1.1). Capture
  3211      * conversions never require a special action at run time and
  3212      * therefore never throw an exception at run time.
  3214      * Capture conversion is not applied recursively.
  3215      */
  3216     /**
  3217      * Capture conversion as specified by the JLS.
  3218      */
  3220     public List<Type> capture(List<Type> ts) {
  3221         List<Type> buf = List.nil();
  3222         for (Type t : ts) {
  3223             buf = buf.prepend(capture(t));
  3225         return buf.reverse();
  3227     public Type capture(Type t) {
  3228         if (t.tag != CLASS)
  3229             return t;
  3230         if (t.getEnclosingType() != Type.noType) {
  3231             Type capturedEncl = capture(t.getEnclosingType());
  3232             if (capturedEncl != t.getEnclosingType()) {
  3233                 Type type1 = memberType(capturedEncl, t.tsym);
  3234                 t = subst(type1, t.tsym.type.getTypeArguments(), t.getTypeArguments());
  3237         ClassType cls = (ClassType)t;
  3238         if (cls.isRaw() || !cls.isParameterized())
  3239             return cls;
  3241         ClassType G = (ClassType)cls.asElement().asType();
  3242         List<Type> A = G.getTypeArguments();
  3243         List<Type> T = cls.getTypeArguments();
  3244         List<Type> S = freshTypeVariables(T);
  3246         List<Type> currentA = A;
  3247         List<Type> currentT = T;
  3248         List<Type> currentS = S;
  3249         boolean captured = false;
  3250         while (!currentA.isEmpty() &&
  3251                !currentT.isEmpty() &&
  3252                !currentS.isEmpty()) {
  3253             if (currentS.head != currentT.head) {
  3254                 captured = true;
  3255                 WildcardType Ti = (WildcardType)currentT.head;
  3256                 Type Ui = currentA.head.getUpperBound();
  3257                 CapturedType Si = (CapturedType)currentS.head;
  3258                 if (Ui == null)
  3259                     Ui = syms.objectType;
  3260                 switch (Ti.kind) {
  3261                 case UNBOUND:
  3262                     Si.bound = subst(Ui, A, S);
  3263                     Si.lower = syms.botType;
  3264                     break;
  3265                 case EXTENDS:
  3266                     Si.bound = glb(Ti.getExtendsBound(), subst(Ui, A, S));
  3267                     Si.lower = syms.botType;
  3268                     break;
  3269                 case SUPER:
  3270                     Si.bound = subst(Ui, A, S);
  3271                     Si.lower = Ti.getSuperBound();
  3272                     break;
  3274                 if (Si.bound == Si.lower)
  3275                     currentS.head = Si.bound;
  3277             currentA = currentA.tail;
  3278             currentT = currentT.tail;
  3279             currentS = currentS.tail;
  3281         if (!currentA.isEmpty() || !currentT.isEmpty() || !currentS.isEmpty())
  3282             return erasure(t); // some "rare" type involved
  3284         if (captured)
  3285             return new ClassType(cls.getEnclosingType(), S, cls.tsym);
  3286         else
  3287             return t;
  3289     // where
  3290         public List<Type> freshTypeVariables(List<Type> types) {
  3291             ListBuffer<Type> result = lb();
  3292             for (Type t : types) {
  3293                 if (t.tag == WILDCARD) {
  3294                     Type bound = ((WildcardType)t).getExtendsBound();
  3295                     if (bound == null)
  3296                         bound = syms.objectType;
  3297                     result.append(new CapturedType(capturedName,
  3298                                                    syms.noSymbol,
  3299                                                    bound,
  3300                                                    syms.botType,
  3301                                                    (WildcardType)t));
  3302                 } else {
  3303                     result.append(t);
  3306             return result.toList();
  3308     // </editor-fold>
  3310     // <editor-fold defaultstate="collapsed" desc="Internal utility methods">
  3311     private List<Type> upperBounds(List<Type> ss) {
  3312         if (ss.isEmpty()) return ss;
  3313         Type head = upperBound(ss.head);
  3314         List<Type> tail = upperBounds(ss.tail);
  3315         if (head != ss.head || tail != ss.tail)
  3316             return tail.prepend(head);
  3317         else
  3318             return ss;
  3321     private boolean sideCast(Type from, Type to, Warner warn) {
  3322         // We are casting from type $from$ to type $to$, which are
  3323         // non-final unrelated types.  This method
  3324         // tries to reject a cast by transferring type parameters
  3325         // from $to$ to $from$ by common superinterfaces.
  3326         boolean reverse = false;
  3327         Type target = to;
  3328         if ((to.tsym.flags() & INTERFACE) == 0) {
  3329             Assert.check((from.tsym.flags() & INTERFACE) != 0);
  3330             reverse = true;
  3331             to = from;
  3332             from = target;
  3334         List<Type> commonSupers = superClosure(to, erasure(from));
  3335         boolean giveWarning = commonSupers.isEmpty();
  3336         // The arguments to the supers could be unified here to
  3337         // get a more accurate analysis
  3338         while (commonSupers.nonEmpty()) {
  3339             Type t1 = asSuper(from, commonSupers.head.tsym);
  3340             Type t2 = commonSupers.head; // same as asSuper(to, commonSupers.head.tsym);
  3341             if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
  3342                 return false;
  3343             giveWarning = giveWarning || (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2));
  3344             commonSupers = commonSupers.tail;
  3346         if (giveWarning && !isReifiable(reverse ? from : to))
  3347             warn.warn(LintCategory.UNCHECKED);
  3348         if (!allowCovariantReturns)
  3349             // reject if there is a common method signature with
  3350             // incompatible return types.
  3351             chk.checkCompatibleAbstracts(warn.pos(), from, to);
  3352         return true;
  3355     private boolean sideCastFinal(Type from, Type to, Warner warn) {
  3356         // We are casting from type $from$ to type $to$, which are
  3357         // unrelated types one of which is final and the other of
  3358         // which is an interface.  This method
  3359         // tries to reject a cast by transferring type parameters
  3360         // from the final class to the interface.
  3361         boolean reverse = false;
  3362         Type target = to;
  3363         if ((to.tsym.flags() & INTERFACE) == 0) {
  3364             Assert.check((from.tsym.flags() & INTERFACE) != 0);
  3365             reverse = true;
  3366             to = from;
  3367             from = target;
  3369         Assert.check((from.tsym.flags() & FINAL) != 0);
  3370         Type t1 = asSuper(from, to.tsym);
  3371         if (t1 == null) return false;
  3372         Type t2 = to;
  3373         if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
  3374             return false;
  3375         if (!allowCovariantReturns)
  3376             // reject if there is a common method signature with
  3377             // incompatible return types.
  3378             chk.checkCompatibleAbstracts(warn.pos(), from, to);
  3379         if (!isReifiable(target) &&
  3380             (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2)))
  3381             warn.warn(LintCategory.UNCHECKED);
  3382         return true;
  3385     private boolean giveWarning(Type from, Type to) {
  3386         Type subFrom = asSub(from, to.tsym);
  3387         return to.isParameterized() &&
  3388                 (!(isUnbounded(to) ||
  3389                 isSubtype(from, to) ||
  3390                 ((subFrom != null) && containsType(to.allparams(), subFrom.allparams()))));
  3393     private List<Type> superClosure(Type t, Type s) {
  3394         List<Type> cl = List.nil();
  3395         for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
  3396             if (isSubtype(s, erasure(l.head))) {
  3397                 cl = insert(cl, l.head);
  3398             } else {
  3399                 cl = union(cl, superClosure(l.head, s));
  3402         return cl;
  3405     private boolean containsTypeEquivalent(Type t, Type s) {
  3406         return
  3407             isSameType(t, s) || // shortcut
  3408             containsType(t, s) && containsType(s, t);
  3411     // <editor-fold defaultstate="collapsed" desc="adapt">
  3412     /**
  3413      * Adapt a type by computing a substitution which maps a source
  3414      * type to a target type.
  3416      * @param source    the source type
  3417      * @param target    the target type
  3418      * @param from      the type variables of the computed substitution
  3419      * @param to        the types of the computed substitution.
  3420      */
  3421     public void adapt(Type source,
  3422                        Type target,
  3423                        ListBuffer<Type> from,
  3424                        ListBuffer<Type> to) throws AdaptFailure {
  3425         new Adapter(from, to).adapt(source, target);
  3428     class Adapter extends SimpleVisitor<Void, Type> {
  3430         ListBuffer<Type> from;
  3431         ListBuffer<Type> to;
  3432         Map<Symbol,Type> mapping;
  3434         Adapter(ListBuffer<Type> from, ListBuffer<Type> to) {
  3435             this.from = from;
  3436             this.to = to;
  3437             mapping = new HashMap<Symbol,Type>();
  3440         public void adapt(Type source, Type target) throws AdaptFailure {
  3441             visit(source, target);
  3442             List<Type> fromList = from.toList();
  3443             List<Type> toList = to.toList();
  3444             while (!fromList.isEmpty()) {
  3445                 Type val = mapping.get(fromList.head.tsym);
  3446                 if (toList.head != val)
  3447                     toList.head = val;
  3448                 fromList = fromList.tail;
  3449                 toList = toList.tail;
  3453         @Override
  3454         public Void visitClassType(ClassType source, Type target) throws AdaptFailure {
  3455             if (target.tag == CLASS)
  3456                 adaptRecursive(source.allparams(), target.allparams());
  3457             return null;
  3460         @Override
  3461         public Void visitArrayType(ArrayType source, Type target) throws AdaptFailure {
  3462             if (target.tag == ARRAY)
  3463                 adaptRecursive(elemtype(source), elemtype(target));
  3464             return null;
  3467         @Override
  3468         public Void visitWildcardType(WildcardType source, Type target) throws AdaptFailure {
  3469             if (source.isExtendsBound())
  3470                 adaptRecursive(upperBound(source), upperBound(target));
  3471             else if (source.isSuperBound())
  3472                 adaptRecursive(lowerBound(source), lowerBound(target));
  3473             return null;
  3476         @Override
  3477         public Void visitTypeVar(TypeVar source, Type target) throws AdaptFailure {
  3478             // Check to see if there is
  3479             // already a mapping for $source$, in which case
  3480             // the old mapping will be merged with the new
  3481             Type val = mapping.get(source.tsym);
  3482             if (val != null) {
  3483                 if (val.isSuperBound() && target.isSuperBound()) {
  3484                     val = isSubtype(lowerBound(val), lowerBound(target))
  3485                         ? target : val;
  3486                 } else if (val.isExtendsBound() && target.isExtendsBound()) {
  3487                     val = isSubtype(upperBound(val), upperBound(target))
  3488                         ? val : target;
  3489                 } else if (!isSameType(val, target)) {
  3490                     throw new AdaptFailure();
  3492             } else {
  3493                 val = target;
  3494                 from.append(source);
  3495                 to.append(target);
  3497             mapping.put(source.tsym, val);
  3498             return null;
  3501         @Override
  3502         public Void visitType(Type source, Type target) {
  3503             return null;
  3506         private Set<TypePair> cache = new HashSet<TypePair>();
  3508         private void adaptRecursive(Type source, Type target) {
  3509             TypePair pair = new TypePair(source, target);
  3510             if (cache.add(pair)) {
  3511                 try {
  3512                     visit(source, target);
  3513                 } finally {
  3514                     cache.remove(pair);
  3519         private void adaptRecursive(List<Type> source, List<Type> target) {
  3520             if (source.length() == target.length()) {
  3521                 while (source.nonEmpty()) {
  3522                     adaptRecursive(source.head, target.head);
  3523                     source = source.tail;
  3524                     target = target.tail;
  3530     public static class AdaptFailure extends RuntimeException {
  3531         static final long serialVersionUID = -7490231548272701566L;
  3534     private void adaptSelf(Type t,
  3535                            ListBuffer<Type> from,
  3536                            ListBuffer<Type> to) {
  3537         try {
  3538             //if (t.tsym.type != t)
  3539                 adapt(t.tsym.type, t, from, to);
  3540         } catch (AdaptFailure ex) {
  3541             // Adapt should never fail calculating a mapping from
  3542             // t.tsym.type to t as there can be no merge problem.
  3543             throw new AssertionError(ex);
  3546     // </editor-fold>
  3548     /**
  3549      * Rewrite all type variables (universal quantifiers) in the given
  3550      * type to wildcards (existential quantifiers).  This is used to
  3551      * determine if a cast is allowed.  For example, if high is true
  3552      * and {@code T <: Number}, then {@code List<T>} is rewritten to
  3553      * {@code List<?  extends Number>}.  Since {@code List<Integer> <:
  3554      * List<? extends Number>} a {@code List<T>} can be cast to {@code
  3555      * List<Integer>} with a warning.
  3556      * @param t a type
  3557      * @param high if true return an upper bound; otherwise a lower
  3558      * bound
  3559      * @param rewriteTypeVars only rewrite captured wildcards if false;
  3560      * otherwise rewrite all type variables
  3561      * @return the type rewritten with wildcards (existential
  3562      * quantifiers) only
  3563      */
  3564     private Type rewriteQuantifiers(Type t, boolean high, boolean rewriteTypeVars) {
  3565         return new Rewriter(high, rewriteTypeVars).visit(t);
  3568     class Rewriter extends UnaryVisitor<Type> {
  3570         boolean high;
  3571         boolean rewriteTypeVars;
  3573         Rewriter(boolean high, boolean rewriteTypeVars) {
  3574             this.high = high;
  3575             this.rewriteTypeVars = rewriteTypeVars;
  3578         @Override
  3579         public Type visitClassType(ClassType t, Void s) {
  3580             ListBuffer<Type> rewritten = new ListBuffer<Type>();
  3581             boolean changed = false;
  3582             for (Type arg : t.allparams()) {
  3583                 Type bound = visit(arg);
  3584                 if (arg != bound) {
  3585                     changed = true;
  3587                 rewritten.append(bound);
  3589             if (changed)
  3590                 return subst(t.tsym.type,
  3591                         t.tsym.type.allparams(),
  3592                         rewritten.toList());
  3593             else
  3594                 return t;
  3597         public Type visitType(Type t, Void s) {
  3598             return high ? upperBound(t) : lowerBound(t);
  3601         @Override
  3602         public Type visitCapturedType(CapturedType t, Void s) {
  3603             Type bound = visitWildcardType(t.wildcard, null);
  3604             return (bound.contains(t)) ?
  3605                     erasure(bound) :
  3606                     bound;
  3609         @Override
  3610         public Type visitTypeVar(TypeVar t, Void s) {
  3611             if (rewriteTypeVars) {
  3612                 Type bound = high ?
  3613                     (t.bound.contains(t) ?
  3614                         erasure(t.bound) :
  3615                         visit(t.bound)) :
  3616                     syms.botType;
  3617                 return rewriteAsWildcardType(bound, t);
  3619             else
  3620                 return t;
  3623         @Override
  3624         public Type visitWildcardType(WildcardType t, Void s) {
  3625             Type bound = high ? t.getExtendsBound() :
  3626                                 t.getSuperBound();
  3627             if (bound == null)
  3628             bound = high ? syms.objectType : syms.botType;
  3629             return rewriteAsWildcardType(visit(bound), t.bound);
  3632         private Type rewriteAsWildcardType(Type bound, TypeVar formal) {
  3633             return high ?
  3634                 makeExtendsWildcard(B(bound), formal) :
  3635                 makeSuperWildcard(B(bound), formal);
  3638         Type B(Type t) {
  3639             while (t.tag == WILDCARD) {
  3640                 WildcardType w = (WildcardType)t;
  3641                 t = high ?
  3642                     w.getExtendsBound() :
  3643                     w.getSuperBound();
  3644                 if (t == null) {
  3645                     t = high ? syms.objectType : syms.botType;
  3648             return t;
  3653     /**
  3654      * Create a wildcard with the given upper (extends) bound; create
  3655      * an unbounded wildcard if bound is Object.
  3657      * @param bound the upper bound
  3658      * @param formal the formal type parameter that will be
  3659      * substituted by the wildcard
  3660      */
  3661     private WildcardType makeExtendsWildcard(Type bound, TypeVar formal) {
  3662         if (bound == syms.objectType) {
  3663             return new WildcardType(syms.objectType,
  3664                                     BoundKind.UNBOUND,
  3665                                     syms.boundClass,
  3666                                     formal);
  3667         } else {
  3668             return new WildcardType(bound,
  3669                                     BoundKind.EXTENDS,
  3670                                     syms.boundClass,
  3671                                     formal);
  3675     /**
  3676      * Create a wildcard with the given lower (super) bound; create an
  3677      * unbounded wildcard if bound is bottom (type of {@code null}).
  3679      * @param bound the lower bound
  3680      * @param formal the formal type parameter that will be
  3681      * substituted by the wildcard
  3682      */
  3683     private WildcardType makeSuperWildcard(Type bound, TypeVar formal) {
  3684         if (bound.tag == BOT) {
  3685             return new WildcardType(syms.objectType,
  3686                                     BoundKind.UNBOUND,
  3687                                     syms.boundClass,
  3688                                     formal);
  3689         } else {
  3690             return new WildcardType(bound,
  3691                                     BoundKind.SUPER,
  3692                                     syms.boundClass,
  3693                                     formal);
  3697     /**
  3698      * A wrapper for a type that allows use in sets.
  3699      */
  3700     class SingletonType {
  3701         final Type t;
  3702         SingletonType(Type t) {
  3703             this.t = t;
  3705         public int hashCode() {
  3706             return Types.hashCode(t);
  3708         public boolean equals(Object obj) {
  3709             return (obj instanceof SingletonType) &&
  3710                 isSameType(t, ((SingletonType)obj).t);
  3712         public String toString() {
  3713             return t.toString();
  3716     // </editor-fold>
  3718     // <editor-fold defaultstate="collapsed" desc="Visitors">
  3719     /**
  3720      * A default visitor for types.  All visitor methods except
  3721      * visitType are implemented by delegating to visitType.  Concrete
  3722      * subclasses must provide an implementation of visitType and can
  3723      * override other methods as needed.
  3725      * @param <R> the return type of the operation implemented by this
  3726      * visitor; use Void if no return type is needed.
  3727      * @param <S> the type of the second argument (the first being the
  3728      * type itself) of the operation implemented by this visitor; use
  3729      * Void if a second argument is not needed.
  3730      */
  3731     public static abstract class DefaultTypeVisitor<R,S> implements Type.Visitor<R,S> {
  3732         final public R visit(Type t, S s)               { return t.accept(this, s); }
  3733         public R visitClassType(ClassType t, S s)       { return visitType(t, s); }
  3734         public R visitWildcardType(WildcardType t, S s) { return visitType(t, s); }
  3735         public R visitArrayType(ArrayType t, S s)       { return visitType(t, s); }
  3736         public R visitMethodType(MethodType t, S s)     { return visitType(t, s); }
  3737         public R visitPackageType(PackageType t, S s)   { return visitType(t, s); }
  3738         public R visitTypeVar(TypeVar t, S s)           { return visitType(t, s); }
  3739         public R visitCapturedType(CapturedType t, S s) { return visitType(t, s); }
  3740         public R visitForAll(ForAll t, S s)             { return visitType(t, s); }
  3741         public R visitUndetVar(UndetVar t, S s)         { return visitType(t, s); }
  3742         public R visitErrorType(ErrorType t, S s)       { return visitType(t, s); }
  3745     /**
  3746      * A default visitor for symbols.  All visitor methods except
  3747      * visitSymbol are implemented by delegating to visitSymbol.  Concrete
  3748      * subclasses must provide an implementation of visitSymbol and can
  3749      * override other methods as needed.
  3751      * @param <R> the return type of the operation implemented by this
  3752      * visitor; use Void if no return type is needed.
  3753      * @param <S> the type of the second argument (the first being the
  3754      * symbol itself) of the operation implemented by this visitor; use
  3755      * Void if a second argument is not needed.
  3756      */
  3757     public static abstract class DefaultSymbolVisitor<R,S> implements Symbol.Visitor<R,S> {
  3758         final public R visit(Symbol s, S arg)                   { return s.accept(this, arg); }
  3759         public R visitClassSymbol(ClassSymbol s, S arg)         { return visitSymbol(s, arg); }
  3760         public R visitMethodSymbol(MethodSymbol s, S arg)       { return visitSymbol(s, arg); }
  3761         public R visitOperatorSymbol(OperatorSymbol s, S arg)   { return visitSymbol(s, arg); }
  3762         public R visitPackageSymbol(PackageSymbol s, S arg)     { return visitSymbol(s, arg); }
  3763         public R visitTypeSymbol(TypeSymbol s, S arg)           { return visitSymbol(s, arg); }
  3764         public R visitVarSymbol(VarSymbol s, S arg)             { return visitSymbol(s, arg); }
  3767     /**
  3768      * A <em>simple</em> visitor for types.  This visitor is simple as
  3769      * captured wildcards, for-all types (generic methods), and
  3770      * undetermined type variables (part of inference) are hidden.
  3771      * Captured wildcards are hidden by treating them as type
  3772      * variables and the rest are hidden by visiting their qtypes.
  3774      * @param <R> the return type of the operation implemented by this
  3775      * visitor; use Void if no return type is needed.
  3776      * @param <S> the type of the second argument (the first being the
  3777      * type itself) of the operation implemented by this visitor; use
  3778      * Void if a second argument is not needed.
  3779      */
  3780     public static abstract class SimpleVisitor<R,S> extends DefaultTypeVisitor<R,S> {
  3781         @Override
  3782         public R visitCapturedType(CapturedType t, S s) {
  3783             return visitTypeVar(t, s);
  3785         @Override
  3786         public R visitForAll(ForAll t, S s) {
  3787             return visit(t.qtype, s);
  3789         @Override
  3790         public R visitUndetVar(UndetVar t, S s) {
  3791             return visit(t.qtype, s);
  3795     /**
  3796      * A plain relation on types.  That is a 2-ary function on the
  3797      * form Type&nbsp;&times;&nbsp;Type&nbsp;&rarr;&nbsp;Boolean.
  3798      * <!-- In plain text: Type x Type -> Boolean -->
  3799      */
  3800     public static abstract class TypeRelation extends SimpleVisitor<Boolean,Type> {}
  3802     /**
  3803      * A convenience visitor for implementing operations that only
  3804      * require one argument (the type itself), that is, unary
  3805      * operations.
  3807      * @param <R> the return type of the operation implemented by this
  3808      * visitor; use Void if no return type is needed.
  3809      */
  3810     public static abstract class UnaryVisitor<R> extends SimpleVisitor<R,Void> {
  3811         final public R visit(Type t) { return t.accept(this, null); }
  3814     /**
  3815      * A visitor for implementing a mapping from types to types.  The
  3816      * default behavior of this class is to implement the identity
  3817      * mapping (mapping a type to itself).  This can be overridden in
  3818      * subclasses.
  3820      * @param <S> the type of the second argument (the first being the
  3821      * type itself) of this mapping; use Void if a second argument is
  3822      * not needed.
  3823      */
  3824     public static class MapVisitor<S> extends DefaultTypeVisitor<Type,S> {
  3825         final public Type visit(Type t) { return t.accept(this, null); }
  3826         public Type visitType(Type t, S s) { return t; }
  3828     // </editor-fold>
  3831     // <editor-fold defaultstate="collapsed" desc="Annotation support">
  3833     public RetentionPolicy getRetention(Attribute.Compound a) {
  3834         RetentionPolicy vis = RetentionPolicy.CLASS; // the default
  3835         Attribute.Compound c = a.type.tsym.attribute(syms.retentionType.tsym);
  3836         if (c != null) {
  3837             Attribute value = c.member(names.value);
  3838             if (value != null && value instanceof Attribute.Enum) {
  3839                 Name levelName = ((Attribute.Enum)value).value.name;
  3840                 if (levelName == names.SOURCE) vis = RetentionPolicy.SOURCE;
  3841                 else if (levelName == names.CLASS) vis = RetentionPolicy.CLASS;
  3842                 else if (levelName == names.RUNTIME) vis = RetentionPolicy.RUNTIME;
  3843                 else ;// /* fail soft */ throw new AssertionError(levelName);
  3846         return vis;
  3848     // </editor-fold>

mercurial