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

Mon, 07 Feb 2011 18:10:13 +0000

author
mcimadamore
date
Mon, 07 Feb 2011 18:10:13 +0000
changeset 858
96d4226bdd60
parent 846
17bafae67e9d
child 877
351027202f60
permissions
-rw-r--r--

7007615: java_util/generics/phase2/NameClashTest02 fails since jdk7/pit/b123.
Summary: override clash algorithm is not implemented correctly
Reviewed-by: jjg

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

mercurial