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

Tue, 28 Dec 2010 15:54:52 -0800

author
ohair
date
Tue, 28 Dec 2010 15:54:52 -0800
changeset 798
4868a36f6fd8
parent 795
7b99f98b3035
child 816
7c537f4298fb
permissions
-rw-r--r--

6962318: Update copyright year
Reviewed-by: xdono

     1 /*
     2  * Copyright (c) 2003, 2010, 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.Type.*;
    40 import static com.sun.tools.javac.code.TypeTags.*;
    41 import static com.sun.tools.javac.code.Symbol.*;
    42 import static com.sun.tools.javac.code.Flags.*;
    43 import static com.sun.tools.javac.code.BoundKind.*;
    44 import static com.sun.tools.javac.util.ListBuffer.lb;
    46 /**
    47  * Utility class containing various operations on types.
    48  *
    49  * <p>Unless other names are more illustrative, the following naming
    50  * conventions should be observed in this file:
    51  *
    52  * <dl>
    53  * <dt>t</dt>
    54  * <dd>If the first argument to an operation is a type, it should be named t.</dd>
    55  * <dt>s</dt>
    56  * <dd>Similarly, if the second argument to an operation is a type, it should be named s.</dd>
    57  * <dt>ts</dt>
    58  * <dd>If an operations takes a list of types, the first should be named ts.</dd>
    59  * <dt>ss</dt>
    60  * <dd>A second list of types should be named ss.</dd>
    61  * </dl>
    62  *
    63  * <p><b>This is NOT part of any supported API.
    64  * If you write code that depends on this, you do so at your own risk.
    65  * This code and its internal interfaces are subject to change or
    66  * deletion without notice.</b>
    67  */
    68 public class Types {
    69     protected static final Context.Key<Types> typesKey =
    70         new Context.Key<Types>();
    72     final Symtab syms;
    73     final Scope.ScopeCounter scopeCounter;
    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         scopeCounter = Scope.ScopeCounter.instance(context);
    95         names = Names.instance(context);
    96         allowBoxing = Source.instance(context).allowBoxing();
    97         reader = ClassReader.instance(context);
    98         source = Source.instance(context);
    99         chk = Check.instance(context);
   100         capturedName = names.fromString("<captured wildcard>");
   101         messages = JavacMessages.instance(context);
   102     }
   103     // </editor-fold>
   105     // <editor-fold defaultstate="collapsed" desc="upperBound">
   106     /**
   107      * The "rvalue conversion".<br>
   108      * The upper bound of most types is the type
   109      * itself.  Wildcards, on the other hand have upper
   110      * and lower bounds.
   111      * @param t a type
   112      * @return the upper bound of the given type
   113      */
   114     public Type upperBound(Type t) {
   115         return upperBound.visit(t);
   116     }
   117     // where
   118         private final MapVisitor<Void> upperBound = new MapVisitor<Void>() {
   120             @Override
   121             public Type visitWildcardType(WildcardType t, Void ignored) {
   122                 if (t.isSuperBound())
   123                     return t.bound == null ? syms.objectType : t.bound.bound;
   124                 else
   125                     return visit(t.type);
   126             }
   128             @Override
   129             public Type visitCapturedType(CapturedType t, Void ignored) {
   130                 return visit(t.bound);
   131             }
   132         };
   133     // </editor-fold>
   135     // <editor-fold defaultstate="collapsed" desc="lowerBound">
   136     /**
   137      * The "lvalue conversion".<br>
   138      * The lower bound of most types is the type
   139      * itself.  Wildcards, on the other hand have upper
   140      * and lower bounds.
   141      * @param t a type
   142      * @return the lower bound of the given type
   143      */
   144     public Type lowerBound(Type t) {
   145         return lowerBound.visit(t);
   146     }
   147     // where
   148         private final MapVisitor<Void> lowerBound = new MapVisitor<Void>() {
   150             @Override
   151             public Type visitWildcardType(WildcardType t, Void ignored) {
   152                 return t.isExtendsBound() ? syms.botType : visit(t.type);
   153             }
   155             @Override
   156             public Type visitCapturedType(CapturedType t, Void ignored) {
   157                 return visit(t.getLowerBound());
   158             }
   159         };
   160     // </editor-fold>
   162     // <editor-fold defaultstate="collapsed" desc="isUnbounded">
   163     /**
   164      * Checks that all the arguments to a class are unbounded
   165      * wildcards or something else that doesn't make any restrictions
   166      * on the arguments. If a class isUnbounded, a raw super- or
   167      * subclass can be cast to it without a warning.
   168      * @param t a type
   169      * @return true iff the given type is unbounded or raw
   170      */
   171     public boolean isUnbounded(Type t) {
   172         return isUnbounded.visit(t);
   173     }
   174     // where
   175         private final UnaryVisitor<Boolean> isUnbounded = new UnaryVisitor<Boolean>() {
   177             public Boolean visitType(Type t, Void ignored) {
   178                 return true;
   179             }
   181             @Override
   182             public Boolean visitClassType(ClassType t, Void ignored) {
   183                 List<Type> parms = t.tsym.type.allparams();
   184                 List<Type> args = t.allparams();
   185                 while (parms.nonEmpty()) {
   186                     WildcardType unb = new WildcardType(syms.objectType,
   187                                                         BoundKind.UNBOUND,
   188                                                         syms.boundClass,
   189                                                         (TypeVar)parms.head);
   190                     if (!containsType(args.head, unb))
   191                         return false;
   192                     parms = parms.tail;
   193                     args = args.tail;
   194                 }
   195                 return true;
   196             }
   197         };
   198     // </editor-fold>
   200     // <editor-fold defaultstate="collapsed" desc="asSub">
   201     /**
   202      * Return the least specific subtype of t that starts with symbol
   203      * sym.  If none exists, return null.  The least specific subtype
   204      * is determined as follows:
   205      *
   206      * <p>If there is exactly one parameterized instance of sym that is a
   207      * subtype of t, that parameterized instance is returned.<br>
   208      * Otherwise, if the plain type or raw type `sym' is a subtype of
   209      * type t, the type `sym' itself is returned.  Otherwise, null is
   210      * returned.
   211      */
   212     public Type asSub(Type t, Symbol sym) {
   213         return asSub.visit(t, sym);
   214     }
   215     // where
   216         private final SimpleVisitor<Type,Symbol> asSub = new SimpleVisitor<Type,Symbol>() {
   218             public Type visitType(Type t, Symbol sym) {
   219                 return null;
   220             }
   222             @Override
   223             public Type visitClassType(ClassType t, Symbol sym) {
   224                 if (t.tsym == sym)
   225                     return t;
   226                 Type base = asSuper(sym.type, t.tsym);
   227                 if (base == null)
   228                     return null;
   229                 ListBuffer<Type> from = new ListBuffer<Type>();
   230                 ListBuffer<Type> to = new ListBuffer<Type>();
   231                 try {
   232                     adapt(base, t, from, to);
   233                 } catch (AdaptFailure ex) {
   234                     return null;
   235                 }
   236                 Type res = subst(sym.type, from.toList(), to.toList());
   237                 if (!isSubtype(res, t))
   238                     return null;
   239                 ListBuffer<Type> openVars = new ListBuffer<Type>();
   240                 for (List<Type> l = sym.type.allparams();
   241                      l.nonEmpty(); l = l.tail)
   242                     if (res.contains(l.head) && !t.contains(l.head))
   243                         openVars.append(l.head);
   244                 if (openVars.nonEmpty()) {
   245                     if (t.isRaw()) {
   246                         // The subtype of a raw type is raw
   247                         res = erasure(res);
   248                     } else {
   249                         // Unbound type arguments default to ?
   250                         List<Type> opens = openVars.toList();
   251                         ListBuffer<Type> qs = new ListBuffer<Type>();
   252                         for (List<Type> iter = opens; iter.nonEmpty(); iter = iter.tail) {
   253                             qs.append(new WildcardType(syms.objectType, BoundKind.UNBOUND, syms.boundClass, (TypeVar) iter.head));
   254                         }
   255                         res = subst(res, opens, qs.toList());
   256                     }
   257                 }
   258                 return res;
   259             }
   261             @Override
   262             public Type visitErrorType(ErrorType t, Symbol sym) {
   263                 return t;
   264             }
   265         };
   266     // </editor-fold>
   268     // <editor-fold defaultstate="collapsed" desc="isConvertible">
   269     /**
   270      * Is t a subtype of or convertiable via boxing/unboxing
   271      * convertions to s?
   272      */
   273     public boolean isConvertible(Type t, Type s, Warner warn) {
   274         boolean tPrimitive = t.isPrimitive();
   275         boolean sPrimitive = s.isPrimitive();
   276         if (tPrimitive == sPrimitive) {
   277             checkUnsafeVarargsConversion(t, s, warn);
   278             return isSubtypeUnchecked(t, s, warn);
   279         }
   280         if (!allowBoxing) return false;
   281         return tPrimitive
   282             ? isSubtype(boxedClass(t).type, s)
   283             : isSubtype(unboxedType(t), s);
   284     }
   285     //where
   286     private void checkUnsafeVarargsConversion(Type t, Type s, Warner warn) {
   287         if (t.tag != ARRAY || isReifiable(t)) return;
   288         ArrayType from = (ArrayType)t;
   289         boolean shouldWarn = false;
   290         switch (s.tag) {
   291             case ARRAY:
   292                 ArrayType to = (ArrayType)s;
   293                 shouldWarn = from.isVarargs() &&
   294                         !to.isVarargs() &&
   295                         !isReifiable(from);
   296                 break;
   297             case CLASS:
   298                 shouldWarn = from.isVarargs() &&
   299                         isSubtype(from, s);
   300                 break;
   301         }
   302         if (shouldWarn) {
   303             warn.warn(LintCategory.VARARGS);
   304         }
   305     }
   307     /**
   308      * Is t a subtype of or convertiable via boxing/unboxing
   309      * convertions to s?
   310      */
   311     public boolean isConvertible(Type t, Type s) {
   312         return isConvertible(t, s, Warner.noWarnings);
   313     }
   314     // </editor-fold>
   316     // <editor-fold defaultstate="collapsed" desc="isSubtype">
   317     /**
   318      * Is t an unchecked subtype of s?
   319      */
   320     public boolean isSubtypeUnchecked(Type t, Type s) {
   321         return isSubtypeUnchecked(t, s, Warner.noWarnings);
   322     }
   323     /**
   324      * Is t an unchecked subtype of s?
   325      */
   326     public boolean isSubtypeUnchecked(Type t, Type s, Warner warn) {
   327         if (t.tag == ARRAY && s.tag == ARRAY) {
   328             if (((ArrayType)t).elemtype.tag <= lastBaseTag) {
   329                 return isSameType(elemtype(t), elemtype(s));
   330             } else {
   331                 ArrayType from = (ArrayType)t;
   332                 ArrayType to = (ArrayType)s;
   333                 if (from.isVarargs() &&
   334                         !to.isVarargs() &&
   335                         !isReifiable(from)) {
   336                     warn.warn(LintCategory.VARARGS);
   337                 }
   338                 return isSubtypeUnchecked(elemtype(t), elemtype(s), warn);
   339             }
   340         } else if (isSubtype(t, s)) {
   341             return true;
   342         }
   343         else if (t.tag == TYPEVAR) {
   344             return isSubtypeUnchecked(t.getUpperBound(), s, warn);
   345         }
   346         else if (s.tag == UNDETVAR) {
   347             UndetVar uv = (UndetVar)s;
   348             if (uv.inst != null)
   349                 return isSubtypeUnchecked(t, uv.inst, warn);
   350         }
   351         else if (!s.isRaw()) {
   352             Type t2 = asSuper(t, s.tsym);
   353             if (t2 != null && t2.isRaw()) {
   354                 if (isReifiable(s))
   355                     warn.silentWarn(LintCategory.UNCHECKED);
   356                 else
   357                     warn.warn(LintCategory.UNCHECKED);
   358                 return true;
   359             }
   360         }
   361         return false;
   362     }
   364     /**
   365      * Is t a subtype of s?<br>
   366      * (not defined for Method and ForAll types)
   367      */
   368     final public boolean isSubtype(Type t, Type s) {
   369         return isSubtype(t, s, true);
   370     }
   371     final public boolean isSubtypeNoCapture(Type t, Type s) {
   372         return isSubtype(t, s, false);
   373     }
   374     public boolean isSubtype(Type t, Type s, boolean capture) {
   375         if (t == s)
   376             return true;
   378         if (s.tag >= firstPartialTag)
   379             return isSuperType(s, t);
   381         if (s.isCompound()) {
   382             for (Type s2 : interfaces(s).prepend(supertype(s))) {
   383                 if (!isSubtype(t, s2, capture))
   384                     return false;
   385             }
   386             return true;
   387         }
   389         Type lower = lowerBound(s);
   390         if (s != lower)
   391             return isSubtype(capture ? capture(t) : t, lower, false);
   393         return isSubtype.visit(capture ? capture(t) : t, s);
   394     }
   395     // where
   396         private TypeRelation isSubtype = new TypeRelation()
   397         {
   398             public Boolean visitType(Type t, Type s) {
   399                 switch (t.tag) {
   400                 case BYTE: case CHAR:
   401                     return (t.tag == s.tag ||
   402                               t.tag + 2 <= s.tag && s.tag <= DOUBLE);
   403                 case SHORT: case INT: case LONG: case FLOAT: case DOUBLE:
   404                     return t.tag <= s.tag && s.tag <= DOUBLE;
   405                 case BOOLEAN: case VOID:
   406                     return t.tag == s.tag;
   407                 case TYPEVAR:
   408                     return isSubtypeNoCapture(t.getUpperBound(), s);
   409                 case BOT:
   410                     return
   411                         s.tag == BOT || s.tag == CLASS ||
   412                         s.tag == ARRAY || s.tag == TYPEVAR;
   413                 case NONE:
   414                     return false;
   415                 default:
   416                     throw new AssertionError("isSubtype " + t.tag);
   417                 }
   418             }
   420             private Set<TypePair> cache = new HashSet<TypePair>();
   422             private boolean containsTypeRecursive(Type t, Type s) {
   423                 TypePair pair = new TypePair(t, s);
   424                 if (cache.add(pair)) {
   425                     try {
   426                         return containsType(t.getTypeArguments(),
   427                                             s.getTypeArguments());
   428                     } finally {
   429                         cache.remove(pair);
   430                     }
   431                 } else {
   432                     return containsType(t.getTypeArguments(),
   433                                         rewriteSupers(s).getTypeArguments());
   434                 }
   435             }
   437             private Type rewriteSupers(Type t) {
   438                 if (!t.isParameterized())
   439                     return t;
   440                 ListBuffer<Type> from = lb();
   441                 ListBuffer<Type> to = lb();
   442                 adaptSelf(t, from, to);
   443                 if (from.isEmpty())
   444                     return t;
   445                 ListBuffer<Type> rewrite = lb();
   446                 boolean changed = false;
   447                 for (Type orig : to.toList()) {
   448                     Type s = rewriteSupers(orig);
   449                     if (s.isSuperBound() && !s.isExtendsBound()) {
   450                         s = new WildcardType(syms.objectType,
   451                                              BoundKind.UNBOUND,
   452                                              syms.boundClass);
   453                         changed = true;
   454                     } else if (s != orig) {
   455                         s = new WildcardType(upperBound(s),
   456                                              BoundKind.EXTENDS,
   457                                              syms.boundClass);
   458                         changed = true;
   459                     }
   460                     rewrite.append(s);
   461                 }
   462                 if (changed)
   463                     return subst(t.tsym.type, from.toList(), rewrite.toList());
   464                 else
   465                     return t;
   466             }
   468             @Override
   469             public Boolean visitClassType(ClassType t, Type s) {
   470                 Type sup = asSuper(t, s.tsym);
   471                 return sup != null
   472                     && sup.tsym == s.tsym
   473                     // You're not allowed to write
   474                     //     Vector<Object> vec = new Vector<String>();
   475                     // But with wildcards you can write
   476                     //     Vector<? extends Object> vec = new Vector<String>();
   477                     // which means that subtype checking must be done
   478                     // here instead of same-type checking (via containsType).
   479                     && (!s.isParameterized() || containsTypeRecursive(s, sup))
   480                     && isSubtypeNoCapture(sup.getEnclosingType(),
   481                                           s.getEnclosingType());
   482             }
   484             @Override
   485             public Boolean visitArrayType(ArrayType t, Type s) {
   486                 if (s.tag == ARRAY) {
   487                     if (t.elemtype.tag <= lastBaseTag)
   488                         return isSameType(t.elemtype, elemtype(s));
   489                     else
   490                         return isSubtypeNoCapture(t.elemtype, elemtype(s));
   491                 }
   493                 if (s.tag == CLASS) {
   494                     Name sname = s.tsym.getQualifiedName();
   495                     return sname == names.java_lang_Object
   496                         || sname == names.java_lang_Cloneable
   497                         || sname == names.java_io_Serializable;
   498                 }
   500                 return false;
   501             }
   503             @Override
   504             public Boolean visitUndetVar(UndetVar t, Type s) {
   505                 //todo: test against origin needed? or replace with substitution?
   506                 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN)
   507                     return true;
   509                 if (t.inst != null)
   510                     return isSubtypeNoCapture(t.inst, s); // TODO: ", warn"?
   512                 t.hibounds = t.hibounds.prepend(s);
   513                 return true;
   514             }
   516             @Override
   517             public Boolean visitErrorType(ErrorType t, Type s) {
   518                 return true;
   519             }
   520         };
   522     /**
   523      * Is t a subtype of every type in given list `ts'?<br>
   524      * (not defined for Method and ForAll types)<br>
   525      * Allows unchecked conversions.
   526      */
   527     public boolean isSubtypeUnchecked(Type t, List<Type> ts, Warner warn) {
   528         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
   529             if (!isSubtypeUnchecked(t, l.head, warn))
   530                 return false;
   531         return true;
   532     }
   534     /**
   535      * Are corresponding elements of ts subtypes of ss?  If lists are
   536      * of different length, return false.
   537      */
   538     public boolean isSubtypes(List<Type> ts, List<Type> ss) {
   539         while (ts.tail != null && ss.tail != null
   540                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   541                isSubtype(ts.head, ss.head)) {
   542             ts = ts.tail;
   543             ss = ss.tail;
   544         }
   545         return ts.tail == null && ss.tail == null;
   546         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   547     }
   549     /**
   550      * Are corresponding elements of ts subtypes of ss, allowing
   551      * unchecked conversions?  If lists are of different length,
   552      * return false.
   553      **/
   554     public boolean isSubtypesUnchecked(List<Type> ts, List<Type> ss, Warner warn) {
   555         while (ts.tail != null && ss.tail != null
   556                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   557                isSubtypeUnchecked(ts.head, ss.head, warn)) {
   558             ts = ts.tail;
   559             ss = ss.tail;
   560         }
   561         return ts.tail == null && ss.tail == null;
   562         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   563     }
   564     // </editor-fold>
   566     // <editor-fold defaultstate="collapsed" desc="isSuperType">
   567     /**
   568      * Is t a supertype of s?
   569      */
   570     public boolean isSuperType(Type t, Type s) {
   571         switch (t.tag) {
   572         case ERROR:
   573             return true;
   574         case UNDETVAR: {
   575             UndetVar undet = (UndetVar)t;
   576             if (t == s ||
   577                 undet.qtype == s ||
   578                 s.tag == ERROR ||
   579                 s.tag == BOT) return true;
   580             if (undet.inst != null)
   581                 return isSubtype(s, undet.inst);
   582             undet.lobounds = undet.lobounds.prepend(s);
   583             return true;
   584         }
   585         default:
   586             return isSubtype(s, t);
   587         }
   588     }
   589     // </editor-fold>
   591     // <editor-fold defaultstate="collapsed" desc="isSameType">
   592     /**
   593      * Are corresponding elements of the lists the same type?  If
   594      * lists are of different length, return false.
   595      */
   596     public boolean isSameTypes(List<Type> ts, List<Type> ss) {
   597         while (ts.tail != null && ss.tail != null
   598                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   599                isSameType(ts.head, ss.head)) {
   600             ts = ts.tail;
   601             ss = ss.tail;
   602         }
   603         return ts.tail == null && ss.tail == null;
   604         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   605     }
   607     /**
   608      * Is t the same type as s?
   609      */
   610     public boolean isSameType(Type t, Type s) {
   611         return isSameType.visit(t, s);
   612     }
   613     // where
   614         private TypeRelation isSameType = new TypeRelation() {
   616             public Boolean visitType(Type t, Type s) {
   617                 if (t == s)
   618                     return true;
   620                 if (s.tag >= firstPartialTag)
   621                     return visit(s, t);
   623                 switch (t.tag) {
   624                 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
   625                 case DOUBLE: case BOOLEAN: case VOID: case BOT: case NONE:
   626                     return t.tag == s.tag;
   627                 case TYPEVAR: {
   628                     if (s.tag == TYPEVAR) {
   629                         //type-substitution does not preserve type-var types
   630                         //check that type var symbols and bounds are indeed the same
   631                         return t.tsym == s.tsym &&
   632                                 visit(t.getUpperBound(), s.getUpperBound());
   633                     }
   634                     else {
   635                         //special case for s == ? super X, where upper(s) = u
   636                         //check that u == t, where u has been set by Type.withTypeVar
   637                         return s.isSuperBound() &&
   638                                 !s.isExtendsBound() &&
   639                                 visit(t, upperBound(s));
   640                     }
   641                 }
   642                 default:
   643                     throw new AssertionError("isSameType " + t.tag);
   644                 }
   645             }
   647             @Override
   648             public Boolean visitWildcardType(WildcardType t, Type s) {
   649                 if (s.tag >= firstPartialTag)
   650                     return visit(s, t);
   651                 else
   652                     return false;
   653             }
   655             @Override
   656             public Boolean visitClassType(ClassType t, Type s) {
   657                 if (t == s)
   658                     return true;
   660                 if (s.tag >= firstPartialTag)
   661                     return visit(s, t);
   663                 if (s.isSuperBound() && !s.isExtendsBound())
   664                     return visit(t, upperBound(s)) && visit(t, lowerBound(s));
   666                 if (t.isCompound() && s.isCompound()) {
   667                     if (!visit(supertype(t), supertype(s)))
   668                         return false;
   670                     HashSet<SingletonType> set = new HashSet<SingletonType>();
   671                     for (Type x : interfaces(t))
   672                         set.add(new SingletonType(x));
   673                     for (Type x : interfaces(s)) {
   674                         if (!set.remove(new SingletonType(x)))
   675                             return false;
   676                     }
   677                     return (set.isEmpty());
   678                 }
   679                 return t.tsym == s.tsym
   680                     && visit(t.getEnclosingType(), s.getEnclosingType())
   681                     && containsTypeEquivalent(t.getTypeArguments(), s.getTypeArguments());
   682             }
   684             @Override
   685             public Boolean visitArrayType(ArrayType t, Type s) {
   686                 if (t == s)
   687                     return true;
   689                 if (s.tag >= firstPartialTag)
   690                     return visit(s, t);
   692                 return s.tag == ARRAY
   693                     && containsTypeEquivalent(t.elemtype, elemtype(s));
   694             }
   696             @Override
   697             public Boolean visitMethodType(MethodType t, Type s) {
   698                 // isSameType for methods does not take thrown
   699                 // exceptions into account!
   700                 return hasSameArgs(t, s) && visit(t.getReturnType(), s.getReturnType());
   701             }
   703             @Override
   704             public Boolean visitPackageType(PackageType t, Type s) {
   705                 return t == s;
   706             }
   708             @Override
   709             public Boolean visitForAll(ForAll t, Type s) {
   710                 if (s.tag != FORALL)
   711                     return false;
   713                 ForAll forAll = (ForAll)s;
   714                 return hasSameBounds(t, forAll)
   715                     && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
   716             }
   718             @Override
   719             public Boolean visitUndetVar(UndetVar t, Type s) {
   720                 if (s.tag == WILDCARD)
   721                     // FIXME, this might be leftovers from before capture conversion
   722                     return false;
   724                 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN)
   725                     return true;
   727                 if (t.inst != null)
   728                     return visit(t.inst, s);
   730                 t.inst = fromUnknownFun.apply(s);
   731                 for (List<Type> l = t.lobounds; l.nonEmpty(); l = l.tail) {
   732                     if (!isSubtype(l.head, t.inst))
   733                         return false;
   734                 }
   735                 for (List<Type> l = t.hibounds; l.nonEmpty(); l = l.tail) {
   736                     if (!isSubtype(t.inst, l.head))
   737                         return false;
   738                 }
   739                 return true;
   740             }
   742             @Override
   743             public Boolean visitErrorType(ErrorType t, Type s) {
   744                 return true;
   745             }
   746         };
   747     // </editor-fold>
   749     // <editor-fold defaultstate="collapsed" desc="fromUnknownFun">
   750     /**
   751      * A mapping that turns all unknown types in this type to fresh
   752      * unknown variables.
   753      */
   754     public Mapping fromUnknownFun = new Mapping("fromUnknownFun") {
   755             public Type apply(Type t) {
   756                 if (t.tag == UNKNOWN) return new UndetVar(t);
   757                 else return t.map(this);
   758             }
   759         };
   760     // </editor-fold>
   762     // <editor-fold defaultstate="collapsed" desc="Contains Type">
   763     public boolean containedBy(Type t, Type s) {
   764         switch (t.tag) {
   765         case UNDETVAR:
   766             if (s.tag == WILDCARD) {
   767                 UndetVar undetvar = (UndetVar)t;
   768                 WildcardType wt = (WildcardType)s;
   769                 switch(wt.kind) {
   770                     case UNBOUND: //similar to ? extends Object
   771                     case EXTENDS: {
   772                         Type bound = upperBound(s);
   773                         // We should check the new upper bound against any of the
   774                         // undetvar's lower bounds.
   775                         for (Type t2 : undetvar.lobounds) {
   776                             if (!isSubtype(t2, bound))
   777                                 return false;
   778                         }
   779                         undetvar.hibounds = undetvar.hibounds.prepend(bound);
   780                         break;
   781                     }
   782                     case SUPER: {
   783                         Type bound = lowerBound(s);
   784                         // We should check the new lower bound against any of the
   785                         // undetvar's lower bounds.
   786                         for (Type t2 : undetvar.hibounds) {
   787                             if (!isSubtype(bound, t2))
   788                                 return false;
   789                         }
   790                         undetvar.lobounds = undetvar.lobounds.prepend(bound);
   791                         break;
   792                     }
   793                 }
   794                 return true;
   795             } else {
   796                 return isSameType(t, s);
   797             }
   798         case ERROR:
   799             return true;
   800         default:
   801             return containsType(s, t);
   802         }
   803     }
   805     boolean containsType(List<Type> ts, List<Type> ss) {
   806         while (ts.nonEmpty() && ss.nonEmpty()
   807                && containsType(ts.head, ss.head)) {
   808             ts = ts.tail;
   809             ss = ss.tail;
   810         }
   811         return ts.isEmpty() && ss.isEmpty();
   812     }
   814     /**
   815      * Check if t contains s.
   816      *
   817      * <p>T contains S if:
   818      *
   819      * <p>{@code L(T) <: L(S) && U(S) <: U(T)}
   820      *
   821      * <p>This relation is only used by ClassType.isSubtype(), that
   822      * is,
   823      *
   824      * <p>{@code C<S> <: C<T> if T contains S.}
   825      *
   826      * <p>Because of F-bounds, this relation can lead to infinite
   827      * recursion.  Thus we must somehow break that recursion.  Notice
   828      * that containsType() is only called from ClassType.isSubtype().
   829      * Since the arguments have already been checked against their
   830      * bounds, we know:
   831      *
   832      * <p>{@code U(S) <: U(T) if T is "super" bound (U(T) *is* the bound)}
   833      *
   834      * <p>{@code L(T) <: L(S) if T is "extends" bound (L(T) is bottom)}
   835      *
   836      * @param t a type
   837      * @param s a type
   838      */
   839     public boolean containsType(Type t, Type s) {
   840         return containsType.visit(t, s);
   841     }
   842     // where
   843         private TypeRelation containsType = new TypeRelation() {
   845             private Type U(Type t) {
   846                 while (t.tag == WILDCARD) {
   847                     WildcardType w = (WildcardType)t;
   848                     if (w.isSuperBound())
   849                         return w.bound == null ? syms.objectType : w.bound.bound;
   850                     else
   851                         t = w.type;
   852                 }
   853                 return t;
   854             }
   856             private Type L(Type t) {
   857                 while (t.tag == WILDCARD) {
   858                     WildcardType w = (WildcardType)t;
   859                     if (w.isExtendsBound())
   860                         return syms.botType;
   861                     else
   862                         t = w.type;
   863                 }
   864                 return t;
   865             }
   867             public Boolean visitType(Type t, Type s) {
   868                 if (s.tag >= firstPartialTag)
   869                     return containedBy(s, t);
   870                 else
   871                     return isSameType(t, s);
   872             }
   874 //            void debugContainsType(WildcardType t, Type s) {
   875 //                System.err.println();
   876 //                System.err.format(" does %s contain %s?%n", t, s);
   877 //                System.err.format(" %s U(%s) <: U(%s) %s = %s%n",
   878 //                                  upperBound(s), s, t, U(t),
   879 //                                  t.isSuperBound()
   880 //                                  || isSubtypeNoCapture(upperBound(s), U(t)));
   881 //                System.err.format(" %s L(%s) <: L(%s) %s = %s%n",
   882 //                                  L(t), t, s, lowerBound(s),
   883 //                                  t.isExtendsBound()
   884 //                                  || isSubtypeNoCapture(L(t), lowerBound(s)));
   885 //                System.err.println();
   886 //            }
   888             @Override
   889             public Boolean visitWildcardType(WildcardType t, Type s) {
   890                 if (s.tag >= firstPartialTag)
   891                     return containedBy(s, t);
   892                 else {
   893 //                    debugContainsType(t, s);
   894                     return isSameWildcard(t, s)
   895                         || isCaptureOf(s, t)
   896                         || ((t.isExtendsBound() || isSubtypeNoCapture(L(t), lowerBound(s))) &&
   897                             (t.isSuperBound() || isSubtypeNoCapture(upperBound(s), U(t))));
   898                 }
   899             }
   901             @Override
   902             public Boolean visitUndetVar(UndetVar t, Type s) {
   903                 if (s.tag != WILDCARD)
   904                     return isSameType(t, s);
   905                 else
   906                     return false;
   907             }
   909             @Override
   910             public Boolean visitErrorType(ErrorType t, Type s) {
   911                 return true;
   912             }
   913         };
   915     public boolean isCaptureOf(Type s, WildcardType t) {
   916         if (s.tag != TYPEVAR || !((TypeVar)s).isCaptured())
   917             return false;
   918         return isSameWildcard(t, ((CapturedType)s).wildcard);
   919     }
   921     public boolean isSameWildcard(WildcardType t, Type s) {
   922         if (s.tag != WILDCARD)
   923             return false;
   924         WildcardType w = (WildcardType)s;
   925         return w.kind == t.kind && w.type == t.type;
   926     }
   928     public boolean containsTypeEquivalent(List<Type> ts, List<Type> ss) {
   929         while (ts.nonEmpty() && ss.nonEmpty()
   930                && containsTypeEquivalent(ts.head, ss.head)) {
   931             ts = ts.tail;
   932             ss = ss.tail;
   933         }
   934         return ts.isEmpty() && ss.isEmpty();
   935     }
   936     // </editor-fold>
   938     // <editor-fold defaultstate="collapsed" desc="isCastable">
   939     public boolean isCastable(Type t, Type s) {
   940         return isCastable(t, s, Warner.noWarnings);
   941     }
   943     /**
   944      * Is t is castable to s?<br>
   945      * s is assumed to be an erased type.<br>
   946      * (not defined for Method and ForAll types).
   947      */
   948     public boolean isCastable(Type t, Type s, Warner warn) {
   949         if (t == s)
   950             return true;
   952         if (t.isPrimitive() != s.isPrimitive())
   953             return allowBoxing && (isConvertible(t, s, warn) || isConvertible(s, t, warn));
   955         if (warn != warnStack.head) {
   956             try {
   957                 warnStack = warnStack.prepend(warn);
   958                 checkUnsafeVarargsConversion(t, s, warn);
   959                 return isCastable.visit(t,s);
   960             } finally {
   961                 warnStack = warnStack.tail;
   962             }
   963         } else {
   964             return isCastable.visit(t,s);
   965         }
   966     }
   967     // where
   968         private TypeRelation isCastable = new TypeRelation() {
   970             public Boolean visitType(Type t, Type s) {
   971                 if (s.tag == ERROR)
   972                     return true;
   974                 switch (t.tag) {
   975                 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
   976                 case DOUBLE:
   977                     return s.tag <= DOUBLE;
   978                 case BOOLEAN:
   979                     return s.tag == BOOLEAN;
   980                 case VOID:
   981                     return false;
   982                 case BOT:
   983                     return isSubtype(t, s);
   984                 default:
   985                     throw new AssertionError();
   986                 }
   987             }
   989             @Override
   990             public Boolean visitWildcardType(WildcardType t, Type s) {
   991                 return isCastable(upperBound(t), s, warnStack.head);
   992             }
   994             @Override
   995             public Boolean visitClassType(ClassType t, Type s) {
   996                 if (s.tag == ERROR || s.tag == BOT)
   997                     return true;
   999                 if (s.tag == TYPEVAR) {
  1000                     if (isCastable(t, s.getUpperBound(), Warner.noWarnings)) {
  1001                         warnStack.head.warn(LintCategory.UNCHECKED);
  1002                         return true;
  1003                     } else {
  1004                         return false;
  1008                 if (t.isCompound()) {
  1009                     Warner oldWarner = warnStack.head;
  1010                     warnStack.head = Warner.noWarnings;
  1011                     if (!visit(supertype(t), s))
  1012                         return false;
  1013                     for (Type intf : interfaces(t)) {
  1014                         if (!visit(intf, s))
  1015                             return false;
  1017                     if (warnStack.head.hasLint(LintCategory.UNCHECKED))
  1018                         oldWarner.warn(LintCategory.UNCHECKED);
  1019                     return true;
  1022                 if (s.isCompound()) {
  1023                     // call recursively to reuse the above code
  1024                     return visitClassType((ClassType)s, t);
  1027                 if (s.tag == CLASS || s.tag == ARRAY) {
  1028                     boolean upcast;
  1029                     if ((upcast = isSubtype(erasure(t), erasure(s)))
  1030                         || isSubtype(erasure(s), erasure(t))) {
  1031                         if (!upcast && s.tag == ARRAY) {
  1032                             if (!isReifiable(s))
  1033                                 warnStack.head.warn(LintCategory.UNCHECKED);
  1034                             return true;
  1035                         } else if (s.isRaw()) {
  1036                             return true;
  1037                         } else if (t.isRaw()) {
  1038                             if (!isUnbounded(s))
  1039                                 warnStack.head.warn(LintCategory.UNCHECKED);
  1040                             return true;
  1042                         // Assume |a| <: |b|
  1043                         final Type a = upcast ? t : s;
  1044                         final Type b = upcast ? s : t;
  1045                         final boolean HIGH = true;
  1046                         final boolean LOW = false;
  1047                         final boolean DONT_REWRITE_TYPEVARS = false;
  1048                         Type aHigh = rewriteQuantifiers(a, HIGH, DONT_REWRITE_TYPEVARS);
  1049                         Type aLow  = rewriteQuantifiers(a, LOW,  DONT_REWRITE_TYPEVARS);
  1050                         Type bHigh = rewriteQuantifiers(b, HIGH, DONT_REWRITE_TYPEVARS);
  1051                         Type bLow  = rewriteQuantifiers(b, LOW,  DONT_REWRITE_TYPEVARS);
  1052                         Type lowSub = asSub(bLow, aLow.tsym);
  1053                         Type highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
  1054                         if (highSub == null) {
  1055                             final boolean REWRITE_TYPEVARS = true;
  1056                             aHigh = rewriteQuantifiers(a, HIGH, REWRITE_TYPEVARS);
  1057                             aLow  = rewriteQuantifiers(a, LOW,  REWRITE_TYPEVARS);
  1058                             bHigh = rewriteQuantifiers(b, HIGH, REWRITE_TYPEVARS);
  1059                             bLow  = rewriteQuantifiers(b, LOW,  REWRITE_TYPEVARS);
  1060                             lowSub = asSub(bLow, aLow.tsym);
  1061                             highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
  1063                         if (highSub != null) {
  1064                             assert a.tsym == highSub.tsym && a.tsym == lowSub.tsym
  1065                                 : 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 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 t != t.tsym.type : t.toString();
  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;
  2026             final Scope.ScopeCounter scopeCounter;
  2028             public Entry(MethodSymbol cachedImpl,
  2029                     Filter<Symbol> scopeFilter,
  2030                     boolean checkResult,
  2031                     Scope.ScopeCounter scopeCounter) {
  2032                 this.cachedImpl = cachedImpl;
  2033                 this.implFilter = scopeFilter;
  2034                 this.checkResult = checkResult;
  2035                 this.scopeCounter = scopeCounter;
  2038             boolean matches(Filter<Symbol> scopeFilter, boolean checkResult, Scope.ScopeCounter scopeCounter) {
  2039                 return this.implFilter == scopeFilter &&
  2040                         this.checkResult == checkResult &&
  2041                         this.scopeCounter.val() >= scopeCounter.val();
  2045         MethodSymbol get(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter, Scope.ScopeCounter scopeCounter) {
  2046             SoftReference<Map<TypeSymbol, Entry>> ref_cache = _map.get(ms);
  2047             Map<TypeSymbol, Entry> cache = ref_cache != null ? ref_cache.get() : null;
  2048             if (cache == null) {
  2049                 cache = new HashMap<TypeSymbol, Entry>();
  2050                 _map.put(ms, new SoftReference<Map<TypeSymbol, Entry>>(cache));
  2052             Entry e = cache.get(origin);
  2053             if (e == null ||
  2054                     !e.matches(implFilter, checkResult, scopeCounter)) {
  2055                 MethodSymbol impl = implementationInternal(ms, origin, Types.this, checkResult, implFilter);
  2056                 cache.put(origin, new Entry(impl, implFilter, checkResult, scopeCounter));
  2057                 return impl;
  2059             else {
  2060                 return e.cachedImpl;
  2064         private MethodSymbol implementationInternal(MethodSymbol ms, TypeSymbol origin, Types types, boolean checkResult, Filter<Symbol> implFilter) {
  2065             for (Type t = origin.type; t.tag == CLASS || t.tag == TYPEVAR; t = types.supertype(t)) {
  2066                 while (t.tag == TYPEVAR)
  2067                     t = t.getUpperBound();
  2068                 TypeSymbol c = t.tsym;
  2069                 for (Scope.Entry e = c.members().lookup(ms.name, implFilter);
  2070                      e.scope != null;
  2071                      e = e.next(implFilter)) {
  2072                     if (e.sym != null &&
  2073                              e.sym.overrides(ms, origin, types, checkResult))
  2074                         return (MethodSymbol)e.sym;
  2077             return null;
  2081     private ImplementationCache implCache = new ImplementationCache();
  2083     public MethodSymbol implementation(MethodSymbol ms, TypeSymbol origin, Types types, boolean checkResult, Filter<Symbol> implFilter) {
  2084         return implCache.get(ms, origin, checkResult, implFilter, scopeCounter);
  2086     // </editor-fold>
  2088     /**
  2089      * Does t have the same arguments as s?  It is assumed that both
  2090      * types are (possibly polymorphic) method types.  Monomorphic
  2091      * method types "have the same arguments", if their argument lists
  2092      * are equal.  Polymorphic method types "have the same arguments",
  2093      * if they have the same arguments after renaming all type
  2094      * variables of one to corresponding type variables in the other,
  2095      * where correspondence is by position in the type parameter list.
  2096      */
  2097     public boolean hasSameArgs(Type t, Type s) {
  2098         return hasSameArgs.visit(t, s);
  2100     // where
  2101         private TypeRelation hasSameArgs = new TypeRelation() {
  2103             public Boolean visitType(Type t, Type s) {
  2104                 throw new AssertionError();
  2107             @Override
  2108             public Boolean visitMethodType(MethodType t, Type s) {
  2109                 return s.tag == METHOD
  2110                     && containsTypeEquivalent(t.argtypes, s.getParameterTypes());
  2113             @Override
  2114             public Boolean visitForAll(ForAll t, Type s) {
  2115                 if (s.tag != FORALL)
  2116                     return false;
  2118                 ForAll forAll = (ForAll)s;
  2119                 return hasSameBounds(t, forAll)
  2120                     && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
  2123             @Override
  2124             public Boolean visitErrorType(ErrorType t, Type s) {
  2125                 return false;
  2127         };
  2128     // </editor-fold>
  2130     // <editor-fold defaultstate="collapsed" desc="subst">
  2131     public List<Type> subst(List<Type> ts,
  2132                             List<Type> from,
  2133                             List<Type> to) {
  2134         return new Subst(from, to).subst(ts);
  2137     /**
  2138      * Substitute all occurrences of a type in `from' with the
  2139      * corresponding type in `to' in 't'. Match lists `from' and `to'
  2140      * from the right: If lists have different length, discard leading
  2141      * elements of the longer list.
  2142      */
  2143     public Type subst(Type t, List<Type> from, List<Type> to) {
  2144         return new Subst(from, to).subst(t);
  2147     private class Subst extends UnaryVisitor<Type> {
  2148         List<Type> from;
  2149         List<Type> to;
  2151         public Subst(List<Type> from, List<Type> to) {
  2152             int fromLength = from.length();
  2153             int toLength = to.length();
  2154             while (fromLength > toLength) {
  2155                 fromLength--;
  2156                 from = from.tail;
  2158             while (fromLength < toLength) {
  2159                 toLength--;
  2160                 to = to.tail;
  2162             this.from = from;
  2163             this.to = to;
  2166         Type subst(Type t) {
  2167             if (from.tail == null)
  2168                 return t;
  2169             else
  2170                 return visit(t);
  2173         List<Type> subst(List<Type> ts) {
  2174             if (from.tail == null)
  2175                 return ts;
  2176             boolean wild = false;
  2177             if (ts.nonEmpty() && from.nonEmpty()) {
  2178                 Type head1 = subst(ts.head);
  2179                 List<Type> tail1 = subst(ts.tail);
  2180                 if (head1 != ts.head || tail1 != ts.tail)
  2181                     return tail1.prepend(head1);
  2183             return ts;
  2186         public Type visitType(Type t, Void ignored) {
  2187             return t;
  2190         @Override
  2191         public Type visitMethodType(MethodType t, Void ignored) {
  2192             List<Type> argtypes = subst(t.argtypes);
  2193             Type restype = subst(t.restype);
  2194             List<Type> thrown = subst(t.thrown);
  2195             if (argtypes == t.argtypes &&
  2196                 restype == t.restype &&
  2197                 thrown == t.thrown)
  2198                 return t;
  2199             else
  2200                 return new MethodType(argtypes, restype, thrown, t.tsym);
  2203         @Override
  2204         public Type visitTypeVar(TypeVar t, Void ignored) {
  2205             for (List<Type> from = this.from, to = this.to;
  2206                  from.nonEmpty();
  2207                  from = from.tail, to = to.tail) {
  2208                 if (t == from.head) {
  2209                     return to.head.withTypeVar(t);
  2212             return t;
  2215         @Override
  2216         public Type visitClassType(ClassType t, Void ignored) {
  2217             if (!t.isCompound()) {
  2218                 List<Type> typarams = t.getTypeArguments();
  2219                 List<Type> typarams1 = subst(typarams);
  2220                 Type outer = t.getEnclosingType();
  2221                 Type outer1 = subst(outer);
  2222                 if (typarams1 == typarams && outer1 == outer)
  2223                     return t;
  2224                 else
  2225                     return new ClassType(outer1, typarams1, t.tsym);
  2226             } else {
  2227                 Type st = subst(supertype(t));
  2228                 List<Type> is = upperBounds(subst(interfaces(t)));
  2229                 if (st == supertype(t) && is == interfaces(t))
  2230                     return t;
  2231                 else
  2232                     return makeCompoundType(is.prepend(st));
  2236         @Override
  2237         public Type visitWildcardType(WildcardType t, Void ignored) {
  2238             Type bound = t.type;
  2239             if (t.kind != BoundKind.UNBOUND)
  2240                 bound = subst(bound);
  2241             if (bound == t.type) {
  2242                 return t;
  2243             } else {
  2244                 if (t.isExtendsBound() && bound.isExtendsBound())
  2245                     bound = upperBound(bound);
  2246                 return new WildcardType(bound, t.kind, syms.boundClass, t.bound);
  2250         @Override
  2251         public Type visitArrayType(ArrayType t, Void ignored) {
  2252             Type elemtype = subst(t.elemtype);
  2253             if (elemtype == t.elemtype)
  2254                 return t;
  2255             else
  2256                 return new ArrayType(upperBound(elemtype), t.tsym);
  2259         @Override
  2260         public Type visitForAll(ForAll t, Void ignored) {
  2261             List<Type> tvars1 = substBounds(t.tvars, from, to);
  2262             Type qtype1 = subst(t.qtype);
  2263             if (tvars1 == t.tvars && qtype1 == t.qtype) {
  2264                 return t;
  2265             } else if (tvars1 == t.tvars) {
  2266                 return new ForAll(tvars1, qtype1);
  2267             } else {
  2268                 return new ForAll(tvars1, Types.this.subst(qtype1, t.tvars, tvars1));
  2272         @Override
  2273         public Type visitErrorType(ErrorType t, Void ignored) {
  2274             return t;
  2278     public List<Type> substBounds(List<Type> tvars,
  2279                                   List<Type> from,
  2280                                   List<Type> to) {
  2281         if (tvars.isEmpty())
  2282             return tvars;
  2283         ListBuffer<Type> newBoundsBuf = lb();
  2284         boolean changed = false;
  2285         // calculate new bounds
  2286         for (Type t : tvars) {
  2287             TypeVar tv = (TypeVar) t;
  2288             Type bound = subst(tv.bound, from, to);
  2289             if (bound != tv.bound)
  2290                 changed = true;
  2291             newBoundsBuf.append(bound);
  2293         if (!changed)
  2294             return tvars;
  2295         ListBuffer<Type> newTvars = lb();
  2296         // create new type variables without bounds
  2297         for (Type t : tvars) {
  2298             newTvars.append(new TypeVar(t.tsym, null, syms.botType));
  2300         // the new bounds should use the new type variables in place
  2301         // of the old
  2302         List<Type> newBounds = newBoundsBuf.toList();
  2303         from = tvars;
  2304         to = newTvars.toList();
  2305         for (; !newBounds.isEmpty(); newBounds = newBounds.tail) {
  2306             newBounds.head = subst(newBounds.head, from, to);
  2308         newBounds = newBoundsBuf.toList();
  2309         // set the bounds of new type variables to the new bounds
  2310         for (Type t : newTvars.toList()) {
  2311             TypeVar tv = (TypeVar) t;
  2312             tv.bound = newBounds.head;
  2313             newBounds = newBounds.tail;
  2315         return newTvars.toList();
  2318     public TypeVar substBound(TypeVar t, List<Type> from, List<Type> to) {
  2319         Type bound1 = subst(t.bound, from, to);
  2320         if (bound1 == t.bound)
  2321             return t;
  2322         else {
  2323             // create new type variable without bounds
  2324             TypeVar tv = new TypeVar(t.tsym, null, syms.botType);
  2325             // the new bound should use the new type variable in place
  2326             // of the old
  2327             tv.bound = subst(bound1, List.<Type>of(t), List.<Type>of(tv));
  2328             return tv;
  2331     // </editor-fold>
  2333     // <editor-fold defaultstate="collapsed" desc="hasSameBounds">
  2334     /**
  2335      * Does t have the same bounds for quantified variables as s?
  2336      */
  2337     boolean hasSameBounds(ForAll t, ForAll s) {
  2338         List<Type> l1 = t.tvars;
  2339         List<Type> l2 = s.tvars;
  2340         while (l1.nonEmpty() && l2.nonEmpty() &&
  2341                isSameType(l1.head.getUpperBound(),
  2342                           subst(l2.head.getUpperBound(),
  2343                                 s.tvars,
  2344                                 t.tvars))) {
  2345             l1 = l1.tail;
  2346             l2 = l2.tail;
  2348         return l1.isEmpty() && l2.isEmpty();
  2350     // </editor-fold>
  2352     // <editor-fold defaultstate="collapsed" desc="newInstances">
  2353     /** Create new vector of type variables from list of variables
  2354      *  changing all recursive bounds from old to new list.
  2355      */
  2356     public List<Type> newInstances(List<Type> tvars) {
  2357         List<Type> tvars1 = Type.map(tvars, newInstanceFun);
  2358         for (List<Type> l = tvars1; l.nonEmpty(); l = l.tail) {
  2359             TypeVar tv = (TypeVar) l.head;
  2360             tv.bound = subst(tv.bound, tvars, tvars1);
  2362         return tvars1;
  2364     static private Mapping newInstanceFun = new Mapping("newInstanceFun") {
  2365             public Type apply(Type t) { return new TypeVar(t.tsym, t.getUpperBound(), t.getLowerBound()); }
  2366         };
  2367     // </editor-fold>
  2369     // <editor-fold defaultstate="collapsed" desc="createErrorType">
  2370     public Type createErrorType(Type originalType) {
  2371         return new ErrorType(originalType, syms.errSymbol);
  2374     public Type createErrorType(ClassSymbol c, Type originalType) {
  2375         return new ErrorType(c, originalType);
  2378     public Type createErrorType(Name name, TypeSymbol container, Type originalType) {
  2379         return new ErrorType(name, container, originalType);
  2381     // </editor-fold>
  2383     // <editor-fold defaultstate="collapsed" desc="rank">
  2384     /**
  2385      * The rank of a class is the length of the longest path between
  2386      * the class and java.lang.Object in the class inheritance
  2387      * graph. Undefined for all but reference types.
  2388      */
  2389     public int rank(Type t) {
  2390         switch(t.tag) {
  2391         case CLASS: {
  2392             ClassType cls = (ClassType)t;
  2393             if (cls.rank_field < 0) {
  2394                 Name fullname = cls.tsym.getQualifiedName();
  2395                 if (fullname == names.java_lang_Object)
  2396                     cls.rank_field = 0;
  2397                 else {
  2398                     int r = rank(supertype(cls));
  2399                     for (List<Type> l = interfaces(cls);
  2400                          l.nonEmpty();
  2401                          l = l.tail) {
  2402                         if (rank(l.head) > r)
  2403                             r = rank(l.head);
  2405                     cls.rank_field = r + 1;
  2408             return cls.rank_field;
  2410         case TYPEVAR: {
  2411             TypeVar tvar = (TypeVar)t;
  2412             if (tvar.rank_field < 0) {
  2413                 int r = rank(supertype(tvar));
  2414                 for (List<Type> l = interfaces(tvar);
  2415                      l.nonEmpty();
  2416                      l = l.tail) {
  2417                     if (rank(l.head) > r) r = rank(l.head);
  2419                 tvar.rank_field = r + 1;
  2421             return tvar.rank_field;
  2423         case ERROR:
  2424             return 0;
  2425         default:
  2426             throw new AssertionError();
  2429     // </editor-fold>
  2431     /**
  2432      * Helper method for generating a string representation of a given type
  2433      * accordingly to a given locale
  2434      */
  2435     public String toString(Type t, Locale locale) {
  2436         return Printer.createStandardPrinter(messages).visit(t, locale);
  2439     /**
  2440      * Helper method for generating a string representation of a given type
  2441      * accordingly to a given locale
  2442      */
  2443     public String toString(Symbol t, Locale locale) {
  2444         return Printer.createStandardPrinter(messages).visit(t, locale);
  2447     // <editor-fold defaultstate="collapsed" desc="toString">
  2448     /**
  2449      * This toString is slightly more descriptive than the one on Type.
  2451      * @deprecated Types.toString(Type t, Locale l) provides better support
  2452      * for localization
  2453      */
  2454     @Deprecated
  2455     public String toString(Type t) {
  2456         if (t.tag == FORALL) {
  2457             ForAll forAll = (ForAll)t;
  2458             return typaramsString(forAll.tvars) + forAll.qtype;
  2460         return "" + t;
  2462     // where
  2463         private String typaramsString(List<Type> tvars) {
  2464             StringBuffer s = new StringBuffer();
  2465             s.append('<');
  2466             boolean first = true;
  2467             for (Type t : tvars) {
  2468                 if (!first) s.append(", ");
  2469                 first = false;
  2470                 appendTyparamString(((TypeVar)t), s);
  2472             s.append('>');
  2473             return s.toString();
  2475         private void appendTyparamString(TypeVar t, StringBuffer buf) {
  2476             buf.append(t);
  2477             if (t.bound == null ||
  2478                 t.bound.tsym.getQualifiedName() == names.java_lang_Object)
  2479                 return;
  2480             buf.append(" extends "); // Java syntax; no need for i18n
  2481             Type bound = t.bound;
  2482             if (!bound.isCompound()) {
  2483                 buf.append(bound);
  2484             } else if ((erasure(t).tsym.flags() & INTERFACE) == 0) {
  2485                 buf.append(supertype(t));
  2486                 for (Type intf : interfaces(t)) {
  2487                     buf.append('&');
  2488                     buf.append(intf);
  2490             } else {
  2491                 // No superclass was given in bounds.
  2492                 // In this case, supertype is Object, erasure is first interface.
  2493                 boolean first = true;
  2494                 for (Type intf : interfaces(t)) {
  2495                     if (!first) buf.append('&');
  2496                     first = false;
  2497                     buf.append(intf);
  2501     // </editor-fold>
  2503     // <editor-fold defaultstate="collapsed" desc="Determining least upper bounds of types">
  2504     /**
  2505      * A cache for closures.
  2507      * <p>A closure is a list of all the supertypes and interfaces of
  2508      * a class or interface type, ordered by ClassSymbol.precedes
  2509      * (that is, subclasses come first, arbitrary but fixed
  2510      * otherwise).
  2511      */
  2512     private Map<Type,List<Type>> closureCache = new HashMap<Type,List<Type>>();
  2514     /**
  2515      * Returns the closure of a class or interface type.
  2516      */
  2517     public List<Type> closure(Type t) {
  2518         List<Type> cl = closureCache.get(t);
  2519         if (cl == null) {
  2520             Type st = supertype(t);
  2521             if (!t.isCompound()) {
  2522                 if (st.tag == CLASS) {
  2523                     cl = insert(closure(st), t);
  2524                 } else if (st.tag == TYPEVAR) {
  2525                     cl = closure(st).prepend(t);
  2526                 } else {
  2527                     cl = List.of(t);
  2529             } else {
  2530                 cl = closure(supertype(t));
  2532             for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail)
  2533                 cl = union(cl, closure(l.head));
  2534             closureCache.put(t, cl);
  2536         return cl;
  2539     /**
  2540      * Insert a type in a closure
  2541      */
  2542     public List<Type> insert(List<Type> cl, Type t) {
  2543         if (cl.isEmpty() || t.tsym.precedes(cl.head.tsym, this)) {
  2544             return cl.prepend(t);
  2545         } else if (cl.head.tsym.precedes(t.tsym, this)) {
  2546             return insert(cl.tail, t).prepend(cl.head);
  2547         } else {
  2548             return cl;
  2552     /**
  2553      * Form the union of two closures
  2554      */
  2555     public List<Type> union(List<Type> cl1, List<Type> cl2) {
  2556         if (cl1.isEmpty()) {
  2557             return cl2;
  2558         } else if (cl2.isEmpty()) {
  2559             return cl1;
  2560         } else if (cl1.head.tsym.precedes(cl2.head.tsym, this)) {
  2561             return union(cl1.tail, cl2).prepend(cl1.head);
  2562         } else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) {
  2563             return union(cl1, cl2.tail).prepend(cl2.head);
  2564         } else {
  2565             return union(cl1.tail, cl2.tail).prepend(cl1.head);
  2569     /**
  2570      * Intersect two closures
  2571      */
  2572     public List<Type> intersect(List<Type> cl1, List<Type> cl2) {
  2573         if (cl1 == cl2)
  2574             return cl1;
  2575         if (cl1.isEmpty() || cl2.isEmpty())
  2576             return List.nil();
  2577         if (cl1.head.tsym.precedes(cl2.head.tsym, this))
  2578             return intersect(cl1.tail, cl2);
  2579         if (cl2.head.tsym.precedes(cl1.head.tsym, this))
  2580             return intersect(cl1, cl2.tail);
  2581         if (isSameType(cl1.head, cl2.head))
  2582             return intersect(cl1.tail, cl2.tail).prepend(cl1.head);
  2583         if (cl1.head.tsym == cl2.head.tsym &&
  2584             cl1.head.tag == CLASS && cl2.head.tag == CLASS) {
  2585             if (cl1.head.isParameterized() && cl2.head.isParameterized()) {
  2586                 Type merge = merge(cl1.head,cl2.head);
  2587                 return intersect(cl1.tail, cl2.tail).prepend(merge);
  2589             if (cl1.head.isRaw() || cl2.head.isRaw())
  2590                 return intersect(cl1.tail, cl2.tail).prepend(erasure(cl1.head));
  2592         return intersect(cl1.tail, cl2.tail);
  2594     // where
  2595         class TypePair {
  2596             final Type t1;
  2597             final Type t2;
  2598             TypePair(Type t1, Type t2) {
  2599                 this.t1 = t1;
  2600                 this.t2 = t2;
  2602             @Override
  2603             public int hashCode() {
  2604                 return 127 * Types.hashCode(t1) + Types.hashCode(t2);
  2606             @Override
  2607             public boolean equals(Object obj) {
  2608                 if (!(obj instanceof TypePair))
  2609                     return false;
  2610                 TypePair typePair = (TypePair)obj;
  2611                 return isSameType(t1, typePair.t1)
  2612                     && isSameType(t2, typePair.t2);
  2615         Set<TypePair> mergeCache = new HashSet<TypePair>();
  2616         private Type merge(Type c1, Type c2) {
  2617             ClassType class1 = (ClassType) c1;
  2618             List<Type> act1 = class1.getTypeArguments();
  2619             ClassType class2 = (ClassType) c2;
  2620             List<Type> act2 = class2.getTypeArguments();
  2621             ListBuffer<Type> merged = new ListBuffer<Type>();
  2622             List<Type> typarams = class1.tsym.type.getTypeArguments();
  2624             while (act1.nonEmpty() && act2.nonEmpty() && typarams.nonEmpty()) {
  2625                 if (containsType(act1.head, act2.head)) {
  2626                     merged.append(act1.head);
  2627                 } else if (containsType(act2.head, act1.head)) {
  2628                     merged.append(act2.head);
  2629                 } else {
  2630                     TypePair pair = new TypePair(c1, c2);
  2631                     Type m;
  2632                     if (mergeCache.add(pair)) {
  2633                         m = new WildcardType(lub(upperBound(act1.head),
  2634                                                  upperBound(act2.head)),
  2635                                              BoundKind.EXTENDS,
  2636                                              syms.boundClass);
  2637                         mergeCache.remove(pair);
  2638                     } else {
  2639                         m = new WildcardType(syms.objectType,
  2640                                              BoundKind.UNBOUND,
  2641                                              syms.boundClass);
  2643                     merged.append(m.withTypeVar(typarams.head));
  2645                 act1 = act1.tail;
  2646                 act2 = act2.tail;
  2647                 typarams = typarams.tail;
  2649             assert(act1.isEmpty() && act2.isEmpty() && typarams.isEmpty());
  2650             return new ClassType(class1.getEnclosingType(), merged.toList(), class1.tsym);
  2653     /**
  2654      * Return the minimum type of a closure, a compound type if no
  2655      * unique minimum exists.
  2656      */
  2657     private Type compoundMin(List<Type> cl) {
  2658         if (cl.isEmpty()) return syms.objectType;
  2659         List<Type> compound = closureMin(cl);
  2660         if (compound.isEmpty())
  2661             return null;
  2662         else if (compound.tail.isEmpty())
  2663             return compound.head;
  2664         else
  2665             return makeCompoundType(compound);
  2668     /**
  2669      * Return the minimum types of a closure, suitable for computing
  2670      * compoundMin or glb.
  2671      */
  2672     private List<Type> closureMin(List<Type> cl) {
  2673         ListBuffer<Type> classes = lb();
  2674         ListBuffer<Type> interfaces = lb();
  2675         while (!cl.isEmpty()) {
  2676             Type current = cl.head;
  2677             if (current.isInterface())
  2678                 interfaces.append(current);
  2679             else
  2680                 classes.append(current);
  2681             ListBuffer<Type> candidates = lb();
  2682             for (Type t : cl.tail) {
  2683                 if (!isSubtypeNoCapture(current, t))
  2684                     candidates.append(t);
  2686             cl = candidates.toList();
  2688         return classes.appendList(interfaces).toList();
  2691     /**
  2692      * Return the least upper bound of pair of types.  if the lub does
  2693      * not exist return null.
  2694      */
  2695     public Type lub(Type t1, Type t2) {
  2696         return lub(List.of(t1, t2));
  2699     /**
  2700      * Return the least upper bound (lub) of set of types.  If the lub
  2701      * does not exist return the type of null (bottom).
  2702      */
  2703     public Type lub(List<Type> ts) {
  2704         final int ARRAY_BOUND = 1;
  2705         final int CLASS_BOUND = 2;
  2706         int boundkind = 0;
  2707         for (Type t : ts) {
  2708             switch (t.tag) {
  2709             case CLASS:
  2710                 boundkind |= CLASS_BOUND;
  2711                 break;
  2712             case ARRAY:
  2713                 boundkind |= ARRAY_BOUND;
  2714                 break;
  2715             case  TYPEVAR:
  2716                 do {
  2717                     t = t.getUpperBound();
  2718                 } while (t.tag == TYPEVAR);
  2719                 if (t.tag == ARRAY) {
  2720                     boundkind |= ARRAY_BOUND;
  2721                 } else {
  2722                     boundkind |= CLASS_BOUND;
  2724                 break;
  2725             default:
  2726                 if (t.isPrimitive())
  2727                     return syms.errType;
  2730         switch (boundkind) {
  2731         case 0:
  2732             return syms.botType;
  2734         case ARRAY_BOUND:
  2735             // calculate lub(A[], B[])
  2736             List<Type> elements = Type.map(ts, elemTypeFun);
  2737             for (Type t : elements) {
  2738                 if (t.isPrimitive()) {
  2739                     // if a primitive type is found, then return
  2740                     // arraySuperType unless all the types are the
  2741                     // same
  2742                     Type first = ts.head;
  2743                     for (Type s : ts.tail) {
  2744                         if (!isSameType(first, s)) {
  2745                              // lub(int[], B[]) is Cloneable & Serializable
  2746                             return arraySuperType();
  2749                     // all the array types are the same, return one
  2750                     // lub(int[], int[]) is int[]
  2751                     return first;
  2754             // lub(A[], B[]) is lub(A, B)[]
  2755             return new ArrayType(lub(elements), syms.arrayClass);
  2757         case CLASS_BOUND:
  2758             // calculate lub(A, B)
  2759             while (ts.head.tag != CLASS && ts.head.tag != TYPEVAR)
  2760                 ts = ts.tail;
  2761             assert !ts.isEmpty();
  2762             List<Type> cl = closure(ts.head);
  2763             for (Type t : ts.tail) {
  2764                 if (t.tag == CLASS || t.tag == TYPEVAR)
  2765                     cl = intersect(cl, closure(t));
  2767             return compoundMin(cl);
  2769         default:
  2770             // calculate lub(A, B[])
  2771             List<Type> classes = List.of(arraySuperType());
  2772             for (Type t : ts) {
  2773                 if (t.tag != ARRAY) // Filter out any arrays
  2774                     classes = classes.prepend(t);
  2776             // lub(A, B[]) is lub(A, arraySuperType)
  2777             return lub(classes);
  2780     // where
  2781         private Type arraySuperType = null;
  2782         private Type arraySuperType() {
  2783             // initialized lazily to avoid problems during compiler startup
  2784             if (arraySuperType == null) {
  2785                 synchronized (this) {
  2786                     if (arraySuperType == null) {
  2787                         // JLS 10.8: all arrays implement Cloneable and Serializable.
  2788                         arraySuperType = makeCompoundType(List.of(syms.serializableType,
  2789                                                                   syms.cloneableType),
  2790                                                           syms.objectType);
  2794             return arraySuperType;
  2796     // </editor-fold>
  2798     // <editor-fold defaultstate="collapsed" desc="Greatest lower bound">
  2799     public Type glb(List<Type> ts) {
  2800         Type t1 = ts.head;
  2801         for (Type t2 : ts.tail) {
  2802             if (t1.isErroneous())
  2803                 return t1;
  2804             t1 = glb(t1, t2);
  2806         return t1;
  2808     //where
  2809     public Type glb(Type t, Type s) {
  2810         if (s == null)
  2811             return t;
  2812         else if (t.isPrimitive() || s.isPrimitive())
  2813             return syms.errType;
  2814         else if (isSubtypeNoCapture(t, s))
  2815             return t;
  2816         else if (isSubtypeNoCapture(s, t))
  2817             return s;
  2819         List<Type> closure = union(closure(t), closure(s));
  2820         List<Type> bounds = closureMin(closure);
  2822         if (bounds.isEmpty()) {             // length == 0
  2823             return syms.objectType;
  2824         } else if (bounds.tail.isEmpty()) { // length == 1
  2825             return bounds.head;
  2826         } else {                            // length > 1
  2827             int classCount = 0;
  2828             for (Type bound : bounds)
  2829                 if (!bound.isInterface())
  2830                     classCount++;
  2831             if (classCount > 1)
  2832                 return createErrorType(t);
  2834         return makeCompoundType(bounds);
  2836     // </editor-fold>
  2838     // <editor-fold defaultstate="collapsed" desc="hashCode">
  2839     /**
  2840      * Compute a hash code on a type.
  2841      */
  2842     public static int hashCode(Type t) {
  2843         return hashCode.visit(t);
  2845     // where
  2846         private static final UnaryVisitor<Integer> hashCode = new UnaryVisitor<Integer>() {
  2848             public Integer visitType(Type t, Void ignored) {
  2849                 return t.tag;
  2852             @Override
  2853             public Integer visitClassType(ClassType t, Void ignored) {
  2854                 int result = visit(t.getEnclosingType());
  2855                 result *= 127;
  2856                 result += t.tsym.flatName().hashCode();
  2857                 for (Type s : t.getTypeArguments()) {
  2858                     result *= 127;
  2859                     result += visit(s);
  2861                 return result;
  2864             @Override
  2865             public Integer visitWildcardType(WildcardType t, Void ignored) {
  2866                 int result = t.kind.hashCode();
  2867                 if (t.type != null) {
  2868                     result *= 127;
  2869                     result += visit(t.type);
  2871                 return result;
  2874             @Override
  2875             public Integer visitArrayType(ArrayType t, Void ignored) {
  2876                 return visit(t.elemtype) + 12;
  2879             @Override
  2880             public Integer visitTypeVar(TypeVar t, Void ignored) {
  2881                 return System.identityHashCode(t.tsym);
  2884             @Override
  2885             public Integer visitUndetVar(UndetVar t, Void ignored) {
  2886                 return System.identityHashCode(t);
  2889             @Override
  2890             public Integer visitErrorType(ErrorType t, Void ignored) {
  2891                 return 0;
  2893         };
  2894     // </editor-fold>
  2896     // <editor-fold defaultstate="collapsed" desc="Return-Type-Substitutable">
  2897     /**
  2898      * Does t have a result that is a subtype of the result type of s,
  2899      * suitable for covariant returns?  It is assumed that both types
  2900      * are (possibly polymorphic) method types.  Monomorphic method
  2901      * types are handled in the obvious way.  Polymorphic method types
  2902      * require renaming all type variables of one to corresponding
  2903      * type variables in the other, where correspondence is by
  2904      * position in the type parameter list. */
  2905     public boolean resultSubtype(Type t, Type s, Warner warner) {
  2906         List<Type> tvars = t.getTypeArguments();
  2907         List<Type> svars = s.getTypeArguments();
  2908         Type tres = t.getReturnType();
  2909         Type sres = subst(s.getReturnType(), svars, tvars);
  2910         return covariantReturnType(tres, sres, warner);
  2913     /**
  2914      * Return-Type-Substitutable.
  2915      * @see <a href="http://java.sun.com/docs/books/jls/">The Java
  2916      * Language Specification, Third Ed. (8.4.5)</a>
  2917      */
  2918     public boolean returnTypeSubstitutable(Type r1, Type r2) {
  2919         if (hasSameArgs(r1, r2))
  2920             return resultSubtype(r1, r2, Warner.noWarnings);
  2921         else
  2922             return covariantReturnType(r1.getReturnType(),
  2923                                        erasure(r2.getReturnType()),
  2924                                        Warner.noWarnings);
  2927     public boolean returnTypeSubstitutable(Type r1,
  2928                                            Type r2, Type r2res,
  2929                                            Warner warner) {
  2930         if (isSameType(r1.getReturnType(), r2res))
  2931             return true;
  2932         if (r1.getReturnType().isPrimitive() || r2res.isPrimitive())
  2933             return false;
  2935         if (hasSameArgs(r1, r2))
  2936             return covariantReturnType(r1.getReturnType(), r2res, warner);
  2937         if (!source.allowCovariantReturns())
  2938             return false;
  2939         if (isSubtypeUnchecked(r1.getReturnType(), r2res, warner))
  2940             return true;
  2941         if (!isSubtype(r1.getReturnType(), erasure(r2res)))
  2942             return false;
  2943         warner.warn(LintCategory.UNCHECKED);
  2944         return true;
  2947     /**
  2948      * Is t an appropriate return type in an overrider for a
  2949      * method that returns s?
  2950      */
  2951     public boolean covariantReturnType(Type t, Type s, Warner warner) {
  2952         return
  2953             isSameType(t, s) ||
  2954             source.allowCovariantReturns() &&
  2955             !t.isPrimitive() &&
  2956             !s.isPrimitive() &&
  2957             isAssignable(t, s, warner);
  2959     // </editor-fold>
  2961     // <editor-fold defaultstate="collapsed" desc="Box/unbox support">
  2962     /**
  2963      * Return the class that boxes the given primitive.
  2964      */
  2965     public ClassSymbol boxedClass(Type t) {
  2966         return reader.enterClass(syms.boxedName[t.tag]);
  2969     /**
  2970      * Return the boxed type if 't' is primitive, otherwise return 't' itself.
  2971      */
  2972     public Type boxedTypeOrType(Type t) {
  2973         return t.isPrimitive() ?
  2974             boxedClass(t).type :
  2975             t;
  2978     /**
  2979      * Return the primitive type corresponding to a boxed type.
  2980      */
  2981     public Type unboxedType(Type t) {
  2982         if (allowBoxing) {
  2983             for (int i=0; i<syms.boxedName.length; i++) {
  2984                 Name box = syms.boxedName[i];
  2985                 if (box != null &&
  2986                     asSuper(t, reader.enterClass(box)) != null)
  2987                     return syms.typeOfTag[i];
  2990         return Type.noType;
  2992     // </editor-fold>
  2994     // <editor-fold defaultstate="collapsed" desc="Capture conversion">
  2995     /*
  2996      * JLS 3rd Ed. 5.1.10 Capture Conversion:
  2998      * Let G name a generic type declaration with n formal type
  2999      * parameters A1 ... An with corresponding bounds U1 ... Un. There
  3000      * exists a capture conversion from G<T1 ... Tn> to G<S1 ... Sn>,
  3001      * where, for 1 <= i <= n:
  3003      * + If Ti is a wildcard type argument (4.5.1) of the form ? then
  3004      *   Si is a fresh type variable whose upper bound is
  3005      *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is the null
  3006      *   type.
  3008      * + If Ti is a wildcard type argument of the form ? extends Bi,
  3009      *   then Si is a fresh type variable whose upper bound is
  3010      *   glb(Bi, Ui[A1 := S1, ..., An := Sn]) and whose lower bound is
  3011      *   the null type, where glb(V1,... ,Vm) is V1 & ... & Vm. It is
  3012      *   a compile-time error if for any two classes (not interfaces)
  3013      *   Vi and Vj,Vi is not a subclass of Vj or vice versa.
  3015      * + If Ti is a wildcard type argument of the form ? super Bi,
  3016      *   then Si is a fresh type variable whose upper bound is
  3017      *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is Bi.
  3019      * + Otherwise, Si = Ti.
  3021      * Capture conversion on any type other than a parameterized type
  3022      * (4.5) acts as an identity conversion (5.1.1). Capture
  3023      * conversions never require a special action at run time and
  3024      * therefore never throw an exception at run time.
  3026      * Capture conversion is not applied recursively.
  3027      */
  3028     /**
  3029      * Capture conversion as specified by JLS 3rd Ed.
  3030      */
  3032     public List<Type> capture(List<Type> ts) {
  3033         List<Type> buf = List.nil();
  3034         for (Type t : ts) {
  3035             buf = buf.prepend(capture(t));
  3037         return buf.reverse();
  3039     public Type capture(Type t) {
  3040         if (t.tag != CLASS)
  3041             return t;
  3042         if (t.getEnclosingType() != Type.noType) {
  3043             Type capturedEncl = capture(t.getEnclosingType());
  3044             if (capturedEncl != t.getEnclosingType()) {
  3045                 Type type1 = memberType(capturedEncl, t.tsym);
  3046                 t = subst(type1, t.tsym.type.getTypeArguments(), t.getTypeArguments());
  3049         ClassType cls = (ClassType)t;
  3050         if (cls.isRaw() || !cls.isParameterized())
  3051             return cls;
  3053         ClassType G = (ClassType)cls.asElement().asType();
  3054         List<Type> A = G.getTypeArguments();
  3055         List<Type> T = cls.getTypeArguments();
  3056         List<Type> S = freshTypeVariables(T);
  3058         List<Type> currentA = A;
  3059         List<Type> currentT = T;
  3060         List<Type> currentS = S;
  3061         boolean captured = false;
  3062         while (!currentA.isEmpty() &&
  3063                !currentT.isEmpty() &&
  3064                !currentS.isEmpty()) {
  3065             if (currentS.head != currentT.head) {
  3066                 captured = true;
  3067                 WildcardType Ti = (WildcardType)currentT.head;
  3068                 Type Ui = currentA.head.getUpperBound();
  3069                 CapturedType Si = (CapturedType)currentS.head;
  3070                 if (Ui == null)
  3071                     Ui = syms.objectType;
  3072                 switch (Ti.kind) {
  3073                 case UNBOUND:
  3074                     Si.bound = subst(Ui, A, S);
  3075                     Si.lower = syms.botType;
  3076                     break;
  3077                 case EXTENDS:
  3078                     Si.bound = glb(Ti.getExtendsBound(), subst(Ui, A, S));
  3079                     Si.lower = syms.botType;
  3080                     break;
  3081                 case SUPER:
  3082                     Si.bound = subst(Ui, A, S);
  3083                     Si.lower = Ti.getSuperBound();
  3084                     break;
  3086                 if (Si.bound == Si.lower)
  3087                     currentS.head = Si.bound;
  3089             currentA = currentA.tail;
  3090             currentT = currentT.tail;
  3091             currentS = currentS.tail;
  3093         if (!currentA.isEmpty() || !currentT.isEmpty() || !currentS.isEmpty())
  3094             return erasure(t); // some "rare" type involved
  3096         if (captured)
  3097             return new ClassType(cls.getEnclosingType(), S, cls.tsym);
  3098         else
  3099             return t;
  3101     // where
  3102         public List<Type> freshTypeVariables(List<Type> types) {
  3103             ListBuffer<Type> result = lb();
  3104             for (Type t : types) {
  3105                 if (t.tag == WILDCARD) {
  3106                     Type bound = ((WildcardType)t).getExtendsBound();
  3107                     if (bound == null)
  3108                         bound = syms.objectType;
  3109                     result.append(new CapturedType(capturedName,
  3110                                                    syms.noSymbol,
  3111                                                    bound,
  3112                                                    syms.botType,
  3113                                                    (WildcardType)t));
  3114                 } else {
  3115                     result.append(t);
  3118             return result.toList();
  3120     // </editor-fold>
  3122     // <editor-fold defaultstate="collapsed" desc="Internal utility methods">
  3123     private List<Type> upperBounds(List<Type> ss) {
  3124         if (ss.isEmpty()) return ss;
  3125         Type head = upperBound(ss.head);
  3126         List<Type> tail = upperBounds(ss.tail);
  3127         if (head != ss.head || tail != ss.tail)
  3128             return tail.prepend(head);
  3129         else
  3130             return ss;
  3133     private boolean sideCast(Type from, Type to, Warner warn) {
  3134         // We are casting from type $from$ to type $to$, which are
  3135         // non-final unrelated types.  This method
  3136         // tries to reject a cast by transferring type parameters
  3137         // from $to$ to $from$ by common superinterfaces.
  3138         boolean reverse = false;
  3139         Type target = to;
  3140         if ((to.tsym.flags() & INTERFACE) == 0) {
  3141             assert (from.tsym.flags() & INTERFACE) != 0;
  3142             reverse = true;
  3143             to = from;
  3144             from = target;
  3146         List<Type> commonSupers = superClosure(to, erasure(from));
  3147         boolean giveWarning = commonSupers.isEmpty();
  3148         // The arguments to the supers could be unified here to
  3149         // get a more accurate analysis
  3150         while (commonSupers.nonEmpty()) {
  3151             Type t1 = asSuper(from, commonSupers.head.tsym);
  3152             Type t2 = commonSupers.head; // same as asSuper(to, commonSupers.head.tsym);
  3153             if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
  3154                 return false;
  3155             giveWarning = giveWarning || (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2));
  3156             commonSupers = commonSupers.tail;
  3158         if (giveWarning && !isReifiable(reverse ? from : to))
  3159             warn.warn(LintCategory.UNCHECKED);
  3160         if (!source.allowCovariantReturns())
  3161             // reject if there is a common method signature with
  3162             // incompatible return types.
  3163             chk.checkCompatibleAbstracts(warn.pos(), from, to);
  3164         return true;
  3167     private boolean sideCastFinal(Type from, Type to, Warner warn) {
  3168         // We are casting from type $from$ to type $to$, which are
  3169         // unrelated types one of which is final and the other of
  3170         // which is an interface.  This method
  3171         // tries to reject a cast by transferring type parameters
  3172         // from the final class to the interface.
  3173         boolean reverse = false;
  3174         Type target = to;
  3175         if ((to.tsym.flags() & INTERFACE) == 0) {
  3176             assert (from.tsym.flags() & INTERFACE) != 0;
  3177             reverse = true;
  3178             to = from;
  3179             from = target;
  3181         assert (from.tsym.flags() & FINAL) != 0;
  3182         Type t1 = asSuper(from, to.tsym);
  3183         if (t1 == null) return false;
  3184         Type t2 = to;
  3185         if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
  3186             return false;
  3187         if (!source.allowCovariantReturns())
  3188             // reject if there is a common method signature with
  3189             // incompatible return types.
  3190             chk.checkCompatibleAbstracts(warn.pos(), from, to);
  3191         if (!isReifiable(target) &&
  3192             (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2)))
  3193             warn.warn(LintCategory.UNCHECKED);
  3194         return true;
  3197     private boolean giveWarning(Type from, Type to) {
  3198         Type subFrom = asSub(from, to.tsym);
  3199         return to.isParameterized() &&
  3200                 (!(isUnbounded(to) ||
  3201                 isSubtype(from, to) ||
  3202                 ((subFrom != null) && containsType(to.allparams(), subFrom.allparams()))));
  3205     private List<Type> superClosure(Type t, Type s) {
  3206         List<Type> cl = List.nil();
  3207         for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
  3208             if (isSubtype(s, erasure(l.head))) {
  3209                 cl = insert(cl, l.head);
  3210             } else {
  3211                 cl = union(cl, superClosure(l.head, s));
  3214         return cl;
  3217     private boolean containsTypeEquivalent(Type t, Type s) {
  3218         return
  3219             isSameType(t, s) || // shortcut
  3220             containsType(t, s) && containsType(s, t);
  3223     // <editor-fold defaultstate="collapsed" desc="adapt">
  3224     /**
  3225      * Adapt a type by computing a substitution which maps a source
  3226      * type to a target type.
  3228      * @param source    the source type
  3229      * @param target    the target type
  3230      * @param from      the type variables of the computed substitution
  3231      * @param to        the types of the computed substitution.
  3232      */
  3233     public void adapt(Type source,
  3234                        Type target,
  3235                        ListBuffer<Type> from,
  3236                        ListBuffer<Type> to) throws AdaptFailure {
  3237         new Adapter(from, to).adapt(source, target);
  3240     class Adapter extends SimpleVisitor<Void, Type> {
  3242         ListBuffer<Type> from;
  3243         ListBuffer<Type> to;
  3244         Map<Symbol,Type> mapping;
  3246         Adapter(ListBuffer<Type> from, ListBuffer<Type> to) {
  3247             this.from = from;
  3248             this.to = to;
  3249             mapping = new HashMap<Symbol,Type>();
  3252         public void adapt(Type source, Type target) throws AdaptFailure {
  3253             visit(source, target);
  3254             List<Type> fromList = from.toList();
  3255             List<Type> toList = to.toList();
  3256             while (!fromList.isEmpty()) {
  3257                 Type val = mapping.get(fromList.head.tsym);
  3258                 if (toList.head != val)
  3259                     toList.head = val;
  3260                 fromList = fromList.tail;
  3261                 toList = toList.tail;
  3265         @Override
  3266         public Void visitClassType(ClassType source, Type target) throws AdaptFailure {
  3267             if (target.tag == CLASS)
  3268                 adaptRecursive(source.allparams(), target.allparams());
  3269             return null;
  3272         @Override
  3273         public Void visitArrayType(ArrayType source, Type target) throws AdaptFailure {
  3274             if (target.tag == ARRAY)
  3275                 adaptRecursive(elemtype(source), elemtype(target));
  3276             return null;
  3279         @Override
  3280         public Void visitWildcardType(WildcardType source, Type target) throws AdaptFailure {
  3281             if (source.isExtendsBound())
  3282                 adaptRecursive(upperBound(source), upperBound(target));
  3283             else if (source.isSuperBound())
  3284                 adaptRecursive(lowerBound(source), lowerBound(target));
  3285             return null;
  3288         @Override
  3289         public Void visitTypeVar(TypeVar source, Type target) throws AdaptFailure {
  3290             // Check to see if there is
  3291             // already a mapping for $source$, in which case
  3292             // the old mapping will be merged with the new
  3293             Type val = mapping.get(source.tsym);
  3294             if (val != null) {
  3295                 if (val.isSuperBound() && target.isSuperBound()) {
  3296                     val = isSubtype(lowerBound(val), lowerBound(target))
  3297                         ? target : val;
  3298                 } else if (val.isExtendsBound() && target.isExtendsBound()) {
  3299                     val = isSubtype(upperBound(val), upperBound(target))
  3300                         ? val : target;
  3301                 } else if (!isSameType(val, target)) {
  3302                     throw new AdaptFailure();
  3304             } else {
  3305                 val = target;
  3306                 from.append(source);
  3307                 to.append(target);
  3309             mapping.put(source.tsym, val);
  3310             return null;
  3313         @Override
  3314         public Void visitType(Type source, Type target) {
  3315             return null;
  3318         private Set<TypePair> cache = new HashSet<TypePair>();
  3320         private void adaptRecursive(Type source, Type target) {
  3321             TypePair pair = new TypePair(source, target);
  3322             if (cache.add(pair)) {
  3323                 try {
  3324                     visit(source, target);
  3325                 } finally {
  3326                     cache.remove(pair);
  3331         private void adaptRecursive(List<Type> source, List<Type> target) {
  3332             if (source.length() == target.length()) {
  3333                 while (source.nonEmpty()) {
  3334                     adaptRecursive(source.head, target.head);
  3335                     source = source.tail;
  3336                     target = target.tail;
  3342     public static class AdaptFailure extends RuntimeException {
  3343         static final long serialVersionUID = -7490231548272701566L;
  3346     private void adaptSelf(Type t,
  3347                            ListBuffer<Type> from,
  3348                            ListBuffer<Type> to) {
  3349         try {
  3350             //if (t.tsym.type != t)
  3351                 adapt(t.tsym.type, t, from, to);
  3352         } catch (AdaptFailure ex) {
  3353             // Adapt should never fail calculating a mapping from
  3354             // t.tsym.type to t as there can be no merge problem.
  3355             throw new AssertionError(ex);
  3358     // </editor-fold>
  3360     /**
  3361      * Rewrite all type variables (universal quantifiers) in the given
  3362      * type to wildcards (existential quantifiers).  This is used to
  3363      * determine if a cast is allowed.  For example, if high is true
  3364      * and {@code T <: Number}, then {@code List<T>} is rewritten to
  3365      * {@code List<?  extends Number>}.  Since {@code List<Integer> <:
  3366      * List<? extends Number>} a {@code List<T>} can be cast to {@code
  3367      * List<Integer>} with a warning.
  3368      * @param t a type
  3369      * @param high if true return an upper bound; otherwise a lower
  3370      * bound
  3371      * @param rewriteTypeVars only rewrite captured wildcards if false;
  3372      * otherwise rewrite all type variables
  3373      * @return the type rewritten with wildcards (existential
  3374      * quantifiers) only
  3375      */
  3376     private Type rewriteQuantifiers(Type t, boolean high, boolean rewriteTypeVars) {
  3377         return new Rewriter(high, rewriteTypeVars).visit(t);
  3380     class Rewriter extends UnaryVisitor<Type> {
  3382         boolean high;
  3383         boolean rewriteTypeVars;
  3385         Rewriter(boolean high, boolean rewriteTypeVars) {
  3386             this.high = high;
  3387             this.rewriteTypeVars = rewriteTypeVars;
  3390         @Override
  3391         public Type visitClassType(ClassType t, Void s) {
  3392             ListBuffer<Type> rewritten = new ListBuffer<Type>();
  3393             boolean changed = false;
  3394             for (Type arg : t.allparams()) {
  3395                 Type bound = visit(arg);
  3396                 if (arg != bound) {
  3397                     changed = true;
  3399                 rewritten.append(bound);
  3401             if (changed)
  3402                 return subst(t.tsym.type,
  3403                         t.tsym.type.allparams(),
  3404                         rewritten.toList());
  3405             else
  3406                 return t;
  3409         public Type visitType(Type t, Void s) {
  3410             return high ? upperBound(t) : lowerBound(t);
  3413         @Override
  3414         public Type visitCapturedType(CapturedType t, Void s) {
  3415             Type bound = visitWildcardType(t.wildcard, null);
  3416             return (bound.contains(t)) ?
  3417                     erasure(bound) :
  3418                     bound;
  3421         @Override
  3422         public Type visitTypeVar(TypeVar t, Void s) {
  3423             if (rewriteTypeVars) {
  3424                 Type bound = high ?
  3425                     (t.bound.contains(t) ?
  3426                         erasure(t.bound) :
  3427                         visit(t.bound)) :
  3428                     syms.botType;
  3429                 return rewriteAsWildcardType(bound, t);
  3431             else
  3432                 return t;
  3435         @Override
  3436         public Type visitWildcardType(WildcardType t, Void s) {
  3437             Type bound = high ? t.getExtendsBound() :
  3438                                 t.getSuperBound();
  3439             if (bound == null)
  3440             bound = high ? syms.objectType : syms.botType;
  3441             return rewriteAsWildcardType(visit(bound), t.bound);
  3444         private Type rewriteAsWildcardType(Type bound, TypeVar formal) {
  3445             return high ?
  3446                 makeExtendsWildcard(B(bound), formal) :
  3447                 makeSuperWildcard(B(bound), formal);
  3450         Type B(Type t) {
  3451             while (t.tag == WILDCARD) {
  3452                 WildcardType w = (WildcardType)t;
  3453                 t = high ?
  3454                     w.getExtendsBound() :
  3455                     w.getSuperBound();
  3456                 if (t == null) {
  3457                     t = high ? syms.objectType : syms.botType;
  3460             return t;
  3465     /**
  3466      * Create a wildcard with the given upper (extends) bound; create
  3467      * an unbounded wildcard if bound is Object.
  3469      * @param bound the upper bound
  3470      * @param formal the formal type parameter that will be
  3471      * substituted by the wildcard
  3472      */
  3473     private WildcardType makeExtendsWildcard(Type bound, TypeVar formal) {
  3474         if (bound == syms.objectType) {
  3475             return new WildcardType(syms.objectType,
  3476                                     BoundKind.UNBOUND,
  3477                                     syms.boundClass,
  3478                                     formal);
  3479         } else {
  3480             return new WildcardType(bound,
  3481                                     BoundKind.EXTENDS,
  3482                                     syms.boundClass,
  3483                                     formal);
  3487     /**
  3488      * Create a wildcard with the given lower (super) bound; create an
  3489      * unbounded wildcard if bound is bottom (type of {@code null}).
  3491      * @param bound the lower bound
  3492      * @param formal the formal type parameter that will be
  3493      * substituted by the wildcard
  3494      */
  3495     private WildcardType makeSuperWildcard(Type bound, TypeVar formal) {
  3496         if (bound.tag == BOT) {
  3497             return new WildcardType(syms.objectType,
  3498                                     BoundKind.UNBOUND,
  3499                                     syms.boundClass,
  3500                                     formal);
  3501         } else {
  3502             return new WildcardType(bound,
  3503                                     BoundKind.SUPER,
  3504                                     syms.boundClass,
  3505                                     formal);
  3509     /**
  3510      * A wrapper for a type that allows use in sets.
  3511      */
  3512     class SingletonType {
  3513         final Type t;
  3514         SingletonType(Type t) {
  3515             this.t = t;
  3517         public int hashCode() {
  3518             return Types.hashCode(t);
  3520         public boolean equals(Object obj) {
  3521             return (obj instanceof SingletonType) &&
  3522                 isSameType(t, ((SingletonType)obj).t);
  3524         public String toString() {
  3525             return t.toString();
  3528     // </editor-fold>
  3530     // <editor-fold defaultstate="collapsed" desc="Visitors">
  3531     /**
  3532      * A default visitor for types.  All visitor methods except
  3533      * visitType are implemented by delegating to visitType.  Concrete
  3534      * subclasses must provide an implementation of visitType and can
  3535      * override other methods as needed.
  3537      * @param <R> the return type of the operation implemented by this
  3538      * visitor; use Void if no return type is needed.
  3539      * @param <S> the type of the second argument (the first being the
  3540      * type itself) of the operation implemented by this visitor; use
  3541      * Void if a second argument is not needed.
  3542      */
  3543     public static abstract class DefaultTypeVisitor<R,S> implements Type.Visitor<R,S> {
  3544         final public R visit(Type t, S s)               { return t.accept(this, s); }
  3545         public R visitClassType(ClassType t, S s)       { return visitType(t, s); }
  3546         public R visitWildcardType(WildcardType t, S s) { return visitType(t, s); }
  3547         public R visitArrayType(ArrayType t, S s)       { return visitType(t, s); }
  3548         public R visitMethodType(MethodType t, S s)     { return visitType(t, s); }
  3549         public R visitPackageType(PackageType t, S s)   { return visitType(t, s); }
  3550         public R visitTypeVar(TypeVar t, S s)           { return visitType(t, s); }
  3551         public R visitCapturedType(CapturedType t, S s) { return visitType(t, s); }
  3552         public R visitForAll(ForAll t, S s)             { return visitType(t, s); }
  3553         public R visitUndetVar(UndetVar t, S s)         { return visitType(t, s); }
  3554         public R visitErrorType(ErrorType t, S s)       { return visitType(t, s); }
  3557     /**
  3558      * A default visitor for symbols.  All visitor methods except
  3559      * visitSymbol are implemented by delegating to visitSymbol.  Concrete
  3560      * subclasses must provide an implementation of visitSymbol and can
  3561      * override other methods as needed.
  3563      * @param <R> the return type of the operation implemented by this
  3564      * visitor; use Void if no return type is needed.
  3565      * @param <S> the type of the second argument (the first being the
  3566      * symbol itself) of the operation implemented by this visitor; use
  3567      * Void if a second argument is not needed.
  3568      */
  3569     public static abstract class DefaultSymbolVisitor<R,S> implements Symbol.Visitor<R,S> {
  3570         final public R visit(Symbol s, S arg)                   { return s.accept(this, arg); }
  3571         public R visitClassSymbol(ClassSymbol s, S arg)         { return visitSymbol(s, arg); }
  3572         public R visitMethodSymbol(MethodSymbol s, S arg)       { return visitSymbol(s, arg); }
  3573         public R visitOperatorSymbol(OperatorSymbol s, S arg)   { return visitSymbol(s, arg); }
  3574         public R visitPackageSymbol(PackageSymbol s, S arg)     { return visitSymbol(s, arg); }
  3575         public R visitTypeSymbol(TypeSymbol s, S arg)           { return visitSymbol(s, arg); }
  3576         public R visitVarSymbol(VarSymbol s, S arg)             { return visitSymbol(s, arg); }
  3579     /**
  3580      * A <em>simple</em> visitor for types.  This visitor is simple as
  3581      * captured wildcards, for-all types (generic methods), and
  3582      * undetermined type variables (part of inference) are hidden.
  3583      * Captured wildcards are hidden by treating them as type
  3584      * variables and the rest are hidden by visiting their qtypes.
  3586      * @param <R> the return type of the operation implemented by this
  3587      * visitor; use Void if no return type is needed.
  3588      * @param <S> the type of the second argument (the first being the
  3589      * type itself) of the operation implemented by this visitor; use
  3590      * Void if a second argument is not needed.
  3591      */
  3592     public static abstract class SimpleVisitor<R,S> extends DefaultTypeVisitor<R,S> {
  3593         @Override
  3594         public R visitCapturedType(CapturedType t, S s) {
  3595             return visitTypeVar(t, s);
  3597         @Override
  3598         public R visitForAll(ForAll t, S s) {
  3599             return visit(t.qtype, s);
  3601         @Override
  3602         public R visitUndetVar(UndetVar t, S s) {
  3603             return visit(t.qtype, s);
  3607     /**
  3608      * A plain relation on types.  That is a 2-ary function on the
  3609      * form Type&nbsp;&times;&nbsp;Type&nbsp;&rarr;&nbsp;Boolean.
  3610      * <!-- In plain text: Type x Type -> Boolean -->
  3611      */
  3612     public static abstract class TypeRelation extends SimpleVisitor<Boolean,Type> {}
  3614     /**
  3615      * A convenience visitor for implementing operations that only
  3616      * require one argument (the type itself), that is, unary
  3617      * operations.
  3619      * @param <R> the return type of the operation implemented by this
  3620      * visitor; use Void if no return type is needed.
  3621      */
  3622     public static abstract class UnaryVisitor<R> extends SimpleVisitor<R,Void> {
  3623         final public R visit(Type t) { return t.accept(this, null); }
  3626     /**
  3627      * A visitor for implementing a mapping from types to types.  The
  3628      * default behavior of this class is to implement the identity
  3629      * mapping (mapping a type to itself).  This can be overridden in
  3630      * subclasses.
  3632      * @param <S> the type of the second argument (the first being the
  3633      * type itself) of this mapping; use Void if a second argument is
  3634      * not needed.
  3635      */
  3636     public static class MapVisitor<S> extends DefaultTypeVisitor<Type,S> {
  3637         final public Type visit(Type t) { return t.accept(this, null); }
  3638         public Type visitType(Type t, S s) { return t; }
  3640     // </editor-fold>
  3643     // <editor-fold defaultstate="collapsed" desc="Annotation support">
  3645     public RetentionPolicy getRetention(Attribute.Compound a) {
  3646         RetentionPolicy vis = RetentionPolicy.CLASS; // the default
  3647         Attribute.Compound c = a.type.tsym.attribute(syms.retentionType.tsym);
  3648         if (c != null) {
  3649             Attribute value = c.member(names.value);
  3650             if (value != null && value instanceof Attribute.Enum) {
  3651                 Name levelName = ((Attribute.Enum)value).value.name;
  3652                 if (levelName == names.SOURCE) vis = RetentionPolicy.SOURCE;
  3653                 else if (levelName == names.CLASS) vis = RetentionPolicy.CLASS;
  3654                 else if (levelName == names.RUNTIME) vis = RetentionPolicy.RUNTIME;
  3655                 else ;// /* fail soft */ throw new AssertionError(levelName);
  3658         return vis;
  3660     // </editor-fold>

mercurial