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

Thu, 25 Oct 2012 11:09:36 -0700

author
jjg
date
Thu, 25 Oct 2012 11:09:36 -0700
changeset 1374
c002fdee76fd
parent 1358
fc123bdeddb8
child 1393
d7d932236fee
permissions
-rw-r--r--

7200915: convert TypeTags from a series of small ints to an enum
Reviewed-by: jjg, mcimadamore
Contributed-by: vicente.romero@oracle.com

     1 /*
     2  * Copyright (c) 2003, 2012, 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.code.Attribute.RetentionPolicy;
    32 import com.sun.tools.javac.code.Lint.LintCategory;
    33 import com.sun.tools.javac.code.Type.UndetVar.InferenceBound;
    34 import com.sun.tools.javac.comp.Check;
    35 import com.sun.tools.javac.jvm.ClassReader;
    36 import com.sun.tools.javac.util.*;
    37 import com.sun.tools.javac.util.List;
    38 import static com.sun.tools.javac.code.BoundKind.*;
    39 import static com.sun.tools.javac.code.Flags.*;
    40 import static com.sun.tools.javac.code.Scope.*;
    41 import static com.sun.tools.javac.code.Symbol.*;
    42 import static com.sun.tools.javac.code.Type.*;
    43 import static com.sun.tools.javac.code.TypeTag.*;
    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 JavacMessages messages;
    74     final Names names;
    75     final boolean allowBoxing;
    76     final boolean allowCovariantReturns;
    77     final boolean allowObjectToPrimitiveCast;
    78     final ClassReader reader;
    79     final Check chk;
    80     JCDiagnostic.Factory diags;
    81     List<Warner> warnStack = List.nil();
    82     final Name capturedName;
    83     private final FunctionDescriptorLookupError functionDescriptorLookupError;
    85     // <editor-fold defaultstate="collapsed" desc="Instantiating">
    86     public static Types instance(Context context) {
    87         Types instance = context.get(typesKey);
    88         if (instance == null)
    89             instance = new Types(context);
    90         return instance;
    91     }
    93     protected Types(Context context) {
    94         context.put(typesKey, this);
    95         syms = Symtab.instance(context);
    96         names = Names.instance(context);
    97         Source source = Source.instance(context);
    98         allowBoxing = source.allowBoxing();
    99         allowCovariantReturns = source.allowCovariantReturns();
   100         allowObjectToPrimitiveCast = source.allowObjectToPrimitiveCast();
   101         reader = ClassReader.instance(context);
   102         chk = Check.instance(context);
   103         capturedName = names.fromString("<captured wildcard>");
   104         messages = JavacMessages.instance(context);
   105         diags = JCDiagnostic.Factory.instance(context);
   106         functionDescriptorLookupError = new FunctionDescriptorLookupError();
   107     }
   108     // </editor-fold>
   110     // <editor-fold defaultstate="collapsed" desc="upperBound">
   111     /**
   112      * The "rvalue conversion".<br>
   113      * The upper bound of most types is the type
   114      * itself.  Wildcards, on the other hand have upper
   115      * and lower bounds.
   116      * @param t a type
   117      * @return the upper bound of the given type
   118      */
   119     public Type upperBound(Type t) {
   120         return upperBound.visit(t);
   121     }
   122     // where
   123         private final MapVisitor<Void> upperBound = new MapVisitor<Void>() {
   125             @Override
   126             public Type visitWildcardType(WildcardType t, Void ignored) {
   127                 if (t.isSuperBound())
   128                     return t.bound == null ? syms.objectType : t.bound.bound;
   129                 else
   130                     return visit(t.type);
   131             }
   133             @Override
   134             public Type visitCapturedType(CapturedType t, Void ignored) {
   135                 return visit(t.bound);
   136             }
   137         };
   138     // </editor-fold>
   140     // <editor-fold defaultstate="collapsed" desc="lowerBound">
   141     /**
   142      * The "lvalue conversion".<br>
   143      * The lower bound of most types is the type
   144      * itself.  Wildcards, on the other hand have upper
   145      * and lower bounds.
   146      * @param t a type
   147      * @return the lower bound of the given type
   148      */
   149     public Type lowerBound(Type t) {
   150         return lowerBound.visit(t);
   151     }
   152     // where
   153         private final MapVisitor<Void> lowerBound = new MapVisitor<Void>() {
   155             @Override
   156             public Type visitWildcardType(WildcardType t, Void ignored) {
   157                 return t.isExtendsBound() ? syms.botType : visit(t.type);
   158             }
   160             @Override
   161             public Type visitCapturedType(CapturedType t, Void ignored) {
   162                 return visit(t.getLowerBound());
   163             }
   164         };
   165     // </editor-fold>
   167     // <editor-fold defaultstate="collapsed" desc="isUnbounded">
   168     /**
   169      * Checks that all the arguments to a class are unbounded
   170      * wildcards or something else that doesn't make any restrictions
   171      * on the arguments. If a class isUnbounded, a raw super- or
   172      * subclass can be cast to it without a warning.
   173      * @param t a type
   174      * @return true iff the given type is unbounded or raw
   175      */
   176     public boolean isUnbounded(Type t) {
   177         return isUnbounded.visit(t);
   178     }
   179     // where
   180         private final UnaryVisitor<Boolean> isUnbounded = new UnaryVisitor<Boolean>() {
   182             public Boolean visitType(Type t, Void ignored) {
   183                 return true;
   184             }
   186             @Override
   187             public Boolean visitClassType(ClassType t, Void ignored) {
   188                 List<Type> parms = t.tsym.type.allparams();
   189                 List<Type> args = t.allparams();
   190                 while (parms.nonEmpty()) {
   191                     WildcardType unb = new WildcardType(syms.objectType,
   192                                                         BoundKind.UNBOUND,
   193                                                         syms.boundClass,
   194                                                         (TypeVar)parms.head);
   195                     if (!containsType(args.head, unb))
   196                         return false;
   197                     parms = parms.tail;
   198                     args = args.tail;
   199                 }
   200                 return true;
   201             }
   202         };
   203     // </editor-fold>
   205     // <editor-fold defaultstate="collapsed" desc="asSub">
   206     /**
   207      * Return the least specific subtype of t that starts with symbol
   208      * sym.  If none exists, return null.  The least specific subtype
   209      * is determined as follows:
   210      *
   211      * <p>If there is exactly one parameterized instance of sym that is a
   212      * subtype of t, that parameterized instance is returned.<br>
   213      * Otherwise, if the plain type or raw type `sym' is a subtype of
   214      * type t, the type `sym' itself is returned.  Otherwise, null is
   215      * returned.
   216      */
   217     public Type asSub(Type t, Symbol sym) {
   218         return asSub.visit(t, sym);
   219     }
   220     // where
   221         private final SimpleVisitor<Type,Symbol> asSub = new SimpleVisitor<Type,Symbol>() {
   223             public Type visitType(Type t, Symbol sym) {
   224                 return null;
   225             }
   227             @Override
   228             public Type visitClassType(ClassType t, Symbol sym) {
   229                 if (t.tsym == sym)
   230                     return t;
   231                 Type base = asSuper(sym.type, t.tsym);
   232                 if (base == null)
   233                     return null;
   234                 ListBuffer<Type> from = new ListBuffer<Type>();
   235                 ListBuffer<Type> to = new ListBuffer<Type>();
   236                 try {
   237                     adapt(base, t, from, to);
   238                 } catch (AdaptFailure ex) {
   239                     return null;
   240                 }
   241                 Type res = subst(sym.type, from.toList(), to.toList());
   242                 if (!isSubtype(res, t))
   243                     return null;
   244                 ListBuffer<Type> openVars = new ListBuffer<Type>();
   245                 for (List<Type> l = sym.type.allparams();
   246                      l.nonEmpty(); l = l.tail)
   247                     if (res.contains(l.head) && !t.contains(l.head))
   248                         openVars.append(l.head);
   249                 if (openVars.nonEmpty()) {
   250                     if (t.isRaw()) {
   251                         // The subtype of a raw type is raw
   252                         res = erasure(res);
   253                     } else {
   254                         // Unbound type arguments default to ?
   255                         List<Type> opens = openVars.toList();
   256                         ListBuffer<Type> qs = new ListBuffer<Type>();
   257                         for (List<Type> iter = opens; iter.nonEmpty(); iter = iter.tail) {
   258                             qs.append(new WildcardType(syms.objectType, BoundKind.UNBOUND, syms.boundClass, (TypeVar) iter.head));
   259                         }
   260                         res = subst(res, opens, qs.toList());
   261                     }
   262                 }
   263                 return res;
   264             }
   266             @Override
   267             public Type visitErrorType(ErrorType t, Symbol sym) {
   268                 return t;
   269             }
   270         };
   271     // </editor-fold>
   273     // <editor-fold defaultstate="collapsed" desc="isConvertible">
   274     /**
   275      * Is t a subtype of or convertible via boxing/unboxing
   276      * conversion to s?
   277      */
   278     public boolean isConvertible(Type t, Type s, Warner warn) {
   279         if (t.tag == ERROR)
   280             return true;
   281         boolean tPrimitive = t.isPrimitive();
   282         boolean sPrimitive = s.isPrimitive();
   283         if (tPrimitive == sPrimitive) {
   284             return isSubtypeUnchecked(t, s, warn);
   285         }
   286         if (!allowBoxing) return false;
   287         return tPrimitive
   288             ? isSubtype(boxedClass(t).type, s)
   289             : isSubtype(unboxedType(t), s);
   290     }
   292     /**
   293      * Is t a subtype of or convertiable via boxing/unboxing
   294      * convertions to s?
   295      */
   296     public boolean isConvertible(Type t, Type s) {
   297         return isConvertible(t, s, Warner.noWarnings);
   298     }
   299     // </editor-fold>
   301     // <editor-fold defaultstate="collapsed" desc="findSam">
   303     /**
   304      * Exception used to report a function descriptor lookup failure. The exception
   305      * wraps a diagnostic that can be used to generate more details error
   306      * messages.
   307      */
   308     public static class FunctionDescriptorLookupError extends RuntimeException {
   309         private static final long serialVersionUID = 0;
   311         JCDiagnostic diagnostic;
   313         FunctionDescriptorLookupError() {
   314             this.diagnostic = null;
   315         }
   317         FunctionDescriptorLookupError setMessage(JCDiagnostic diag) {
   318             this.diagnostic = diag;
   319             return this;
   320         }
   322         public JCDiagnostic getDiagnostic() {
   323             return diagnostic;
   324         }
   325     }
   327     /**
   328      * A cache that keeps track of function descriptors associated with given
   329      * functional interfaces.
   330      */
   331     class DescriptorCache {
   333         private WeakHashMap<TypeSymbol, Entry> _map = new WeakHashMap<TypeSymbol, Entry>();
   335         class FunctionDescriptor {
   336             Symbol descSym;
   338             FunctionDescriptor(Symbol descSym) {
   339                 this.descSym = descSym;
   340             }
   342             public Symbol getSymbol() {
   343                 return descSym;
   344             }
   346             public Type getType(Type origin) {
   347                 return memberType(origin, descSym);
   348             }
   349         }
   351         class Entry {
   352             final FunctionDescriptor cachedDescRes;
   353             final int prevMark;
   355             public Entry(FunctionDescriptor cachedDescRes,
   356                     int prevMark) {
   357                 this.cachedDescRes = cachedDescRes;
   358                 this.prevMark = prevMark;
   359             }
   361             boolean matches(int mark) {
   362                 return  this.prevMark == mark;
   363             }
   364         }
   366         FunctionDescriptor get(TypeSymbol origin) throws FunctionDescriptorLookupError {
   367             Entry e = _map.get(origin);
   368             CompoundScope members = membersClosure(origin.type, false);
   369             if (e == null ||
   370                     !e.matches(members.getMark())) {
   371                 FunctionDescriptor descRes = findDescriptorInternal(origin, members);
   372                 _map.put(origin, new Entry(descRes, members.getMark()));
   373                 return descRes;
   374             }
   375             else {
   376                 return e.cachedDescRes;
   377             }
   378         }
   380         /**
   381          * Scope filter used to skip methods that should be ignored during
   382          * function interface conversion (such as methods overridden by
   383          * j.l.Object)
   384          */
   385         class DescriptorFilter implements Filter<Symbol> {
   387             TypeSymbol origin;
   389             DescriptorFilter(TypeSymbol origin) {
   390                 this.origin = origin;
   391             }
   393             @Override
   394             public boolean accepts(Symbol sym) {
   395                     return sym.kind == Kinds.MTH &&
   396                             (sym.flags() & ABSTRACT) != 0 &&
   397                             !overridesObjectMethod(origin, sym) &&
   398                             notOverridden(sym);
   399             }
   401             private boolean notOverridden(Symbol msym) {
   402                 Symbol impl = ((MethodSymbol)msym).implementation(origin, Types.this, false);
   403                 return impl == null || (impl.flags() & ABSTRACT) != 0;
   404             }
   405         };
   407         /**
   408          * Compute the function descriptor associated with a given functional interface
   409          */
   410         public FunctionDescriptor findDescriptorInternal(TypeSymbol origin, CompoundScope membersCache) throws FunctionDescriptorLookupError {
   411             if (!origin.isInterface()) {
   412                 //t must be an interface
   413                 throw failure("not.a.functional.intf");
   414             }
   416             final ListBuffer<Symbol> abstracts = ListBuffer.lb();
   417             for (Symbol sym : membersCache.getElements(new DescriptorFilter(origin))) {
   418                 Type mtype = memberType(origin.type, sym);
   419                 if (abstracts.isEmpty() ||
   420                         (sym.name == abstracts.first().name &&
   421                         overrideEquivalent(mtype, memberType(origin.type, abstracts.first())))) {
   422                     abstracts.append(sym);
   423                 } else {
   424                     //the target method(s) should be the only abstract members of t
   425                     throw failure("not.a.functional.intf.1",
   426                             diags.fragment("incompatible.abstracts", Kinds.kindName(origin), origin));
   427                 }
   428             }
   429             if (abstracts.isEmpty()) {
   430                 //t must define a suitable non-generic method
   431                 throw failure("not.a.functional.intf.1",
   432                             diags.fragment("no.abstracts", Kinds.kindName(origin), origin));
   433             } else if (abstracts.size() == 1) {
   434                 if (abstracts.first().type.tag == FORALL) {
   435                     throw failure("invalid.generic.desc.in.functional.intf",
   436                             abstracts.first(),
   437                             Kinds.kindName(origin),
   438                             origin);
   439                 } else {
   440                     return new FunctionDescriptor(abstracts.first());
   441                 }
   442             } else { // size > 1
   443                 for (Symbol msym : abstracts) {
   444                     if (msym.type.tag == FORALL) {
   445                         throw failure("invalid.generic.desc.in.functional.intf",
   446                                 abstracts.first(),
   447                                 Kinds.kindName(origin),
   448                                 origin);
   449                     }
   450                 }
   451                 FunctionDescriptor descRes = mergeDescriptors(origin, abstracts.toList());
   452                 if (descRes == null) {
   453                     //we can get here if the functional interface is ill-formed
   454                     ListBuffer<JCDiagnostic> descriptors = ListBuffer.lb();
   455                     for (Symbol desc : abstracts) {
   456                         String key = desc.type.getThrownTypes().nonEmpty() ?
   457                                 "descriptor.throws" : "descriptor";
   458                         descriptors.append(diags.fragment(key, desc.name,
   459                                 desc.type.getParameterTypes(),
   460                                 desc.type.getReturnType(),
   461                                 desc.type.getThrownTypes()));
   462                     }
   463                     JCDiagnostic.MultilineDiagnostic incompatibleDescriptors =
   464                             new JCDiagnostic.MultilineDiagnostic(diags.fragment("incompatible.descs.in.functional.intf",
   465                             Kinds.kindName(origin), origin), descriptors.toList());
   466                     throw failure(incompatibleDescriptors);
   467                 }
   468                 return descRes;
   469             }
   470         }
   472         /**
   473          * Compute a synthetic type for the target descriptor given a list
   474          * of override-equivalent methods in the functional interface type.
   475          * The resulting method type is a method type that is override-equivalent
   476          * and return-type substitutable with each method in the original list.
   477          */
   478         private FunctionDescriptor mergeDescriptors(TypeSymbol origin, List<Symbol> methodSyms) {
   479             //pick argument types - simply take the signature that is a
   480             //subsignature of all other signatures in the list (as per JLS 8.4.2)
   481             List<Symbol> mostSpecific = List.nil();
   482             outer: for (Symbol msym1 : methodSyms) {
   483                 Type mt1 = memberType(origin.type, msym1);
   484                 for (Symbol msym2 : methodSyms) {
   485                     Type mt2 = memberType(origin.type, msym2);
   486                     if (!isSubSignature(mt1, mt2)) {
   487                         continue outer;
   488                     }
   489                 }
   490                 mostSpecific = mostSpecific.prepend(msym1);
   491             }
   492             if (mostSpecific.isEmpty()) {
   493                 return null;
   494             }
   497             //pick return types - this is done in two phases: (i) first, the most
   498             //specific return type is chosen using strict subtyping; if this fails,
   499             //a second attempt is made using return type substitutability (see JLS 8.4.5)
   500             boolean phase2 = false;
   501             Symbol bestSoFar = null;
   502             while (bestSoFar == null) {
   503                 outer: for (Symbol msym1 : mostSpecific) {
   504                     Type mt1 = memberType(origin.type, msym1);
   505                     for (Symbol msym2 : methodSyms) {
   506                         Type mt2 = memberType(origin.type, msym2);
   507                         if (phase2 ?
   508                                 !returnTypeSubstitutable(mt1, mt2) :
   509                                 !isSubtypeInternal(mt1.getReturnType(), mt2.getReturnType())) {
   510                             continue outer;
   511                         }
   512                     }
   513                     bestSoFar = msym1;
   514                 }
   515                 if (phase2) {
   516                     break;
   517                 } else {
   518                     phase2 = true;
   519                 }
   520             }
   521             if (bestSoFar == null) return null;
   523             //merge thrown types - form the intersection of all the thrown types in
   524             //all the signatures in the list
   525             List<Type> thrown = null;
   526             for (Symbol msym1 : methodSyms) {
   527                 Type mt1 = memberType(origin.type, msym1);
   528                 thrown = (thrown == null) ?
   529                     mt1.getThrownTypes() :
   530                     chk.intersect(mt1.getThrownTypes(), thrown);
   531             }
   533             final List<Type> thrown1 = thrown;
   534             return new FunctionDescriptor(bestSoFar) {
   535                 @Override
   536                 public Type getType(Type origin) {
   537                     Type mt = memberType(origin, getSymbol());
   538                     return new MethodType(mt.getParameterTypes(), mt.getReturnType(), thrown1, syms.methodClass);
   539                 }
   540             };
   541         }
   543         boolean isSubtypeInternal(Type s, Type t) {
   544             return (s.isPrimitive() && t.isPrimitive()) ?
   545                     isSameType(t, s) :
   546                     isSubtype(s, t);
   547         }
   549         FunctionDescriptorLookupError failure(String msg, Object... args) {
   550             return failure(diags.fragment(msg, args));
   551         }
   553         FunctionDescriptorLookupError failure(JCDiagnostic diag) {
   554             return functionDescriptorLookupError.setMessage(diag);
   555         }
   556     }
   558     private DescriptorCache descCache = new DescriptorCache();
   560     /**
   561      * Find the method descriptor associated to this class symbol - if the
   562      * symbol 'origin' is not a functional interface, an exception is thrown.
   563      */
   564     public Symbol findDescriptorSymbol(TypeSymbol origin) throws FunctionDescriptorLookupError {
   565         return descCache.get(origin).getSymbol();
   566     }
   568     /**
   569      * Find the type of the method descriptor associated to this class symbol -
   570      * if the symbol 'origin' is not a functional interface, an exception is thrown.
   571      */
   572     public Type findDescriptorType(Type origin) throws FunctionDescriptorLookupError {
   573         return descCache.get(origin.tsym).getType(origin);
   574     }
   576     /**
   577      * Is given type a functional interface?
   578      */
   579     public boolean isFunctionalInterface(TypeSymbol tsym) {
   580         try {
   581             findDescriptorSymbol(tsym);
   582             return true;
   583         } catch (FunctionDescriptorLookupError ex) {
   584             return false;
   585         }
   586     }
   587     // </editor-fold>
   589     // <editor-fold defaultstate="collapsed" desc="isSubtype">
   590     /**
   591      * Is t an unchecked subtype of s?
   592      */
   593     public boolean isSubtypeUnchecked(Type t, Type s) {
   594         return isSubtypeUnchecked(t, s, Warner.noWarnings);
   595     }
   596     /**
   597      * Is t an unchecked subtype of s?
   598      */
   599     public boolean isSubtypeUnchecked(Type t, Type s, Warner warn) {
   600         boolean result = isSubtypeUncheckedInternal(t, s, warn);
   601         if (result) {
   602             checkUnsafeVarargsConversion(t, s, warn);
   603         }
   604         return result;
   605     }
   606     //where
   607         private boolean isSubtypeUncheckedInternal(Type t, Type s, Warner warn) {
   608             if (t.hasTag(ARRAY) && s.hasTag(ARRAY)) {
   609                 if (((ArrayType)t).elemtype.isPrimitive()) {
   610                     return isSameType(elemtype(t), elemtype(s));
   611                 } else {
   612                     return isSubtypeUnchecked(elemtype(t), elemtype(s), warn);
   613                 }
   614             } else if (isSubtype(t, s)) {
   615                 return true;
   616             }
   617             else if (t.tag == TYPEVAR) {
   618                 return isSubtypeUnchecked(t.getUpperBound(), s, warn);
   619             }
   620             else if (!s.isRaw()) {
   621                 Type t2 = asSuper(t, s.tsym);
   622                 if (t2 != null && t2.isRaw()) {
   623                     if (isReifiable(s))
   624                         warn.silentWarn(LintCategory.UNCHECKED);
   625                     else
   626                         warn.warn(LintCategory.UNCHECKED);
   627                     return true;
   628                 }
   629             }
   630             return false;
   631         }
   633         private void checkUnsafeVarargsConversion(Type t, Type s, Warner warn) {
   634             if (t.tag != ARRAY || isReifiable(t)) return;
   635             ArrayType from = (ArrayType)t;
   636             boolean shouldWarn = false;
   637             switch (s.tag) {
   638                 case ARRAY:
   639                     ArrayType to = (ArrayType)s;
   640                     shouldWarn = from.isVarargs() &&
   641                             !to.isVarargs() &&
   642                             !isReifiable(from);
   643                     break;
   644                 case CLASS:
   645                     shouldWarn = from.isVarargs();
   646                     break;
   647             }
   648             if (shouldWarn) {
   649                 warn.warn(LintCategory.VARARGS);
   650             }
   651         }
   653     /**
   654      * Is t a subtype of s?<br>
   655      * (not defined for Method and ForAll types)
   656      */
   657     final public boolean isSubtype(Type t, Type s) {
   658         return isSubtype(t, s, true);
   659     }
   660     final public boolean isSubtypeNoCapture(Type t, Type s) {
   661         return isSubtype(t, s, false);
   662     }
   663     public boolean isSubtype(Type t, Type s, boolean capture) {
   664         if (t == s)
   665             return true;
   667         if (s.isPartial())
   668             return isSuperType(s, t);
   670         if (s.isCompound()) {
   671             for (Type s2 : interfaces(s).prepend(supertype(s))) {
   672                 if (!isSubtype(t, s2, capture))
   673                     return false;
   674             }
   675             return true;
   676         }
   678         Type lower = lowerBound(s);
   679         if (s != lower)
   680             return isSubtype(capture ? capture(t) : t, lower, false);
   682         return isSubtype.visit(capture ? capture(t) : t, s);
   683     }
   684     // where
   685         private TypeRelation isSubtype = new TypeRelation()
   686         {
   687             public Boolean visitType(Type t, Type s) {
   688                 switch (t.tag) {
   689                  case BYTE:
   690                      return (!s.hasTag(CHAR) && t.getTag().isSubRangeOf(s.getTag()));
   691                  case CHAR:
   692                      return (!s.hasTag(SHORT) && t.getTag().isSubRangeOf(s.getTag()));
   693                  case SHORT: case INT: case LONG:
   694                  case FLOAT: case DOUBLE:
   695                      return t.getTag().isSubRangeOf(s.getTag());
   696                  case BOOLEAN: case VOID:
   697                      return t.hasTag(s.getTag());
   698                  case TYPEVAR:
   699                      return isSubtypeNoCapture(t.getUpperBound(), s);
   700                  case BOT:
   701                      return
   702                          s.hasTag(BOT) || s.hasTag(CLASS) ||
   703                          s.hasTag(ARRAY) || s.hasTag(TYPEVAR);
   704                  case WILDCARD: //we shouldn't be here - avoids crash (see 7034495)
   705                  case NONE:
   706                      return false;
   707                  default:
   708                      throw new AssertionError("isSubtype " + t.tag);
   709                  }
   710             }
   712             private Set<TypePair> cache = new HashSet<TypePair>();
   714             private boolean containsTypeRecursive(Type t, Type s) {
   715                 TypePair pair = new TypePair(t, s);
   716                 if (cache.add(pair)) {
   717                     try {
   718                         return containsType(t.getTypeArguments(),
   719                                             s.getTypeArguments());
   720                     } finally {
   721                         cache.remove(pair);
   722                     }
   723                 } else {
   724                     return containsType(t.getTypeArguments(),
   725                                         rewriteSupers(s).getTypeArguments());
   726                 }
   727             }
   729             private Type rewriteSupers(Type t) {
   730                 if (!t.isParameterized())
   731                     return t;
   732                 ListBuffer<Type> from = lb();
   733                 ListBuffer<Type> to = lb();
   734                 adaptSelf(t, from, to);
   735                 if (from.isEmpty())
   736                     return t;
   737                 ListBuffer<Type> rewrite = lb();
   738                 boolean changed = false;
   739                 for (Type orig : to.toList()) {
   740                     Type s = rewriteSupers(orig);
   741                     if (s.isSuperBound() && !s.isExtendsBound()) {
   742                         s = new WildcardType(syms.objectType,
   743                                              BoundKind.UNBOUND,
   744                                              syms.boundClass);
   745                         changed = true;
   746                     } else if (s != orig) {
   747                         s = new WildcardType(upperBound(s),
   748                                              BoundKind.EXTENDS,
   749                                              syms.boundClass);
   750                         changed = true;
   751                     }
   752                     rewrite.append(s);
   753                 }
   754                 if (changed)
   755                     return subst(t.tsym.type, from.toList(), rewrite.toList());
   756                 else
   757                     return t;
   758             }
   760             @Override
   761             public Boolean visitClassType(ClassType t, Type s) {
   762                 Type sup = asSuper(t, s.tsym);
   763                 return sup != null
   764                     && sup.tsym == s.tsym
   765                     // You're not allowed to write
   766                     //     Vector<Object> vec = new Vector<String>();
   767                     // But with wildcards you can write
   768                     //     Vector<? extends Object> vec = new Vector<String>();
   769                     // which means that subtype checking must be done
   770                     // here instead of same-type checking (via containsType).
   771                     && (!s.isParameterized() || containsTypeRecursive(s, sup))
   772                     && isSubtypeNoCapture(sup.getEnclosingType(),
   773                                           s.getEnclosingType());
   774             }
   776             @Override
   777             public Boolean visitArrayType(ArrayType t, Type s) {
   778                 if (s.tag == ARRAY) {
   779                     if (t.elemtype.isPrimitive())
   780                         return isSameType(t.elemtype, elemtype(s));
   781                     else
   782                         return isSubtypeNoCapture(t.elemtype, elemtype(s));
   783                 }
   785                 if (s.tag == CLASS) {
   786                     Name sname = s.tsym.getQualifiedName();
   787                     return sname == names.java_lang_Object
   788                         || sname == names.java_lang_Cloneable
   789                         || sname == names.java_io_Serializable;
   790                 }
   792                 return false;
   793             }
   795             @Override
   796             public Boolean visitUndetVar(UndetVar t, Type s) {
   797                 //todo: test against origin needed? or replace with substitution?
   798                 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN) {
   799                     return true;
   800                 } else if (s.tag == BOT) {
   801                     //if 's' is 'null' there's no instantiated type U for which
   802                     //U <: s (but 'null' itself, which is not a valid type)
   803                     return false;
   804                 }
   806                 t.addBound(InferenceBound.UPPER, s, Types.this);
   807                 return true;
   808             }
   810             @Override
   811             public Boolean visitErrorType(ErrorType t, Type s) {
   812                 return true;
   813             }
   814         };
   816     /**
   817      * Is t a subtype of every type in given list `ts'?<br>
   818      * (not defined for Method and ForAll types)<br>
   819      * Allows unchecked conversions.
   820      */
   821     public boolean isSubtypeUnchecked(Type t, List<Type> ts, Warner warn) {
   822         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
   823             if (!isSubtypeUnchecked(t, l.head, warn))
   824                 return false;
   825         return true;
   826     }
   828     /**
   829      * Are corresponding elements of ts subtypes of ss?  If lists are
   830      * of different length, return false.
   831      */
   832     public boolean isSubtypes(List<Type> ts, List<Type> ss) {
   833         while (ts.tail != null && ss.tail != null
   834                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   835                isSubtype(ts.head, ss.head)) {
   836             ts = ts.tail;
   837             ss = ss.tail;
   838         }
   839         return ts.tail == null && ss.tail == null;
   840         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   841     }
   843     /**
   844      * Are corresponding elements of ts subtypes of ss, allowing
   845      * unchecked conversions?  If lists are of different length,
   846      * return false.
   847      **/
   848     public boolean isSubtypesUnchecked(List<Type> ts, List<Type> ss, Warner warn) {
   849         while (ts.tail != null && ss.tail != null
   850                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   851                isSubtypeUnchecked(ts.head, ss.head, warn)) {
   852             ts = ts.tail;
   853             ss = ss.tail;
   854         }
   855         return ts.tail == null && ss.tail == null;
   856         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   857     }
   858     // </editor-fold>
   860     // <editor-fold defaultstate="collapsed" desc="isSuperType">
   861     /**
   862      * Is t a supertype of s?
   863      */
   864     public boolean isSuperType(Type t, Type s) {
   865         switch (t.tag) {
   866         case ERROR:
   867             return true;
   868         case UNDETVAR: {
   869             UndetVar undet = (UndetVar)t;
   870             if (t == s ||
   871                 undet.qtype == s ||
   872                 s.tag == ERROR ||
   873                 s.tag == BOT) return true;
   874             undet.addBound(InferenceBound.LOWER, s, this);
   875             return true;
   876         }
   877         default:
   878             return isSubtype(s, t);
   879         }
   880     }
   881     // </editor-fold>
   883     // <editor-fold defaultstate="collapsed" desc="isSameType">
   884     /**
   885      * Are corresponding elements of the lists the same type?  If
   886      * lists are of different length, return false.
   887      */
   888     public boolean isSameTypes(List<Type> ts, List<Type> ss) {
   889         while (ts.tail != null && ss.tail != null
   890                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   891                isSameType(ts.head, ss.head)) {
   892             ts = ts.tail;
   893             ss = ss.tail;
   894         }
   895         return ts.tail == null && ss.tail == null;
   896         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   897     }
   899     /**
   900      * Is t the same type as s?
   901      */
   902     public boolean isSameType(Type t, Type s) {
   903         return isSameType.visit(t, s);
   904     }
   905     // where
   906         private TypeRelation isSameType = new TypeRelation() {
   908             public Boolean visitType(Type t, Type s) {
   909                 if (t == s)
   910                     return true;
   912                 if (s.isPartial())
   913                     return visit(s, t);
   915                 switch (t.tag) {
   916                 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
   917                 case DOUBLE: case BOOLEAN: case VOID: case BOT: case NONE:
   918                     return t.tag == s.tag;
   919                 case TYPEVAR: {
   920                     if (s.tag == TYPEVAR) {
   921                         //type-substitution does not preserve type-var types
   922                         //check that type var symbols and bounds are indeed the same
   923                         return t.tsym == s.tsym &&
   924                                 visit(t.getUpperBound(), s.getUpperBound());
   925                     }
   926                     else {
   927                         //special case for s == ? super X, where upper(s) = u
   928                         //check that u == t, where u has been set by Type.withTypeVar
   929                         return s.isSuperBound() &&
   930                                 !s.isExtendsBound() &&
   931                                 visit(t, upperBound(s));
   932                     }
   933                 }
   934                 default:
   935                     throw new AssertionError("isSameType " + t.tag);
   936                 }
   937             }
   939             @Override
   940             public Boolean visitWildcardType(WildcardType t, Type s) {
   941                 if (s.isPartial())
   942                     return visit(s, t);
   943                 else
   944                     return false;
   945             }
   947             @Override
   948             public Boolean visitClassType(ClassType t, Type s) {
   949                 if (t == s)
   950                     return true;
   952                 if (s.isPartial())
   953                     return visit(s, t);
   955                 if (s.isSuperBound() && !s.isExtendsBound())
   956                     return visit(t, upperBound(s)) && visit(t, lowerBound(s));
   958                 if (t.isCompound() && s.isCompound()) {
   959                     if (!visit(supertype(t), supertype(s)))
   960                         return false;
   962                     HashSet<SingletonType> set = new HashSet<SingletonType>();
   963                     for (Type x : interfaces(t))
   964                         set.add(new SingletonType(x));
   965                     for (Type x : interfaces(s)) {
   966                         if (!set.remove(new SingletonType(x)))
   967                             return false;
   968                     }
   969                     return (set.isEmpty());
   970                 }
   971                 return t.tsym == s.tsym
   972                     && visit(t.getEnclosingType(), s.getEnclosingType())
   973                     && containsTypeEquivalent(t.getTypeArguments(), s.getTypeArguments());
   974             }
   976             @Override
   977             public Boolean visitArrayType(ArrayType t, Type s) {
   978                 if (t == s)
   979                     return true;
   981                 if (s.isPartial())
   982                     return visit(s, t);
   984                 return s.hasTag(ARRAY)
   985                     && containsTypeEquivalent(t.elemtype, elemtype(s));
   986             }
   988             @Override
   989             public Boolean visitMethodType(MethodType t, Type s) {
   990                 // isSameType for methods does not take thrown
   991                 // exceptions into account!
   992                 return hasSameArgs(t, s) && visit(t.getReturnType(), s.getReturnType());
   993             }
   995             @Override
   996             public Boolean visitPackageType(PackageType t, Type s) {
   997                 return t == s;
   998             }
  1000             @Override
  1001             public Boolean visitForAll(ForAll t, Type s) {
  1002                 if (s.tag != FORALL)
  1003                     return false;
  1005                 ForAll forAll = (ForAll)s;
  1006                 return hasSameBounds(t, forAll)
  1007                     && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
  1010             @Override
  1011             public Boolean visitUndetVar(UndetVar t, Type s) {
  1012                 if (s.tag == WILDCARD)
  1013                     // FIXME, this might be leftovers from before capture conversion
  1014                     return false;
  1016                 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN)
  1017                     return true;
  1019                 t.addBound(InferenceBound.EQ, s, Types.this);
  1021                 return true;
  1024             @Override
  1025             public Boolean visitErrorType(ErrorType t, Type s) {
  1026                 return true;
  1028         };
  1029     // </editor-fold>
  1031     // <editor-fold defaultstate="collapsed" desc="Contains Type">
  1032     public boolean containedBy(Type t, Type s) {
  1033         switch (t.tag) {
  1034         case UNDETVAR:
  1035             if (s.tag == WILDCARD) {
  1036                 UndetVar undetvar = (UndetVar)t;
  1037                 WildcardType wt = (WildcardType)s;
  1038                 switch(wt.kind) {
  1039                     case UNBOUND: //similar to ? extends Object
  1040                     case EXTENDS: {
  1041                         Type bound = upperBound(s);
  1042                         undetvar.addBound(InferenceBound.UPPER, bound, this);
  1043                         break;
  1045                     case SUPER: {
  1046                         Type bound = lowerBound(s);
  1047                         undetvar.addBound(InferenceBound.LOWER, bound, this);
  1048                         break;
  1051                 return true;
  1052             } else {
  1053                 return isSameType(t, s);
  1055         case ERROR:
  1056             return true;
  1057         default:
  1058             return containsType(s, t);
  1062     boolean containsType(List<Type> ts, List<Type> ss) {
  1063         while (ts.nonEmpty() && ss.nonEmpty()
  1064                && containsType(ts.head, ss.head)) {
  1065             ts = ts.tail;
  1066             ss = ss.tail;
  1068         return ts.isEmpty() && ss.isEmpty();
  1071     /**
  1072      * Check if t contains s.
  1074      * <p>T contains S if:
  1076      * <p>{@code L(T) <: L(S) && U(S) <: U(T)}
  1078      * <p>This relation is only used by ClassType.isSubtype(), that
  1079      * is,
  1081      * <p>{@code C<S> <: C<T> if T contains S.}
  1083      * <p>Because of F-bounds, this relation can lead to infinite
  1084      * recursion.  Thus we must somehow break that recursion.  Notice
  1085      * that containsType() is only called from ClassType.isSubtype().
  1086      * Since the arguments have already been checked against their
  1087      * bounds, we know:
  1089      * <p>{@code U(S) <: U(T) if T is "super" bound (U(T) *is* the bound)}
  1091      * <p>{@code L(T) <: L(S) if T is "extends" bound (L(T) is bottom)}
  1093      * @param t a type
  1094      * @param s a type
  1095      */
  1096     public boolean containsType(Type t, Type s) {
  1097         return containsType.visit(t, s);
  1099     // where
  1100         private TypeRelation containsType = new TypeRelation() {
  1102             private Type U(Type t) {
  1103                 while (t.tag == WILDCARD) {
  1104                     WildcardType w = (WildcardType)t;
  1105                     if (w.isSuperBound())
  1106                         return w.bound == null ? syms.objectType : w.bound.bound;
  1107                     else
  1108                         t = w.type;
  1110                 return t;
  1113             private Type L(Type t) {
  1114                 while (t.tag == WILDCARD) {
  1115                     WildcardType w = (WildcardType)t;
  1116                     if (w.isExtendsBound())
  1117                         return syms.botType;
  1118                     else
  1119                         t = w.type;
  1121                 return t;
  1124             public Boolean visitType(Type t, Type s) {
  1125                 if (s.isPartial())
  1126                     return containedBy(s, t);
  1127                 else
  1128                     return isSameType(t, s);
  1131 //            void debugContainsType(WildcardType t, Type s) {
  1132 //                System.err.println();
  1133 //                System.err.format(" does %s contain %s?%n", t, s);
  1134 //                System.err.format(" %s U(%s) <: U(%s) %s = %s%n",
  1135 //                                  upperBound(s), s, t, U(t),
  1136 //                                  t.isSuperBound()
  1137 //                                  || isSubtypeNoCapture(upperBound(s), U(t)));
  1138 //                System.err.format(" %s L(%s) <: L(%s) %s = %s%n",
  1139 //                                  L(t), t, s, lowerBound(s),
  1140 //                                  t.isExtendsBound()
  1141 //                                  || isSubtypeNoCapture(L(t), lowerBound(s)));
  1142 //                System.err.println();
  1143 //            }
  1145             @Override
  1146             public Boolean visitWildcardType(WildcardType t, Type s) {
  1147                 if (s.isPartial())
  1148                     return containedBy(s, t);
  1149                 else {
  1150 //                    debugContainsType(t, s);
  1151                     return isSameWildcard(t, s)
  1152                         || isCaptureOf(s, t)
  1153                         || ((t.isExtendsBound() || isSubtypeNoCapture(L(t), lowerBound(s))) &&
  1154                             (t.isSuperBound() || isSubtypeNoCapture(upperBound(s), U(t))));
  1158             @Override
  1159             public Boolean visitUndetVar(UndetVar t, Type s) {
  1160                 if (s.tag != WILDCARD)
  1161                     return isSameType(t, s);
  1162                 else
  1163                     return false;
  1166             @Override
  1167             public Boolean visitErrorType(ErrorType t, Type s) {
  1168                 return true;
  1170         };
  1172     public boolean isCaptureOf(Type s, WildcardType t) {
  1173         if (s.tag != TYPEVAR || !((TypeVar)s).isCaptured())
  1174             return false;
  1175         return isSameWildcard(t, ((CapturedType)s).wildcard);
  1178     public boolean isSameWildcard(WildcardType t, Type s) {
  1179         if (s.tag != WILDCARD)
  1180             return false;
  1181         WildcardType w = (WildcardType)s;
  1182         return w.kind == t.kind && w.type == t.type;
  1185     public boolean containsTypeEquivalent(List<Type> ts, List<Type> ss) {
  1186         while (ts.nonEmpty() && ss.nonEmpty()
  1187                && containsTypeEquivalent(ts.head, ss.head)) {
  1188             ts = ts.tail;
  1189             ss = ss.tail;
  1191         return ts.isEmpty() && ss.isEmpty();
  1193     // </editor-fold>
  1195     // <editor-fold defaultstate="collapsed" desc="isCastable">
  1196     public boolean isCastable(Type t, Type s) {
  1197         return isCastable(t, s, Warner.noWarnings);
  1200     /**
  1201      * Is t is castable to s?<br>
  1202      * s is assumed to be an erased type.<br>
  1203      * (not defined for Method and ForAll types).
  1204      */
  1205     public boolean isCastable(Type t, Type s, Warner warn) {
  1206         if (t == s)
  1207             return true;
  1209         if (t.isPrimitive() != s.isPrimitive())
  1210             return allowBoxing && (
  1211                     isConvertible(t, s, warn)
  1212                     || (allowObjectToPrimitiveCast &&
  1213                         s.isPrimitive() &&
  1214                         isSubtype(boxedClass(s).type, t)));
  1215         if (warn != warnStack.head) {
  1216             try {
  1217                 warnStack = warnStack.prepend(warn);
  1218                 checkUnsafeVarargsConversion(t, s, warn);
  1219                 return isCastable.visit(t,s);
  1220             } finally {
  1221                 warnStack = warnStack.tail;
  1223         } else {
  1224             return isCastable.visit(t,s);
  1227     // where
  1228         private TypeRelation isCastable = new TypeRelation() {
  1230             public Boolean visitType(Type t, Type s) {
  1231                 if (s.tag == ERROR)
  1232                     return true;
  1234                 switch (t.tag) {
  1235                 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
  1236                 case DOUBLE:
  1237                     return s.isNumeric();
  1238                 case BOOLEAN:
  1239                     return s.tag == BOOLEAN;
  1240                 case VOID:
  1241                     return false;
  1242                 case BOT:
  1243                     return isSubtype(t, s);
  1244                 default:
  1245                     throw new AssertionError();
  1249             @Override
  1250             public Boolean visitWildcardType(WildcardType t, Type s) {
  1251                 return isCastable(upperBound(t), s, warnStack.head);
  1254             @Override
  1255             public Boolean visitClassType(ClassType t, Type s) {
  1256                 if (s.tag == ERROR || s.tag == BOT)
  1257                     return true;
  1259                 if (s.tag == TYPEVAR) {
  1260                     if (isCastable(t, s.getUpperBound(), Warner.noWarnings)) {
  1261                         warnStack.head.warn(LintCategory.UNCHECKED);
  1262                         return true;
  1263                     } else {
  1264                         return false;
  1268                 if (t.isCompound()) {
  1269                     Warner oldWarner = warnStack.head;
  1270                     warnStack.head = Warner.noWarnings;
  1271                     if (!visit(supertype(t), s))
  1272                         return false;
  1273                     for (Type intf : interfaces(t)) {
  1274                         if (!visit(intf, s))
  1275                             return false;
  1277                     if (warnStack.head.hasLint(LintCategory.UNCHECKED))
  1278                         oldWarner.warn(LintCategory.UNCHECKED);
  1279                     return true;
  1282                 if (s.isCompound()) {
  1283                     // call recursively to reuse the above code
  1284                     return visitClassType((ClassType)s, t);
  1287                 if (s.tag == CLASS || s.tag == ARRAY) {
  1288                     boolean upcast;
  1289                     if ((upcast = isSubtype(erasure(t), erasure(s)))
  1290                         || isSubtype(erasure(s), erasure(t))) {
  1291                         if (!upcast && s.tag == ARRAY) {
  1292                             if (!isReifiable(s))
  1293                                 warnStack.head.warn(LintCategory.UNCHECKED);
  1294                             return true;
  1295                         } else if (s.isRaw()) {
  1296                             return true;
  1297                         } else if (t.isRaw()) {
  1298                             if (!isUnbounded(s))
  1299                                 warnStack.head.warn(LintCategory.UNCHECKED);
  1300                             return true;
  1302                         // Assume |a| <: |b|
  1303                         final Type a = upcast ? t : s;
  1304                         final Type b = upcast ? s : t;
  1305                         final boolean HIGH = true;
  1306                         final boolean LOW = false;
  1307                         final boolean DONT_REWRITE_TYPEVARS = false;
  1308                         Type aHigh = rewriteQuantifiers(a, HIGH, DONT_REWRITE_TYPEVARS);
  1309                         Type aLow  = rewriteQuantifiers(a, LOW,  DONT_REWRITE_TYPEVARS);
  1310                         Type bHigh = rewriteQuantifiers(b, HIGH, DONT_REWRITE_TYPEVARS);
  1311                         Type bLow  = rewriteQuantifiers(b, LOW,  DONT_REWRITE_TYPEVARS);
  1312                         Type lowSub = asSub(bLow, aLow.tsym);
  1313                         Type highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
  1314                         if (highSub == null) {
  1315                             final boolean REWRITE_TYPEVARS = true;
  1316                             aHigh = rewriteQuantifiers(a, HIGH, REWRITE_TYPEVARS);
  1317                             aLow  = rewriteQuantifiers(a, LOW,  REWRITE_TYPEVARS);
  1318                             bHigh = rewriteQuantifiers(b, HIGH, REWRITE_TYPEVARS);
  1319                             bLow  = rewriteQuantifiers(b, LOW,  REWRITE_TYPEVARS);
  1320                             lowSub = asSub(bLow, aLow.tsym);
  1321                             highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
  1323                         if (highSub != null) {
  1324                             if (!(a.tsym == highSub.tsym && a.tsym == lowSub.tsym)) {
  1325                                 Assert.error(a.tsym + " != " + highSub.tsym + " != " + lowSub.tsym);
  1327                             if (!disjointTypes(aHigh.allparams(), highSub.allparams())
  1328                                 && !disjointTypes(aHigh.allparams(), lowSub.allparams())
  1329                                 && !disjointTypes(aLow.allparams(), highSub.allparams())
  1330                                 && !disjointTypes(aLow.allparams(), lowSub.allparams())) {
  1331                                 if (upcast ? giveWarning(a, b) :
  1332                                     giveWarning(b, a))
  1333                                     warnStack.head.warn(LintCategory.UNCHECKED);
  1334                                 return true;
  1337                         if (isReifiable(s))
  1338                             return isSubtypeUnchecked(a, b);
  1339                         else
  1340                             return isSubtypeUnchecked(a, b, warnStack.head);
  1343                     // Sidecast
  1344                     if (s.tag == CLASS) {
  1345                         if ((s.tsym.flags() & INTERFACE) != 0) {
  1346                             return ((t.tsym.flags() & FINAL) == 0)
  1347                                 ? sideCast(t, s, warnStack.head)
  1348                                 : sideCastFinal(t, s, warnStack.head);
  1349                         } else if ((t.tsym.flags() & INTERFACE) != 0) {
  1350                             return ((s.tsym.flags() & FINAL) == 0)
  1351                                 ? sideCast(t, s, warnStack.head)
  1352                                 : sideCastFinal(t, s, warnStack.head);
  1353                         } else {
  1354                             // unrelated class types
  1355                             return false;
  1359                 return false;
  1362             @Override
  1363             public Boolean visitArrayType(ArrayType t, Type s) {
  1364                 switch (s.tag) {
  1365                 case ERROR:
  1366                 case BOT:
  1367                     return true;
  1368                 case TYPEVAR:
  1369                     if (isCastable(s, t, Warner.noWarnings)) {
  1370                         warnStack.head.warn(LintCategory.UNCHECKED);
  1371                         return true;
  1372                     } else {
  1373                         return false;
  1375                 case CLASS:
  1376                     return isSubtype(t, s);
  1377                 case ARRAY:
  1378                     if (elemtype(t).isPrimitive() || elemtype(s).isPrimitive()) {
  1379                         return elemtype(t).tag == elemtype(s).tag;
  1380                     } else {
  1381                         return visit(elemtype(t), elemtype(s));
  1383                 default:
  1384                     return false;
  1388             @Override
  1389             public Boolean visitTypeVar(TypeVar t, Type s) {
  1390                 switch (s.tag) {
  1391                 case ERROR:
  1392                 case BOT:
  1393                     return true;
  1394                 case TYPEVAR:
  1395                     if (isSubtype(t, s)) {
  1396                         return true;
  1397                     } else if (isCastable(t.bound, s, Warner.noWarnings)) {
  1398                         warnStack.head.warn(LintCategory.UNCHECKED);
  1399                         return true;
  1400                     } else {
  1401                         return false;
  1403                 default:
  1404                     return isCastable(t.bound, s, warnStack.head);
  1408             @Override
  1409             public Boolean visitErrorType(ErrorType t, Type s) {
  1410                 return true;
  1412         };
  1413     // </editor-fold>
  1415     // <editor-fold defaultstate="collapsed" desc="disjointTypes">
  1416     public boolean disjointTypes(List<Type> ts, List<Type> ss) {
  1417         while (ts.tail != null && ss.tail != null) {
  1418             if (disjointType(ts.head, ss.head)) return true;
  1419             ts = ts.tail;
  1420             ss = ss.tail;
  1422         return false;
  1425     /**
  1426      * Two types or wildcards are considered disjoint if it can be
  1427      * proven that no type can be contained in both. It is
  1428      * conservative in that it is allowed to say that two types are
  1429      * not disjoint, even though they actually are.
  1431      * The type {@code C<X>} is castable to {@code C<Y>} exactly if
  1432      * {@code X} and {@code Y} are not disjoint.
  1433      */
  1434     public boolean disjointType(Type t, Type s) {
  1435         return disjointType.visit(t, s);
  1437     // where
  1438         private TypeRelation disjointType = new TypeRelation() {
  1440             private Set<TypePair> cache = new HashSet<TypePair>();
  1442             public Boolean visitType(Type t, Type s) {
  1443                 if (s.tag == WILDCARD)
  1444                     return visit(s, t);
  1445                 else
  1446                     return notSoftSubtypeRecursive(t, s) || notSoftSubtypeRecursive(s, t);
  1449             private boolean isCastableRecursive(Type t, Type s) {
  1450                 TypePair pair = new TypePair(t, s);
  1451                 if (cache.add(pair)) {
  1452                     try {
  1453                         return Types.this.isCastable(t, s);
  1454                     } finally {
  1455                         cache.remove(pair);
  1457                 } else {
  1458                     return true;
  1462             private boolean notSoftSubtypeRecursive(Type t, Type s) {
  1463                 TypePair pair = new TypePair(t, s);
  1464                 if (cache.add(pair)) {
  1465                     try {
  1466                         return Types.this.notSoftSubtype(t, s);
  1467                     } finally {
  1468                         cache.remove(pair);
  1470                 } else {
  1471                     return false;
  1475             @Override
  1476             public Boolean visitWildcardType(WildcardType t, Type s) {
  1477                 if (t.isUnbound())
  1478                     return false;
  1480                 if (s.tag != WILDCARD) {
  1481                     if (t.isExtendsBound())
  1482                         return notSoftSubtypeRecursive(s, t.type);
  1483                     else // isSuperBound()
  1484                         return notSoftSubtypeRecursive(t.type, s);
  1487                 if (s.isUnbound())
  1488                     return false;
  1490                 if (t.isExtendsBound()) {
  1491                     if (s.isExtendsBound())
  1492                         return !isCastableRecursive(t.type, upperBound(s));
  1493                     else if (s.isSuperBound())
  1494                         return notSoftSubtypeRecursive(lowerBound(s), t.type);
  1495                 } else if (t.isSuperBound()) {
  1496                     if (s.isExtendsBound())
  1497                         return notSoftSubtypeRecursive(t.type, upperBound(s));
  1499                 return false;
  1501         };
  1502     // </editor-fold>
  1504     // <editor-fold defaultstate="collapsed" desc="lowerBoundArgtypes">
  1505     /**
  1506      * Returns the lower bounds of the formals of a method.
  1507      */
  1508     public List<Type> lowerBoundArgtypes(Type t) {
  1509         return lowerBounds(t.getParameterTypes());
  1511     public List<Type> lowerBounds(List<Type> ts) {
  1512         return map(ts, lowerBoundMapping);
  1514     private final Mapping lowerBoundMapping = new Mapping("lowerBound") {
  1515             public Type apply(Type t) {
  1516                 return lowerBound(t);
  1518         };
  1519     // </editor-fold>
  1521     // <editor-fold defaultstate="collapsed" desc="notSoftSubtype">
  1522     /**
  1523      * This relation answers the question: is impossible that
  1524      * something of type `t' can be a subtype of `s'? This is
  1525      * different from the question "is `t' not a subtype of `s'?"
  1526      * when type variables are involved: Integer is not a subtype of T
  1527      * where {@code <T extends Number>} but it is not true that Integer cannot
  1528      * possibly be a subtype of T.
  1529      */
  1530     public boolean notSoftSubtype(Type t, Type s) {
  1531         if (t == s) return false;
  1532         if (t.tag == TYPEVAR) {
  1533             TypeVar tv = (TypeVar) t;
  1534             return !isCastable(tv.bound,
  1535                                relaxBound(s),
  1536                                Warner.noWarnings);
  1538         if (s.tag != WILDCARD)
  1539             s = upperBound(s);
  1541         return !isSubtype(t, relaxBound(s));
  1544     private Type relaxBound(Type t) {
  1545         if (t.tag == TYPEVAR) {
  1546             while (t.tag == TYPEVAR)
  1547                 t = t.getUpperBound();
  1548             t = rewriteQuantifiers(t, true, true);
  1550         return t;
  1552     // </editor-fold>
  1554     // <editor-fold defaultstate="collapsed" desc="isReifiable">
  1555     public boolean isReifiable(Type t) {
  1556         return isReifiable.visit(t);
  1558     // where
  1559         private UnaryVisitor<Boolean> isReifiable = new UnaryVisitor<Boolean>() {
  1561             public Boolean visitType(Type t, Void ignored) {
  1562                 return true;
  1565             @Override
  1566             public Boolean visitClassType(ClassType t, Void ignored) {
  1567                 if (t.isCompound())
  1568                     return false;
  1569                 else {
  1570                     if (!t.isParameterized())
  1571                         return true;
  1573                     for (Type param : t.allparams()) {
  1574                         if (!param.isUnbound())
  1575                             return false;
  1577                     return true;
  1581             @Override
  1582             public Boolean visitArrayType(ArrayType t, Void ignored) {
  1583                 return visit(t.elemtype);
  1586             @Override
  1587             public Boolean visitTypeVar(TypeVar t, Void ignored) {
  1588                 return false;
  1590         };
  1591     // </editor-fold>
  1593     // <editor-fold defaultstate="collapsed" desc="Array Utils">
  1594     public boolean isArray(Type t) {
  1595         while (t.tag == WILDCARD)
  1596             t = upperBound(t);
  1597         return t.tag == ARRAY;
  1600     /**
  1601      * The element type of an array.
  1602      */
  1603     public Type elemtype(Type t) {
  1604         switch (t.tag) {
  1605         case WILDCARD:
  1606             return elemtype(upperBound(t));
  1607         case ARRAY:
  1608             return ((ArrayType)t).elemtype;
  1609         case FORALL:
  1610             return elemtype(((ForAll)t).qtype);
  1611         case ERROR:
  1612             return t;
  1613         default:
  1614             return null;
  1618     public Type elemtypeOrType(Type t) {
  1619         Type elemtype = elemtype(t);
  1620         return elemtype != null ?
  1621             elemtype :
  1622             t;
  1625     /**
  1626      * Mapping to take element type of an arraytype
  1627      */
  1628     private Mapping elemTypeFun = new Mapping ("elemTypeFun") {
  1629         public Type apply(Type t) { return elemtype(t); }
  1630     };
  1632     /**
  1633      * The number of dimensions of an array type.
  1634      */
  1635     public int dimensions(Type t) {
  1636         int result = 0;
  1637         while (t.tag == ARRAY) {
  1638             result++;
  1639             t = elemtype(t);
  1641         return result;
  1644     /**
  1645      * Returns an ArrayType with the component type t
  1647      * @param t The component type of the ArrayType
  1648      * @return the ArrayType for the given component
  1649      */
  1650     public ArrayType makeArrayType(Type t) {
  1651         if (t.tag == VOID ||
  1652             t.tag == PACKAGE) {
  1653             Assert.error("Type t must not be a VOID or PACKAGE type, " + t.toString());
  1655         return new ArrayType(t, syms.arrayClass);
  1657     // </editor-fold>
  1659     // <editor-fold defaultstate="collapsed" desc="asSuper">
  1660     /**
  1661      * Return the (most specific) base type of t that starts with the
  1662      * given symbol.  If none exists, return null.
  1664      * @param t a type
  1665      * @param sym a symbol
  1666      */
  1667     public Type asSuper(Type t, Symbol sym) {
  1668         return asSuper.visit(t, sym);
  1670     // where
  1671         private SimpleVisitor<Type,Symbol> asSuper = new SimpleVisitor<Type,Symbol>() {
  1673             public Type visitType(Type t, Symbol sym) {
  1674                 return null;
  1677             @Override
  1678             public Type visitClassType(ClassType t, Symbol sym) {
  1679                 if (t.tsym == sym)
  1680                     return t;
  1682                 Type st = supertype(t);
  1683                 if (st.tag == CLASS || st.tag == TYPEVAR || st.tag == ERROR) {
  1684                     Type x = asSuper(st, sym);
  1685                     if (x != null)
  1686                         return x;
  1688                 if ((sym.flags() & INTERFACE) != 0) {
  1689                     for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
  1690                         Type x = asSuper(l.head, sym);
  1691                         if (x != null)
  1692                             return x;
  1695                 return null;
  1698             @Override
  1699             public Type visitArrayType(ArrayType t, Symbol sym) {
  1700                 return isSubtype(t, sym.type) ? sym.type : null;
  1703             @Override
  1704             public Type visitTypeVar(TypeVar t, Symbol sym) {
  1705                 if (t.tsym == sym)
  1706                     return t;
  1707                 else
  1708                     return asSuper(t.bound, sym);
  1711             @Override
  1712             public Type visitErrorType(ErrorType t, Symbol sym) {
  1713                 return t;
  1715         };
  1717     /**
  1718      * Return the base type of t or any of its outer types that starts
  1719      * with the given symbol.  If none exists, return null.
  1721      * @param t a type
  1722      * @param sym a symbol
  1723      */
  1724     public Type asOuterSuper(Type t, Symbol sym) {
  1725         switch (t.tag) {
  1726         case CLASS:
  1727             do {
  1728                 Type s = asSuper(t, sym);
  1729                 if (s != null) return s;
  1730                 t = t.getEnclosingType();
  1731             } while (t.tag == CLASS);
  1732             return null;
  1733         case ARRAY:
  1734             return isSubtype(t, sym.type) ? sym.type : null;
  1735         case TYPEVAR:
  1736             return asSuper(t, sym);
  1737         case ERROR:
  1738             return t;
  1739         default:
  1740             return null;
  1744     /**
  1745      * Return the base type of t or any of its enclosing types that
  1746      * starts with the given symbol.  If none exists, return null.
  1748      * @param t a type
  1749      * @param sym a symbol
  1750      */
  1751     public Type asEnclosingSuper(Type t, Symbol sym) {
  1752         switch (t.tag) {
  1753         case CLASS:
  1754             do {
  1755                 Type s = asSuper(t, sym);
  1756                 if (s != null) return s;
  1757                 Type outer = t.getEnclosingType();
  1758                 t = (outer.tag == CLASS) ? outer :
  1759                     (t.tsym.owner.enclClass() != null) ? t.tsym.owner.enclClass().type :
  1760                     Type.noType;
  1761             } while (t.tag == CLASS);
  1762             return null;
  1763         case ARRAY:
  1764             return isSubtype(t, sym.type) ? sym.type : null;
  1765         case TYPEVAR:
  1766             return asSuper(t, sym);
  1767         case ERROR:
  1768             return t;
  1769         default:
  1770             return null;
  1773     // </editor-fold>
  1775     // <editor-fold defaultstate="collapsed" desc="memberType">
  1776     /**
  1777      * The type of given symbol, seen as a member of t.
  1779      * @param t a type
  1780      * @param sym a symbol
  1781      */
  1782     public Type memberType(Type t, Symbol sym) {
  1783         return (sym.flags() & STATIC) != 0
  1784             ? sym.type
  1785             : memberType.visit(t, sym);
  1787     // where
  1788         private SimpleVisitor<Type,Symbol> memberType = new SimpleVisitor<Type,Symbol>() {
  1790             public Type visitType(Type t, Symbol sym) {
  1791                 return sym.type;
  1794             @Override
  1795             public Type visitWildcardType(WildcardType t, Symbol sym) {
  1796                 return memberType(upperBound(t), sym);
  1799             @Override
  1800             public Type visitClassType(ClassType t, Symbol sym) {
  1801                 Symbol owner = sym.owner;
  1802                 long flags = sym.flags();
  1803                 if (((flags & STATIC) == 0) && owner.type.isParameterized()) {
  1804                     Type base = asOuterSuper(t, owner);
  1805                     //if t is an intersection type T = CT & I1 & I2 ... & In
  1806                     //its supertypes CT, I1, ... In might contain wildcards
  1807                     //so we need to go through capture conversion
  1808                     base = t.isCompound() ? capture(base) : base;
  1809                     if (base != null) {
  1810                         List<Type> ownerParams = owner.type.allparams();
  1811                         List<Type> baseParams = base.allparams();
  1812                         if (ownerParams.nonEmpty()) {
  1813                             if (baseParams.isEmpty()) {
  1814                                 // then base is a raw type
  1815                                 return erasure(sym.type);
  1816                             } else {
  1817                                 return subst(sym.type, ownerParams, baseParams);
  1822                 return sym.type;
  1825             @Override
  1826             public Type visitTypeVar(TypeVar t, Symbol sym) {
  1827                 return memberType(t.bound, sym);
  1830             @Override
  1831             public Type visitErrorType(ErrorType t, Symbol sym) {
  1832                 return t;
  1834         };
  1835     // </editor-fold>
  1837     // <editor-fold defaultstate="collapsed" desc="isAssignable">
  1838     public boolean isAssignable(Type t, Type s) {
  1839         return isAssignable(t, s, Warner.noWarnings);
  1842     /**
  1843      * Is t assignable to s?<br>
  1844      * Equivalent to subtype except for constant values and raw
  1845      * types.<br>
  1846      * (not defined for Method and ForAll types)
  1847      */
  1848     public boolean isAssignable(Type t, Type s, Warner warn) {
  1849         if (t.tag == ERROR)
  1850             return true;
  1851         if (t.tag.isSubRangeOf(INT) && t.constValue() != null) {
  1852             int value = ((Number)t.constValue()).intValue();
  1853             switch (s.tag) {
  1854             case BYTE:
  1855                 if (Byte.MIN_VALUE <= value && value <= Byte.MAX_VALUE)
  1856                     return true;
  1857                 break;
  1858             case CHAR:
  1859                 if (Character.MIN_VALUE <= value && value <= Character.MAX_VALUE)
  1860                     return true;
  1861                 break;
  1862             case SHORT:
  1863                 if (Short.MIN_VALUE <= value && value <= Short.MAX_VALUE)
  1864                     return true;
  1865                 break;
  1866             case INT:
  1867                 return true;
  1868             case CLASS:
  1869                 switch (unboxedType(s).tag) {
  1870                 case BYTE:
  1871                 case CHAR:
  1872                 case SHORT:
  1873                     return isAssignable(t, unboxedType(s), warn);
  1875                 break;
  1878         return isConvertible(t, s, warn);
  1880     // </editor-fold>
  1882     // <editor-fold defaultstate="collapsed" desc="erasure">
  1883     /**
  1884      * The erasure of t {@code |t|} -- the type that results when all
  1885      * type parameters in t are deleted.
  1886      */
  1887     public Type erasure(Type t) {
  1888         return eraseNotNeeded(t)? t : erasure(t, false);
  1890     //where
  1891     private boolean eraseNotNeeded(Type t) {
  1892         // We don't want to erase primitive types and String type as that
  1893         // operation is idempotent. Also, erasing these could result in loss
  1894         // of information such as constant values attached to such types.
  1895         return (t.isPrimitive()) || (syms.stringType.tsym == t.tsym);
  1898     private Type erasure(Type t, boolean recurse) {
  1899         if (t.isPrimitive())
  1900             return t; /* fast special case */
  1901         else
  1902             return erasure.visit(t, recurse);
  1904     // where
  1905         private SimpleVisitor<Type, Boolean> erasure = new SimpleVisitor<Type, Boolean>() {
  1906             public Type visitType(Type t, Boolean recurse) {
  1907                 if (t.isPrimitive())
  1908                     return t; /*fast special case*/
  1909                 else
  1910                     return t.map(recurse ? erasureRecFun : erasureFun);
  1913             @Override
  1914             public Type visitWildcardType(WildcardType t, Boolean recurse) {
  1915                 return erasure(upperBound(t), recurse);
  1918             @Override
  1919             public Type visitClassType(ClassType t, Boolean recurse) {
  1920                 Type erased = t.tsym.erasure(Types.this);
  1921                 if (recurse) {
  1922                     erased = new ErasedClassType(erased.getEnclosingType(),erased.tsym);
  1924                 return erased;
  1927             @Override
  1928             public Type visitTypeVar(TypeVar t, Boolean recurse) {
  1929                 return erasure(t.bound, recurse);
  1932             @Override
  1933             public Type visitErrorType(ErrorType t, Boolean recurse) {
  1934                 return t;
  1936         };
  1938     private Mapping erasureFun = new Mapping ("erasure") {
  1939             public Type apply(Type t) { return erasure(t); }
  1940         };
  1942     private Mapping erasureRecFun = new Mapping ("erasureRecursive") {
  1943         public Type apply(Type t) { return erasureRecursive(t); }
  1944     };
  1946     public List<Type> erasure(List<Type> ts) {
  1947         return Type.map(ts, erasureFun);
  1950     public Type erasureRecursive(Type t) {
  1951         return erasure(t, true);
  1954     public List<Type> erasureRecursive(List<Type> ts) {
  1955         return Type.map(ts, erasureRecFun);
  1957     // </editor-fold>
  1959     // <editor-fold defaultstate="collapsed" desc="makeCompoundType">
  1960     /**
  1961      * Make a compound type from non-empty list of types
  1963      * @param bounds            the types from which the compound type is formed
  1964      * @param supertype         is objectType if all bounds are interfaces,
  1965      *                          null otherwise.
  1966      */
  1967     public Type makeCompoundType(List<Type> bounds,
  1968                                  Type supertype) {
  1969         ClassSymbol bc =
  1970             new ClassSymbol(ABSTRACT|PUBLIC|SYNTHETIC|COMPOUND|ACYCLIC,
  1971                             Type.moreInfo
  1972                                 ? names.fromString(bounds.toString())
  1973                                 : names.empty,
  1974                             syms.noSymbol);
  1975         if (bounds.head.tag == TYPEVAR)
  1976             // error condition, recover
  1977                 bc.erasure_field = syms.objectType;
  1978             else
  1979                 bc.erasure_field = erasure(bounds.head);
  1980             bc.members_field = new Scope(bc);
  1981         ClassType bt = (ClassType)bc.type;
  1982         bt.allparams_field = List.nil();
  1983         if (supertype != null) {
  1984             bt.supertype_field = supertype;
  1985             bt.interfaces_field = bounds;
  1986         } else {
  1987             bt.supertype_field = bounds.head;
  1988             bt.interfaces_field = bounds.tail;
  1990         Assert.check(bt.supertype_field.tsym.completer != null
  1991                 || !bt.supertype_field.isInterface(),
  1992             bt.supertype_field);
  1993         return bt;
  1996     /**
  1997      * Same as {@link #makeCompoundType(List,Type)}, except that the
  1998      * second parameter is computed directly. Note that this might
  1999      * cause a symbol completion.  Hence, this version of
  2000      * makeCompoundType may not be called during a classfile read.
  2001      */
  2002     public Type makeCompoundType(List<Type> bounds) {
  2003         Type supertype = (bounds.head.tsym.flags() & INTERFACE) != 0 ?
  2004             supertype(bounds.head) : null;
  2005         return makeCompoundType(bounds, supertype);
  2008     /**
  2009      * A convenience wrapper for {@link #makeCompoundType(List)}; the
  2010      * arguments are converted to a list and passed to the other
  2011      * method.  Note that this might cause a symbol completion.
  2012      * Hence, this version of makeCompoundType may not be called
  2013      * during a classfile read.
  2014      */
  2015     public Type makeCompoundType(Type bound1, Type bound2) {
  2016         return makeCompoundType(List.of(bound1, bound2));
  2018     // </editor-fold>
  2020     // <editor-fold defaultstate="collapsed" desc="supertype">
  2021     public Type supertype(Type t) {
  2022         return supertype.visit(t);
  2024     // where
  2025         private UnaryVisitor<Type> supertype = new UnaryVisitor<Type>() {
  2027             public Type visitType(Type t, Void ignored) {
  2028                 // A note on wildcards: there is no good way to
  2029                 // determine a supertype for a super bounded wildcard.
  2030                 return null;
  2033             @Override
  2034             public Type visitClassType(ClassType t, Void ignored) {
  2035                 if (t.supertype_field == null) {
  2036                     Type supertype = ((ClassSymbol)t.tsym).getSuperclass();
  2037                     // An interface has no superclass; its supertype is Object.
  2038                     if (t.isInterface())
  2039                         supertype = ((ClassType)t.tsym.type).supertype_field;
  2040                     if (t.supertype_field == null) {
  2041                         List<Type> actuals = classBound(t).allparams();
  2042                         List<Type> formals = t.tsym.type.allparams();
  2043                         if (t.hasErasedSupertypes()) {
  2044                             t.supertype_field = erasureRecursive(supertype);
  2045                         } else if (formals.nonEmpty()) {
  2046                             t.supertype_field = subst(supertype, formals, actuals);
  2048                         else {
  2049                             t.supertype_field = supertype;
  2053                 return t.supertype_field;
  2056             /**
  2057              * The supertype is always a class type. If the type
  2058              * variable's bounds start with a class type, this is also
  2059              * the supertype.  Otherwise, the supertype is
  2060              * java.lang.Object.
  2061              */
  2062             @Override
  2063             public Type visitTypeVar(TypeVar t, Void ignored) {
  2064                 if (t.bound.tag == TYPEVAR ||
  2065                     (!t.bound.isCompound() && !t.bound.isInterface())) {
  2066                     return t.bound;
  2067                 } else {
  2068                     return supertype(t.bound);
  2072             @Override
  2073             public Type visitArrayType(ArrayType t, Void ignored) {
  2074                 if (t.elemtype.isPrimitive() || isSameType(t.elemtype, syms.objectType))
  2075                     return arraySuperType();
  2076                 else
  2077                     return new ArrayType(supertype(t.elemtype), t.tsym);
  2080             @Override
  2081             public Type visitErrorType(ErrorType t, Void ignored) {
  2082                 return t;
  2084         };
  2085     // </editor-fold>
  2087     // <editor-fold defaultstate="collapsed" desc="interfaces">
  2088     /**
  2089      * Return the interfaces implemented by this class.
  2090      */
  2091     public List<Type> interfaces(Type t) {
  2092         return interfaces.visit(t);
  2094     // where
  2095         private UnaryVisitor<List<Type>> interfaces = new UnaryVisitor<List<Type>>() {
  2097             public List<Type> visitType(Type t, Void ignored) {
  2098                 return List.nil();
  2101             @Override
  2102             public List<Type> visitClassType(ClassType t, Void ignored) {
  2103                 if (t.interfaces_field == null) {
  2104                     List<Type> interfaces = ((ClassSymbol)t.tsym).getInterfaces();
  2105                     if (t.interfaces_field == null) {
  2106                         // If t.interfaces_field is null, then t must
  2107                         // be a parameterized type (not to be confused
  2108                         // with a generic type declaration).
  2109                         // Terminology:
  2110                         //    Parameterized type: List<String>
  2111                         //    Generic type declaration: class List<E> { ... }
  2112                         // So t corresponds to List<String> and
  2113                         // t.tsym.type corresponds to List<E>.
  2114                         // The reason t must be parameterized type is
  2115                         // that completion will happen as a side
  2116                         // effect of calling
  2117                         // ClassSymbol.getInterfaces.  Since
  2118                         // t.interfaces_field is null after
  2119                         // completion, we can assume that t is not the
  2120                         // type of a class/interface declaration.
  2121                         Assert.check(t != t.tsym.type, t);
  2122                         List<Type> actuals = t.allparams();
  2123                         List<Type> formals = t.tsym.type.allparams();
  2124                         if (t.hasErasedSupertypes()) {
  2125                             t.interfaces_field = erasureRecursive(interfaces);
  2126                         } else if (formals.nonEmpty()) {
  2127                             t.interfaces_field =
  2128                                 upperBounds(subst(interfaces, formals, actuals));
  2130                         else {
  2131                             t.interfaces_field = interfaces;
  2135                 return t.interfaces_field;
  2138             @Override
  2139             public List<Type> visitTypeVar(TypeVar t, Void ignored) {
  2140                 if (t.bound.isCompound())
  2141                     return interfaces(t.bound);
  2143                 if (t.bound.isInterface())
  2144                     return List.of(t.bound);
  2146                 return List.nil();
  2148         };
  2149     // </editor-fold>
  2151     // <editor-fold defaultstate="collapsed" desc="isDerivedRaw">
  2152     Map<Type,Boolean> isDerivedRawCache = new HashMap<Type,Boolean>();
  2154     public boolean isDerivedRaw(Type t) {
  2155         Boolean result = isDerivedRawCache.get(t);
  2156         if (result == null) {
  2157             result = isDerivedRawInternal(t);
  2158             isDerivedRawCache.put(t, result);
  2160         return result;
  2163     public boolean isDerivedRawInternal(Type t) {
  2164         if (t.isErroneous())
  2165             return false;
  2166         return
  2167             t.isRaw() ||
  2168             supertype(t) != null && isDerivedRaw(supertype(t)) ||
  2169             isDerivedRaw(interfaces(t));
  2172     public boolean isDerivedRaw(List<Type> ts) {
  2173         List<Type> l = ts;
  2174         while (l.nonEmpty() && !isDerivedRaw(l.head)) l = l.tail;
  2175         return l.nonEmpty();
  2177     // </editor-fold>
  2179     // <editor-fold defaultstate="collapsed" desc="setBounds">
  2180     /**
  2181      * Set the bounds field of the given type variable to reflect a
  2182      * (possibly multiple) list of bounds.
  2183      * @param t                 a type variable
  2184      * @param bounds            the bounds, must be nonempty
  2185      * @param supertype         is objectType if all bounds are interfaces,
  2186      *                          null otherwise.
  2187      */
  2188     public void setBounds(TypeVar t, List<Type> bounds, Type supertype) {
  2189         if (bounds.tail.isEmpty())
  2190             t.bound = bounds.head;
  2191         else
  2192             t.bound = makeCompoundType(bounds, supertype);
  2193         t.rank_field = -1;
  2196     /**
  2197      * Same as {@link #setBounds(Type.TypeVar,List,Type)}, except that
  2198      * third parameter is computed directly, as follows: if all
  2199      * all bounds are interface types, the computed supertype is Object,
  2200      * otherwise the supertype is simply left null (in this case, the supertype
  2201      * is assumed to be the head of the bound list passed as second argument).
  2202      * Note that this check might cause a symbol completion. Hence, this version of
  2203      * setBounds may not be called during a classfile read.
  2204      */
  2205     public void setBounds(TypeVar t, List<Type> bounds) {
  2206         Type supertype = (bounds.head.tsym.flags() & INTERFACE) != 0 ?
  2207             syms.objectType : null;
  2208         setBounds(t, bounds, supertype);
  2209         t.rank_field = -1;
  2211     // </editor-fold>
  2213     // <editor-fold defaultstate="collapsed" desc="getBounds">
  2214     /**
  2215      * Return list of bounds of the given type variable.
  2216      */
  2217     public List<Type> getBounds(TypeVar t) {
  2218         if (t.bound.isErroneous() || !t.bound.isCompound())
  2219             return List.of(t.bound);
  2220         else if ((erasure(t).tsym.flags() & INTERFACE) == 0)
  2221             return interfaces(t).prepend(supertype(t));
  2222         else
  2223             // No superclass was given in bounds.
  2224             // In this case, supertype is Object, erasure is first interface.
  2225             return interfaces(t);
  2227     // </editor-fold>
  2229     // <editor-fold defaultstate="collapsed" desc="classBound">
  2230     /**
  2231      * If the given type is a (possibly selected) type variable,
  2232      * return the bounding class of this type, otherwise return the
  2233      * type itself.
  2234      */
  2235     public Type classBound(Type t) {
  2236         return classBound.visit(t);
  2238     // where
  2239         private UnaryVisitor<Type> classBound = new UnaryVisitor<Type>() {
  2241             public Type visitType(Type t, Void ignored) {
  2242                 return t;
  2245             @Override
  2246             public Type visitClassType(ClassType t, Void ignored) {
  2247                 Type outer1 = classBound(t.getEnclosingType());
  2248                 if (outer1 != t.getEnclosingType())
  2249                     return new ClassType(outer1, t.getTypeArguments(), t.tsym);
  2250                 else
  2251                     return t;
  2254             @Override
  2255             public Type visitTypeVar(TypeVar t, Void ignored) {
  2256                 return classBound(supertype(t));
  2259             @Override
  2260             public Type visitErrorType(ErrorType t, Void ignored) {
  2261                 return t;
  2263         };
  2264     // </editor-fold>
  2266     // <editor-fold defaultstate="collapsed" desc="sub signature / override equivalence">
  2267     /**
  2268      * Returns true iff the first signature is a <em>sub
  2269      * signature</em> of the other.  This is <b>not</b> an equivalence
  2270      * relation.
  2272      * @jls section 8.4.2.
  2273      * @see #overrideEquivalent(Type t, Type s)
  2274      * @param t first signature (possibly raw).
  2275      * @param s second signature (could be subjected to erasure).
  2276      * @return true if t is a sub signature of s.
  2277      */
  2278     public boolean isSubSignature(Type t, Type s) {
  2279         return isSubSignature(t, s, true);
  2282     public boolean isSubSignature(Type t, Type s, boolean strict) {
  2283         return hasSameArgs(t, s, strict) || hasSameArgs(t, erasure(s), strict);
  2286     /**
  2287      * Returns true iff these signatures are related by <em>override
  2288      * equivalence</em>.  This is the natural extension of
  2289      * isSubSignature to an equivalence relation.
  2291      * @jls section 8.4.2.
  2292      * @see #isSubSignature(Type t, Type s)
  2293      * @param t a signature (possible raw, could be subjected to
  2294      * erasure).
  2295      * @param s a signature (possible raw, could be subjected to
  2296      * erasure).
  2297      * @return true if either argument is a sub signature of the other.
  2298      */
  2299     public boolean overrideEquivalent(Type t, Type s) {
  2300         return hasSameArgs(t, s) ||
  2301             hasSameArgs(t, erasure(s)) || hasSameArgs(erasure(t), s);
  2304     public boolean overridesObjectMethod(TypeSymbol origin, Symbol msym) {
  2305         for (Scope.Entry e = syms.objectType.tsym.members().lookup(msym.name) ; e.scope != null ; e = e.next()) {
  2306             if (msym.overrides(e.sym, origin, Types.this, true)) {
  2307                 return true;
  2310         return false;
  2313     // <editor-fold defaultstate="collapsed" desc="Determining method implementation in given site">
  2314     class ImplementationCache {
  2316         private WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>> _map =
  2317                 new WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>>();
  2319         class Entry {
  2320             final MethodSymbol cachedImpl;
  2321             final Filter<Symbol> implFilter;
  2322             final boolean checkResult;
  2323             final int prevMark;
  2325             public Entry(MethodSymbol cachedImpl,
  2326                     Filter<Symbol> scopeFilter,
  2327                     boolean checkResult,
  2328                     int prevMark) {
  2329                 this.cachedImpl = cachedImpl;
  2330                 this.implFilter = scopeFilter;
  2331                 this.checkResult = checkResult;
  2332                 this.prevMark = prevMark;
  2335             boolean matches(Filter<Symbol> scopeFilter, boolean checkResult, int mark) {
  2336                 return this.implFilter == scopeFilter &&
  2337                         this.checkResult == checkResult &&
  2338                         this.prevMark == mark;
  2342         MethodSymbol get(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
  2343             SoftReference<Map<TypeSymbol, Entry>> ref_cache = _map.get(ms);
  2344             Map<TypeSymbol, Entry> cache = ref_cache != null ? ref_cache.get() : null;
  2345             if (cache == null) {
  2346                 cache = new HashMap<TypeSymbol, Entry>();
  2347                 _map.put(ms, new SoftReference<Map<TypeSymbol, Entry>>(cache));
  2349             Entry e = cache.get(origin);
  2350             CompoundScope members = membersClosure(origin.type, true);
  2351             if (e == null ||
  2352                     !e.matches(implFilter, checkResult, members.getMark())) {
  2353                 MethodSymbol impl = implementationInternal(ms, origin, checkResult, implFilter);
  2354                 cache.put(origin, new Entry(impl, implFilter, checkResult, members.getMark()));
  2355                 return impl;
  2357             else {
  2358                 return e.cachedImpl;
  2362         private MethodSymbol implementationInternal(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
  2363             for (Type t = origin.type; t.tag == CLASS || t.tag == TYPEVAR; t = supertype(t)) {
  2364                 while (t.tag == TYPEVAR)
  2365                     t = t.getUpperBound();
  2366                 TypeSymbol c = t.tsym;
  2367                 for (Scope.Entry e = c.members().lookup(ms.name, implFilter);
  2368                      e.scope != null;
  2369                      e = e.next(implFilter)) {
  2370                     if (e.sym != null &&
  2371                              e.sym.overrides(ms, origin, Types.this, checkResult))
  2372                         return (MethodSymbol)e.sym;
  2375             return null;
  2379     private ImplementationCache implCache = new ImplementationCache();
  2381     public MethodSymbol implementation(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
  2382         return implCache.get(ms, origin, checkResult, implFilter);
  2384     // </editor-fold>
  2386     // <editor-fold defaultstate="collapsed" desc="compute transitive closure of all members in given site">
  2387     class MembersClosureCache extends SimpleVisitor<CompoundScope, Boolean> {
  2389         private WeakHashMap<TypeSymbol, Entry> _map =
  2390                 new WeakHashMap<TypeSymbol, Entry>();
  2392         class Entry {
  2393             final boolean skipInterfaces;
  2394             final CompoundScope compoundScope;
  2396             public Entry(boolean skipInterfaces, CompoundScope compoundScope) {
  2397                 this.skipInterfaces = skipInterfaces;
  2398                 this.compoundScope = compoundScope;
  2401             boolean matches(boolean skipInterfaces) {
  2402                 return this.skipInterfaces == skipInterfaces;
  2406         List<TypeSymbol> seenTypes = List.nil();
  2408         /** members closure visitor methods **/
  2410         public CompoundScope visitType(Type t, Boolean skipInterface) {
  2411             return null;
  2414         @Override
  2415         public CompoundScope visitClassType(ClassType t, Boolean skipInterface) {
  2416             if (seenTypes.contains(t.tsym)) {
  2417                 //this is possible when an interface is implemented in multiple
  2418                 //superclasses, or when a classs hierarchy is circular - in such
  2419                 //cases we don't need to recurse (empty scope is returned)
  2420                 return new CompoundScope(t.tsym);
  2422             try {
  2423                 seenTypes = seenTypes.prepend(t.tsym);
  2424                 ClassSymbol csym = (ClassSymbol)t.tsym;
  2425                 Entry e = _map.get(csym);
  2426                 if (e == null || !e.matches(skipInterface)) {
  2427                     CompoundScope membersClosure = new CompoundScope(csym);
  2428                     if (!skipInterface) {
  2429                         for (Type i : interfaces(t)) {
  2430                             membersClosure.addSubScope(visit(i, skipInterface));
  2433                     membersClosure.addSubScope(visit(supertype(t), skipInterface));
  2434                     membersClosure.addSubScope(csym.members());
  2435                     e = new Entry(skipInterface, membersClosure);
  2436                     _map.put(csym, e);
  2438                 return e.compoundScope;
  2440             finally {
  2441                 seenTypes = seenTypes.tail;
  2445         @Override
  2446         public CompoundScope visitTypeVar(TypeVar t, Boolean skipInterface) {
  2447             return visit(t.getUpperBound(), skipInterface);
  2451     private MembersClosureCache membersCache = new MembersClosureCache();
  2453     public CompoundScope membersClosure(Type site, boolean skipInterface) {
  2454         return membersCache.visit(site, skipInterface);
  2456     // </editor-fold>
  2458     /**
  2459      * Does t have the same arguments as s?  It is assumed that both
  2460      * types are (possibly polymorphic) method types.  Monomorphic
  2461      * method types "have the same arguments", if their argument lists
  2462      * are equal.  Polymorphic method types "have the same arguments",
  2463      * if they have the same arguments after renaming all type
  2464      * variables of one to corresponding type variables in the other,
  2465      * where correspondence is by position in the type parameter list.
  2466      */
  2467     public boolean hasSameArgs(Type t, Type s) {
  2468         return hasSameArgs(t, s, true);
  2471     public boolean hasSameArgs(Type t, Type s, boolean strict) {
  2472         return hasSameArgs(t, s, strict ? hasSameArgs_strict : hasSameArgs_nonstrict);
  2475     private boolean hasSameArgs(Type t, Type s, TypeRelation hasSameArgs) {
  2476         return hasSameArgs.visit(t, s);
  2478     // where
  2479         private class HasSameArgs extends TypeRelation {
  2481             boolean strict;
  2483             public HasSameArgs(boolean strict) {
  2484                 this.strict = strict;
  2487             public Boolean visitType(Type t, Type s) {
  2488                 throw new AssertionError();
  2491             @Override
  2492             public Boolean visitMethodType(MethodType t, Type s) {
  2493                 return s.tag == METHOD
  2494                     && containsTypeEquivalent(t.argtypes, s.getParameterTypes());
  2497             @Override
  2498             public Boolean visitForAll(ForAll t, Type s) {
  2499                 if (s.tag != FORALL)
  2500                     return strict ? false : visitMethodType(t.asMethodType(), s);
  2502                 ForAll forAll = (ForAll)s;
  2503                 return hasSameBounds(t, forAll)
  2504                     && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
  2507             @Override
  2508             public Boolean visitErrorType(ErrorType t, Type s) {
  2509                 return false;
  2511         };
  2513         TypeRelation hasSameArgs_strict = new HasSameArgs(true);
  2514         TypeRelation hasSameArgs_nonstrict = new HasSameArgs(false);
  2516     // </editor-fold>
  2518     // <editor-fold defaultstate="collapsed" desc="subst">
  2519     public List<Type> subst(List<Type> ts,
  2520                             List<Type> from,
  2521                             List<Type> to) {
  2522         return new Subst(from, to).subst(ts);
  2525     /**
  2526      * Substitute all occurrences of a type in `from' with the
  2527      * corresponding type in `to' in 't'. Match lists `from' and `to'
  2528      * from the right: If lists have different length, discard leading
  2529      * elements of the longer list.
  2530      */
  2531     public Type subst(Type t, List<Type> from, List<Type> to) {
  2532         return new Subst(from, to).subst(t);
  2535     private class Subst extends UnaryVisitor<Type> {
  2536         List<Type> from;
  2537         List<Type> to;
  2539         public Subst(List<Type> from, List<Type> to) {
  2540             int fromLength = from.length();
  2541             int toLength = to.length();
  2542             while (fromLength > toLength) {
  2543                 fromLength--;
  2544                 from = from.tail;
  2546             while (fromLength < toLength) {
  2547                 toLength--;
  2548                 to = to.tail;
  2550             this.from = from;
  2551             this.to = to;
  2554         Type subst(Type t) {
  2555             if (from.tail == null)
  2556                 return t;
  2557             else
  2558                 return visit(t);
  2561         List<Type> subst(List<Type> ts) {
  2562             if (from.tail == null)
  2563                 return ts;
  2564             boolean wild = false;
  2565             if (ts.nonEmpty() && from.nonEmpty()) {
  2566                 Type head1 = subst(ts.head);
  2567                 List<Type> tail1 = subst(ts.tail);
  2568                 if (head1 != ts.head || tail1 != ts.tail)
  2569                     return tail1.prepend(head1);
  2571             return ts;
  2574         public Type visitType(Type t, Void ignored) {
  2575             return t;
  2578         @Override
  2579         public Type visitMethodType(MethodType t, Void ignored) {
  2580             List<Type> argtypes = subst(t.argtypes);
  2581             Type restype = subst(t.restype);
  2582             List<Type> thrown = subst(t.thrown);
  2583             if (argtypes == t.argtypes &&
  2584                 restype == t.restype &&
  2585                 thrown == t.thrown)
  2586                 return t;
  2587             else
  2588                 return new MethodType(argtypes, restype, thrown, t.tsym);
  2591         @Override
  2592         public Type visitTypeVar(TypeVar t, Void ignored) {
  2593             for (List<Type> from = this.from, to = this.to;
  2594                  from.nonEmpty();
  2595                  from = from.tail, to = to.tail) {
  2596                 if (t == from.head) {
  2597                     return to.head.withTypeVar(t);
  2600             return t;
  2603         @Override
  2604         public Type visitClassType(ClassType t, Void ignored) {
  2605             if (!t.isCompound()) {
  2606                 List<Type> typarams = t.getTypeArguments();
  2607                 List<Type> typarams1 = subst(typarams);
  2608                 Type outer = t.getEnclosingType();
  2609                 Type outer1 = subst(outer);
  2610                 if (typarams1 == typarams && outer1 == outer)
  2611                     return t;
  2612                 else
  2613                     return new ClassType(outer1, typarams1, t.tsym);
  2614             } else {
  2615                 Type st = subst(supertype(t));
  2616                 List<Type> is = upperBounds(subst(interfaces(t)));
  2617                 if (st == supertype(t) && is == interfaces(t))
  2618                     return t;
  2619                 else
  2620                     return makeCompoundType(is.prepend(st));
  2624         @Override
  2625         public Type visitWildcardType(WildcardType t, Void ignored) {
  2626             Type bound = t.type;
  2627             if (t.kind != BoundKind.UNBOUND)
  2628                 bound = subst(bound);
  2629             if (bound == t.type) {
  2630                 return t;
  2631             } else {
  2632                 if (t.isExtendsBound() && bound.isExtendsBound())
  2633                     bound = upperBound(bound);
  2634                 return new WildcardType(bound, t.kind, syms.boundClass, t.bound);
  2638         @Override
  2639         public Type visitArrayType(ArrayType t, Void ignored) {
  2640             Type elemtype = subst(t.elemtype);
  2641             if (elemtype == t.elemtype)
  2642                 return t;
  2643             else
  2644                 return new ArrayType(upperBound(elemtype), t.tsym);
  2647         @Override
  2648         public Type visitForAll(ForAll t, Void ignored) {
  2649             if (Type.containsAny(to, t.tvars)) {
  2650                 //perform alpha-renaming of free-variables in 't'
  2651                 //if 'to' types contain variables that are free in 't'
  2652                 List<Type> freevars = newInstances(t.tvars);
  2653                 t = new ForAll(freevars,
  2654                         Types.this.subst(t.qtype, t.tvars, freevars));
  2656             List<Type> tvars1 = substBounds(t.tvars, from, to);
  2657             Type qtype1 = subst(t.qtype);
  2658             if (tvars1 == t.tvars && qtype1 == t.qtype) {
  2659                 return t;
  2660             } else if (tvars1 == t.tvars) {
  2661                 return new ForAll(tvars1, qtype1);
  2662             } else {
  2663                 return new ForAll(tvars1, Types.this.subst(qtype1, t.tvars, tvars1));
  2667         @Override
  2668         public Type visitErrorType(ErrorType t, Void ignored) {
  2669             return t;
  2673     public List<Type> substBounds(List<Type> tvars,
  2674                                   List<Type> from,
  2675                                   List<Type> to) {
  2676         if (tvars.isEmpty())
  2677             return tvars;
  2678         ListBuffer<Type> newBoundsBuf = lb();
  2679         boolean changed = false;
  2680         // calculate new bounds
  2681         for (Type t : tvars) {
  2682             TypeVar tv = (TypeVar) t;
  2683             Type bound = subst(tv.bound, from, to);
  2684             if (bound != tv.bound)
  2685                 changed = true;
  2686             newBoundsBuf.append(bound);
  2688         if (!changed)
  2689             return tvars;
  2690         ListBuffer<Type> newTvars = lb();
  2691         // create new type variables without bounds
  2692         for (Type t : tvars) {
  2693             newTvars.append(new TypeVar(t.tsym, null, syms.botType));
  2695         // the new bounds should use the new type variables in place
  2696         // of the old
  2697         List<Type> newBounds = newBoundsBuf.toList();
  2698         from = tvars;
  2699         to = newTvars.toList();
  2700         for (; !newBounds.isEmpty(); newBounds = newBounds.tail) {
  2701             newBounds.head = subst(newBounds.head, from, to);
  2703         newBounds = newBoundsBuf.toList();
  2704         // set the bounds of new type variables to the new bounds
  2705         for (Type t : newTvars.toList()) {
  2706             TypeVar tv = (TypeVar) t;
  2707             tv.bound = newBounds.head;
  2708             newBounds = newBounds.tail;
  2710         return newTvars.toList();
  2713     public TypeVar substBound(TypeVar t, List<Type> from, List<Type> to) {
  2714         Type bound1 = subst(t.bound, from, to);
  2715         if (bound1 == t.bound)
  2716             return t;
  2717         else {
  2718             // create new type variable without bounds
  2719             TypeVar tv = new TypeVar(t.tsym, null, syms.botType);
  2720             // the new bound should use the new type variable in place
  2721             // of the old
  2722             tv.bound = subst(bound1, List.<Type>of(t), List.<Type>of(tv));
  2723             return tv;
  2726     // </editor-fold>
  2728     // <editor-fold defaultstate="collapsed" desc="hasSameBounds">
  2729     /**
  2730      * Does t have the same bounds for quantified variables as s?
  2731      */
  2732     boolean hasSameBounds(ForAll t, ForAll s) {
  2733         List<Type> l1 = t.tvars;
  2734         List<Type> l2 = s.tvars;
  2735         while (l1.nonEmpty() && l2.nonEmpty() &&
  2736                isSameType(l1.head.getUpperBound(),
  2737                           subst(l2.head.getUpperBound(),
  2738                                 s.tvars,
  2739                                 t.tvars))) {
  2740             l1 = l1.tail;
  2741             l2 = l2.tail;
  2743         return l1.isEmpty() && l2.isEmpty();
  2745     // </editor-fold>
  2747     // <editor-fold defaultstate="collapsed" desc="newInstances">
  2748     /** Create new vector of type variables from list of variables
  2749      *  changing all recursive bounds from old to new list.
  2750      */
  2751     public List<Type> newInstances(List<Type> tvars) {
  2752         List<Type> tvars1 = Type.map(tvars, newInstanceFun);
  2753         for (List<Type> l = tvars1; l.nonEmpty(); l = l.tail) {
  2754             TypeVar tv = (TypeVar) l.head;
  2755             tv.bound = subst(tv.bound, tvars, tvars1);
  2757         return tvars1;
  2759     static private Mapping newInstanceFun = new Mapping("newInstanceFun") {
  2760             public Type apply(Type t) { return new TypeVar(t.tsym, t.getUpperBound(), t.getLowerBound()); }
  2761         };
  2762     // </editor-fold>
  2764     public Type createMethodTypeWithParameters(Type original, List<Type> newParams) {
  2765         return original.accept(methodWithParameters, newParams);
  2767     // where
  2768         private final MapVisitor<List<Type>> methodWithParameters = new MapVisitor<List<Type>>() {
  2769             public Type visitType(Type t, List<Type> newParams) {
  2770                 throw new IllegalArgumentException("Not a method type: " + t);
  2772             public Type visitMethodType(MethodType t, List<Type> newParams) {
  2773                 return new MethodType(newParams, t.restype, t.thrown, t.tsym);
  2775             public Type visitForAll(ForAll t, List<Type> newParams) {
  2776                 return new ForAll(t.tvars, t.qtype.accept(this, newParams));
  2778         };
  2780     public Type createMethodTypeWithThrown(Type original, List<Type> newThrown) {
  2781         return original.accept(methodWithThrown, newThrown);
  2783     // where
  2784         private final MapVisitor<List<Type>> methodWithThrown = new MapVisitor<List<Type>>() {
  2785             public Type visitType(Type t, List<Type> newThrown) {
  2786                 throw new IllegalArgumentException("Not a method type: " + t);
  2788             public Type visitMethodType(MethodType t, List<Type> newThrown) {
  2789                 return new MethodType(t.argtypes, t.restype, newThrown, t.tsym);
  2791             public Type visitForAll(ForAll t, List<Type> newThrown) {
  2792                 return new ForAll(t.tvars, t.qtype.accept(this, newThrown));
  2794         };
  2796     public Type createMethodTypeWithReturn(Type original, Type newReturn) {
  2797         return original.accept(methodWithReturn, newReturn);
  2799     // where
  2800         private final MapVisitor<Type> methodWithReturn = new MapVisitor<Type>() {
  2801             public Type visitType(Type t, Type newReturn) {
  2802                 throw new IllegalArgumentException("Not a method type: " + t);
  2804             public Type visitMethodType(MethodType t, Type newReturn) {
  2805                 return new MethodType(t.argtypes, newReturn, t.thrown, t.tsym);
  2807             public Type visitForAll(ForAll t, Type newReturn) {
  2808                 return new ForAll(t.tvars, t.qtype.accept(this, newReturn));
  2810         };
  2812     // <editor-fold defaultstate="collapsed" desc="createErrorType">
  2813     public Type createErrorType(Type originalType) {
  2814         return new ErrorType(originalType, syms.errSymbol);
  2817     public Type createErrorType(ClassSymbol c, Type originalType) {
  2818         return new ErrorType(c, originalType);
  2821     public Type createErrorType(Name name, TypeSymbol container, Type originalType) {
  2822         return new ErrorType(name, container, originalType);
  2824     // </editor-fold>
  2826     // <editor-fold defaultstate="collapsed" desc="rank">
  2827     /**
  2828      * The rank of a class is the length of the longest path between
  2829      * the class and java.lang.Object in the class inheritance
  2830      * graph. Undefined for all but reference types.
  2831      */
  2832     public int rank(Type t) {
  2833         switch(t.tag) {
  2834         case CLASS: {
  2835             ClassType cls = (ClassType)t;
  2836             if (cls.rank_field < 0) {
  2837                 Name fullname = cls.tsym.getQualifiedName();
  2838                 if (fullname == names.java_lang_Object)
  2839                     cls.rank_field = 0;
  2840                 else {
  2841                     int r = rank(supertype(cls));
  2842                     for (List<Type> l = interfaces(cls);
  2843                          l.nonEmpty();
  2844                          l = l.tail) {
  2845                         if (rank(l.head) > r)
  2846                             r = rank(l.head);
  2848                     cls.rank_field = r + 1;
  2851             return cls.rank_field;
  2853         case TYPEVAR: {
  2854             TypeVar tvar = (TypeVar)t;
  2855             if (tvar.rank_field < 0) {
  2856                 int r = rank(supertype(tvar));
  2857                 for (List<Type> l = interfaces(tvar);
  2858                      l.nonEmpty();
  2859                      l = l.tail) {
  2860                     if (rank(l.head) > r) r = rank(l.head);
  2862                 tvar.rank_field = r + 1;
  2864             return tvar.rank_field;
  2866         case ERROR:
  2867             return 0;
  2868         default:
  2869             throw new AssertionError();
  2872     // </editor-fold>
  2874     /**
  2875      * Helper method for generating a string representation of a given type
  2876      * accordingly to a given locale
  2877      */
  2878     public String toString(Type t, Locale locale) {
  2879         return Printer.createStandardPrinter(messages).visit(t, locale);
  2882     /**
  2883      * Helper method for generating a string representation of a given type
  2884      * accordingly to a given locale
  2885      */
  2886     public String toString(Symbol t, Locale locale) {
  2887         return Printer.createStandardPrinter(messages).visit(t, locale);
  2890     // <editor-fold defaultstate="collapsed" desc="toString">
  2891     /**
  2892      * This toString is slightly more descriptive than the one on Type.
  2894      * @deprecated Types.toString(Type t, Locale l) provides better support
  2895      * for localization
  2896      */
  2897     @Deprecated
  2898     public String toString(Type t) {
  2899         if (t.tag == FORALL) {
  2900             ForAll forAll = (ForAll)t;
  2901             return typaramsString(forAll.tvars) + forAll.qtype;
  2903         return "" + t;
  2905     // where
  2906         private String typaramsString(List<Type> tvars) {
  2907             StringBuilder s = new StringBuilder();
  2908             s.append('<');
  2909             boolean first = true;
  2910             for (Type t : tvars) {
  2911                 if (!first) s.append(", ");
  2912                 first = false;
  2913                 appendTyparamString(((TypeVar)t), s);
  2915             s.append('>');
  2916             return s.toString();
  2918         private void appendTyparamString(TypeVar t, StringBuilder buf) {
  2919             buf.append(t);
  2920             if (t.bound == null ||
  2921                 t.bound.tsym.getQualifiedName() == names.java_lang_Object)
  2922                 return;
  2923             buf.append(" extends "); // Java syntax; no need for i18n
  2924             Type bound = t.bound;
  2925             if (!bound.isCompound()) {
  2926                 buf.append(bound);
  2927             } else if ((erasure(t).tsym.flags() & INTERFACE) == 0) {
  2928                 buf.append(supertype(t));
  2929                 for (Type intf : interfaces(t)) {
  2930                     buf.append('&');
  2931                     buf.append(intf);
  2933             } else {
  2934                 // No superclass was given in bounds.
  2935                 // In this case, supertype is Object, erasure is first interface.
  2936                 boolean first = true;
  2937                 for (Type intf : interfaces(t)) {
  2938                     if (!first) buf.append('&');
  2939                     first = false;
  2940                     buf.append(intf);
  2944     // </editor-fold>
  2946     // <editor-fold defaultstate="collapsed" desc="Determining least upper bounds of types">
  2947     /**
  2948      * A cache for closures.
  2950      * <p>A closure is a list of all the supertypes and interfaces of
  2951      * a class or interface type, ordered by ClassSymbol.precedes
  2952      * (that is, subclasses come first, arbitrary but fixed
  2953      * otherwise).
  2954      */
  2955     private Map<Type,List<Type>> closureCache = new HashMap<Type,List<Type>>();
  2957     /**
  2958      * Returns the closure of a class or interface type.
  2959      */
  2960     public List<Type> closure(Type t) {
  2961         List<Type> cl = closureCache.get(t);
  2962         if (cl == null) {
  2963             Type st = supertype(t);
  2964             if (!t.isCompound()) {
  2965                 if (st.tag == CLASS) {
  2966                     cl = insert(closure(st), t);
  2967                 } else if (st.tag == TYPEVAR) {
  2968                     cl = closure(st).prepend(t);
  2969                 } else {
  2970                     cl = List.of(t);
  2972             } else {
  2973                 cl = closure(supertype(t));
  2975             for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail)
  2976                 cl = union(cl, closure(l.head));
  2977             closureCache.put(t, cl);
  2979         return cl;
  2982     /**
  2983      * Insert a type in a closure
  2984      */
  2985     public List<Type> insert(List<Type> cl, Type t) {
  2986         if (cl.isEmpty() || t.tsym.precedes(cl.head.tsym, this)) {
  2987             return cl.prepend(t);
  2988         } else if (cl.head.tsym.precedes(t.tsym, this)) {
  2989             return insert(cl.tail, t).prepend(cl.head);
  2990         } else {
  2991             return cl;
  2995     /**
  2996      * Form the union of two closures
  2997      */
  2998     public List<Type> union(List<Type> cl1, List<Type> cl2) {
  2999         if (cl1.isEmpty()) {
  3000             return cl2;
  3001         } else if (cl2.isEmpty()) {
  3002             return cl1;
  3003         } else if (cl1.head.tsym.precedes(cl2.head.tsym, this)) {
  3004             return union(cl1.tail, cl2).prepend(cl1.head);
  3005         } else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) {
  3006             return union(cl1, cl2.tail).prepend(cl2.head);
  3007         } else {
  3008             return union(cl1.tail, cl2.tail).prepend(cl1.head);
  3012     /**
  3013      * Intersect two closures
  3014      */
  3015     public List<Type> intersect(List<Type> cl1, List<Type> cl2) {
  3016         if (cl1 == cl2)
  3017             return cl1;
  3018         if (cl1.isEmpty() || cl2.isEmpty())
  3019             return List.nil();
  3020         if (cl1.head.tsym.precedes(cl2.head.tsym, this))
  3021             return intersect(cl1.tail, cl2);
  3022         if (cl2.head.tsym.precedes(cl1.head.tsym, this))
  3023             return intersect(cl1, cl2.tail);
  3024         if (isSameType(cl1.head, cl2.head))
  3025             return intersect(cl1.tail, cl2.tail).prepend(cl1.head);
  3026         if (cl1.head.tsym == cl2.head.tsym &&
  3027             cl1.head.tag == CLASS && cl2.head.tag == CLASS) {
  3028             if (cl1.head.isParameterized() && cl2.head.isParameterized()) {
  3029                 Type merge = merge(cl1.head,cl2.head);
  3030                 return intersect(cl1.tail, cl2.tail).prepend(merge);
  3032             if (cl1.head.isRaw() || cl2.head.isRaw())
  3033                 return intersect(cl1.tail, cl2.tail).prepend(erasure(cl1.head));
  3035         return intersect(cl1.tail, cl2.tail);
  3037     // where
  3038         class TypePair {
  3039             final Type t1;
  3040             final Type t2;
  3041             TypePair(Type t1, Type t2) {
  3042                 this.t1 = t1;
  3043                 this.t2 = t2;
  3045             @Override
  3046             public int hashCode() {
  3047                 return 127 * Types.hashCode(t1) + Types.hashCode(t2);
  3049             @Override
  3050             public boolean equals(Object obj) {
  3051                 if (!(obj instanceof TypePair))
  3052                     return false;
  3053                 TypePair typePair = (TypePair)obj;
  3054                 return isSameType(t1, typePair.t1)
  3055                     && isSameType(t2, typePair.t2);
  3058         Set<TypePair> mergeCache = new HashSet<TypePair>();
  3059         private Type merge(Type c1, Type c2) {
  3060             ClassType class1 = (ClassType) c1;
  3061             List<Type> act1 = class1.getTypeArguments();
  3062             ClassType class2 = (ClassType) c2;
  3063             List<Type> act2 = class2.getTypeArguments();
  3064             ListBuffer<Type> merged = new ListBuffer<Type>();
  3065             List<Type> typarams = class1.tsym.type.getTypeArguments();
  3067             while (act1.nonEmpty() && act2.nonEmpty() && typarams.nonEmpty()) {
  3068                 if (containsType(act1.head, act2.head)) {
  3069                     merged.append(act1.head);
  3070                 } else if (containsType(act2.head, act1.head)) {
  3071                     merged.append(act2.head);
  3072                 } else {
  3073                     TypePair pair = new TypePair(c1, c2);
  3074                     Type m;
  3075                     if (mergeCache.add(pair)) {
  3076                         m = new WildcardType(lub(upperBound(act1.head),
  3077                                                  upperBound(act2.head)),
  3078                                              BoundKind.EXTENDS,
  3079                                              syms.boundClass);
  3080                         mergeCache.remove(pair);
  3081                     } else {
  3082                         m = new WildcardType(syms.objectType,
  3083                                              BoundKind.UNBOUND,
  3084                                              syms.boundClass);
  3086                     merged.append(m.withTypeVar(typarams.head));
  3088                 act1 = act1.tail;
  3089                 act2 = act2.tail;
  3090                 typarams = typarams.tail;
  3092             Assert.check(act1.isEmpty() && act2.isEmpty() && typarams.isEmpty());
  3093             return new ClassType(class1.getEnclosingType(), merged.toList(), class1.tsym);
  3096     /**
  3097      * Return the minimum type of a closure, a compound type if no
  3098      * unique minimum exists.
  3099      */
  3100     private Type compoundMin(List<Type> cl) {
  3101         if (cl.isEmpty()) return syms.objectType;
  3102         List<Type> compound = closureMin(cl);
  3103         if (compound.isEmpty())
  3104             return null;
  3105         else if (compound.tail.isEmpty())
  3106             return compound.head;
  3107         else
  3108             return makeCompoundType(compound);
  3111     /**
  3112      * Return the minimum types of a closure, suitable for computing
  3113      * compoundMin or glb.
  3114      */
  3115     private List<Type> closureMin(List<Type> cl) {
  3116         ListBuffer<Type> classes = lb();
  3117         ListBuffer<Type> interfaces = lb();
  3118         while (!cl.isEmpty()) {
  3119             Type current = cl.head;
  3120             if (current.isInterface())
  3121                 interfaces.append(current);
  3122             else
  3123                 classes.append(current);
  3124             ListBuffer<Type> candidates = lb();
  3125             for (Type t : cl.tail) {
  3126                 if (!isSubtypeNoCapture(current, t))
  3127                     candidates.append(t);
  3129             cl = candidates.toList();
  3131         return classes.appendList(interfaces).toList();
  3134     /**
  3135      * Return the least upper bound of pair of types.  if the lub does
  3136      * not exist return null.
  3137      */
  3138     public Type lub(Type t1, Type t2) {
  3139         return lub(List.of(t1, t2));
  3142     /**
  3143      * Return the least upper bound (lub) of set of types.  If the lub
  3144      * does not exist return the type of null (bottom).
  3145      */
  3146     public Type lub(List<Type> ts) {
  3147         final int ARRAY_BOUND = 1;
  3148         final int CLASS_BOUND = 2;
  3149         int boundkind = 0;
  3150         for (Type t : ts) {
  3151             switch (t.tag) {
  3152             case CLASS:
  3153                 boundkind |= CLASS_BOUND;
  3154                 break;
  3155             case ARRAY:
  3156                 boundkind |= ARRAY_BOUND;
  3157                 break;
  3158             case  TYPEVAR:
  3159                 do {
  3160                     t = t.getUpperBound();
  3161                 } while (t.tag == TYPEVAR);
  3162                 if (t.tag == ARRAY) {
  3163                     boundkind |= ARRAY_BOUND;
  3164                 } else {
  3165                     boundkind |= CLASS_BOUND;
  3167                 break;
  3168             default:
  3169                 if (t.isPrimitive())
  3170                     return syms.errType;
  3173         switch (boundkind) {
  3174         case 0:
  3175             return syms.botType;
  3177         case ARRAY_BOUND:
  3178             // calculate lub(A[], B[])
  3179             List<Type> elements = Type.map(ts, elemTypeFun);
  3180             for (Type t : elements) {
  3181                 if (t.isPrimitive()) {
  3182                     // if a primitive type is found, then return
  3183                     // arraySuperType unless all the types are the
  3184                     // same
  3185                     Type first = ts.head;
  3186                     for (Type s : ts.tail) {
  3187                         if (!isSameType(first, s)) {
  3188                              // lub(int[], B[]) is Cloneable & Serializable
  3189                             return arraySuperType();
  3192                     // all the array types are the same, return one
  3193                     // lub(int[], int[]) is int[]
  3194                     return first;
  3197             // lub(A[], B[]) is lub(A, B)[]
  3198             return new ArrayType(lub(elements), syms.arrayClass);
  3200         case CLASS_BOUND:
  3201             // calculate lub(A, B)
  3202             while (ts.head.tag != CLASS && ts.head.tag != TYPEVAR)
  3203                 ts = ts.tail;
  3204             Assert.check(!ts.isEmpty());
  3205             //step 1 - compute erased candidate set (EC)
  3206             List<Type> cl = erasedSupertypes(ts.head);
  3207             for (Type t : ts.tail) {
  3208                 if (t.tag == CLASS || t.tag == TYPEVAR)
  3209                     cl = intersect(cl, erasedSupertypes(t));
  3211             //step 2 - compute minimal erased candidate set (MEC)
  3212             List<Type> mec = closureMin(cl);
  3213             //step 3 - for each element G in MEC, compute lci(Inv(G))
  3214             List<Type> candidates = List.nil();
  3215             for (Type erasedSupertype : mec) {
  3216                 List<Type> lci = List.of(asSuper(ts.head, erasedSupertype.tsym));
  3217                 for (Type t : ts) {
  3218                     lci = intersect(lci, List.of(asSuper(t, erasedSupertype.tsym)));
  3220                 candidates = candidates.appendList(lci);
  3222             //step 4 - let MEC be { G1, G2 ... Gn }, then we have that
  3223             //lub = lci(Inv(G1)) & lci(Inv(G2)) & ... & lci(Inv(Gn))
  3224             return compoundMin(candidates);
  3226         default:
  3227             // calculate lub(A, B[])
  3228             List<Type> classes = List.of(arraySuperType());
  3229             for (Type t : ts) {
  3230                 if (t.tag != ARRAY) // Filter out any arrays
  3231                     classes = classes.prepend(t);
  3233             // lub(A, B[]) is lub(A, arraySuperType)
  3234             return lub(classes);
  3237     // where
  3238         List<Type> erasedSupertypes(Type t) {
  3239             ListBuffer<Type> buf = lb();
  3240             for (Type sup : closure(t)) {
  3241                 if (sup.tag == TYPEVAR) {
  3242                     buf.append(sup);
  3243                 } else {
  3244                     buf.append(erasure(sup));
  3247             return buf.toList();
  3250         private Type arraySuperType = null;
  3251         private Type arraySuperType() {
  3252             // initialized lazily to avoid problems during compiler startup
  3253             if (arraySuperType == null) {
  3254                 synchronized (this) {
  3255                     if (arraySuperType == null) {
  3256                         // JLS 10.8: all arrays implement Cloneable and Serializable.
  3257                         arraySuperType = makeCompoundType(List.of(syms.serializableType,
  3258                                                                   syms.cloneableType),
  3259                                                           syms.objectType);
  3263             return arraySuperType;
  3265     // </editor-fold>
  3267     // <editor-fold defaultstate="collapsed" desc="Greatest lower bound">
  3268     public Type glb(List<Type> ts) {
  3269         Type t1 = ts.head;
  3270         for (Type t2 : ts.tail) {
  3271             if (t1.isErroneous())
  3272                 return t1;
  3273             t1 = glb(t1, t2);
  3275         return t1;
  3277     //where
  3278     public Type glb(Type t, Type s) {
  3279         if (s == null)
  3280             return t;
  3281         else if (t.isPrimitive() || s.isPrimitive())
  3282             return syms.errType;
  3283         else if (isSubtypeNoCapture(t, s))
  3284             return t;
  3285         else if (isSubtypeNoCapture(s, t))
  3286             return s;
  3288         List<Type> closure = union(closure(t), closure(s));
  3289         List<Type> bounds = closureMin(closure);
  3291         if (bounds.isEmpty()) {             // length == 0
  3292             return syms.objectType;
  3293         } else if (bounds.tail.isEmpty()) { // length == 1
  3294             return bounds.head;
  3295         } else {                            // length > 1
  3296             int classCount = 0;
  3297             for (Type bound : bounds)
  3298                 if (!bound.isInterface())
  3299                     classCount++;
  3300             if (classCount > 1)
  3301                 return createErrorType(t);
  3303         return makeCompoundType(bounds);
  3305     // </editor-fold>
  3307     // <editor-fold defaultstate="collapsed" desc="hashCode">
  3308     /**
  3309      * Compute a hash code on a type.
  3310      */
  3311     public static int hashCode(Type t) {
  3312         return hashCode.visit(t);
  3314     // where
  3315         private static final UnaryVisitor<Integer> hashCode = new UnaryVisitor<Integer>() {
  3317             public Integer visitType(Type t, Void ignored) {
  3318                 return t.tag.ordinal();
  3321             @Override
  3322             public Integer visitClassType(ClassType t, Void ignored) {
  3323                 int result = visit(t.getEnclosingType());
  3324                 result *= 127;
  3325                 result += t.tsym.flatName().hashCode();
  3326                 for (Type s : t.getTypeArguments()) {
  3327                     result *= 127;
  3328                     result += visit(s);
  3330                 return result;
  3333             @Override
  3334             public Integer visitWildcardType(WildcardType t, Void ignored) {
  3335                 int result = t.kind.hashCode();
  3336                 if (t.type != null) {
  3337                     result *= 127;
  3338                     result += visit(t.type);
  3340                 return result;
  3343             @Override
  3344             public Integer visitArrayType(ArrayType t, Void ignored) {
  3345                 return visit(t.elemtype) + 12;
  3348             @Override
  3349             public Integer visitTypeVar(TypeVar t, Void ignored) {
  3350                 return System.identityHashCode(t.tsym);
  3353             @Override
  3354             public Integer visitUndetVar(UndetVar t, Void ignored) {
  3355                 return System.identityHashCode(t);
  3358             @Override
  3359             public Integer visitErrorType(ErrorType t, Void ignored) {
  3360                 return 0;
  3362         };
  3363     // </editor-fold>
  3365     // <editor-fold defaultstate="collapsed" desc="Return-Type-Substitutable">
  3366     /**
  3367      * Does t have a result that is a subtype of the result type of s,
  3368      * suitable for covariant returns?  It is assumed that both types
  3369      * are (possibly polymorphic) method types.  Monomorphic method
  3370      * types are handled in the obvious way.  Polymorphic method types
  3371      * require renaming all type variables of one to corresponding
  3372      * type variables in the other, where correspondence is by
  3373      * position in the type parameter list. */
  3374     public boolean resultSubtype(Type t, Type s, Warner warner) {
  3375         List<Type> tvars = t.getTypeArguments();
  3376         List<Type> svars = s.getTypeArguments();
  3377         Type tres = t.getReturnType();
  3378         Type sres = subst(s.getReturnType(), svars, tvars);
  3379         return covariantReturnType(tres, sres, warner);
  3382     /**
  3383      * Return-Type-Substitutable.
  3384      * @jls section 8.4.5
  3385      */
  3386     public boolean returnTypeSubstitutable(Type r1, Type r2) {
  3387         if (hasSameArgs(r1, r2))
  3388             return resultSubtype(r1, r2, Warner.noWarnings);
  3389         else
  3390             return covariantReturnType(r1.getReturnType(),
  3391                                        erasure(r2.getReturnType()),
  3392                                        Warner.noWarnings);
  3395     public boolean returnTypeSubstitutable(Type r1,
  3396                                            Type r2, Type r2res,
  3397                                            Warner warner) {
  3398         if (isSameType(r1.getReturnType(), r2res))
  3399             return true;
  3400         if (r1.getReturnType().isPrimitive() || r2res.isPrimitive())
  3401             return false;
  3403         if (hasSameArgs(r1, r2))
  3404             return covariantReturnType(r1.getReturnType(), r2res, warner);
  3405         if (!allowCovariantReturns)
  3406             return false;
  3407         if (isSubtypeUnchecked(r1.getReturnType(), r2res, warner))
  3408             return true;
  3409         if (!isSubtype(r1.getReturnType(), erasure(r2res)))
  3410             return false;
  3411         warner.warn(LintCategory.UNCHECKED);
  3412         return true;
  3415     /**
  3416      * Is t an appropriate return type in an overrider for a
  3417      * method that returns s?
  3418      */
  3419     public boolean covariantReturnType(Type t, Type s, Warner warner) {
  3420         return
  3421             isSameType(t, s) ||
  3422             allowCovariantReturns &&
  3423             !t.isPrimitive() &&
  3424             !s.isPrimitive() &&
  3425             isAssignable(t, s, warner);
  3427     // </editor-fold>
  3429     // <editor-fold defaultstate="collapsed" desc="Box/unbox support">
  3430     /**
  3431      * Return the class that boxes the given primitive.
  3432      */
  3433     public ClassSymbol boxedClass(Type t) {
  3434         return reader.enterClass(syms.boxedName[t.tag.ordinal()]);
  3437     /**
  3438      * Return the boxed type if 't' is primitive, otherwise return 't' itself.
  3439      */
  3440     public Type boxedTypeOrType(Type t) {
  3441         return t.isPrimitive() ?
  3442             boxedClass(t).type :
  3443             t;
  3446     /**
  3447      * Return the primitive type corresponding to a boxed type.
  3448      */
  3449     public Type unboxedType(Type t) {
  3450         if (allowBoxing) {
  3451             for (int i=0; i<syms.boxedName.length; i++) {
  3452                 Name box = syms.boxedName[i];
  3453                 if (box != null &&
  3454                     asSuper(t, reader.enterClass(box)) != null)
  3455                     return syms.typeOfTag[i];
  3458         return Type.noType;
  3461     /**
  3462      * Return the unboxed type if 't' is a boxed class, otherwise return 't' itself.
  3463      */
  3464     public Type unboxedTypeOrType(Type t) {
  3465         Type unboxedType = unboxedType(t);
  3466         return unboxedType.tag == NONE ? t : unboxedType;
  3468     // </editor-fold>
  3470     // <editor-fold defaultstate="collapsed" desc="Capture conversion">
  3471     /*
  3472      * JLS 5.1.10 Capture Conversion:
  3474      * Let G name a generic type declaration with n formal type
  3475      * parameters A1 ... An with corresponding bounds U1 ... Un. There
  3476      * exists a capture conversion from G<T1 ... Tn> to G<S1 ... Sn>,
  3477      * where, for 1 <= i <= n:
  3479      * + If Ti is a wildcard type argument (4.5.1) of the form ? then
  3480      *   Si is a fresh type variable whose upper bound is
  3481      *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is the null
  3482      *   type.
  3484      * + If Ti is a wildcard type argument of the form ? extends Bi,
  3485      *   then Si is a fresh type variable whose upper bound is
  3486      *   glb(Bi, Ui[A1 := S1, ..., An := Sn]) and whose lower bound is
  3487      *   the null type, where glb(V1,... ,Vm) is V1 & ... & Vm. It is
  3488      *   a compile-time error if for any two classes (not interfaces)
  3489      *   Vi and Vj,Vi is not a subclass of Vj or vice versa.
  3491      * + If Ti is a wildcard type argument of the form ? super Bi,
  3492      *   then Si is a fresh type variable whose upper bound is
  3493      *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is Bi.
  3495      * + Otherwise, Si = Ti.
  3497      * Capture conversion on any type other than a parameterized type
  3498      * (4.5) acts as an identity conversion (5.1.1). Capture
  3499      * conversions never require a special action at run time and
  3500      * therefore never throw an exception at run time.
  3502      * Capture conversion is not applied recursively.
  3503      */
  3504     /**
  3505      * Capture conversion as specified by the JLS.
  3506      */
  3508     public List<Type> capture(List<Type> ts) {
  3509         List<Type> buf = List.nil();
  3510         for (Type t : ts) {
  3511             buf = buf.prepend(capture(t));
  3513         return buf.reverse();
  3515     public Type capture(Type t) {
  3516         if (t.tag != CLASS)
  3517             return t;
  3518         if (t.getEnclosingType() != Type.noType) {
  3519             Type capturedEncl = capture(t.getEnclosingType());
  3520             if (capturedEncl != t.getEnclosingType()) {
  3521                 Type type1 = memberType(capturedEncl, t.tsym);
  3522                 t = subst(type1, t.tsym.type.getTypeArguments(), t.getTypeArguments());
  3525         ClassType cls = (ClassType)t;
  3526         if (cls.isRaw() || !cls.isParameterized())
  3527             return cls;
  3529         ClassType G = (ClassType)cls.asElement().asType();
  3530         List<Type> A = G.getTypeArguments();
  3531         List<Type> T = cls.getTypeArguments();
  3532         List<Type> S = freshTypeVariables(T);
  3534         List<Type> currentA = A;
  3535         List<Type> currentT = T;
  3536         List<Type> currentS = S;
  3537         boolean captured = false;
  3538         while (!currentA.isEmpty() &&
  3539                !currentT.isEmpty() &&
  3540                !currentS.isEmpty()) {
  3541             if (currentS.head != currentT.head) {
  3542                 captured = true;
  3543                 WildcardType Ti = (WildcardType)currentT.head;
  3544                 Type Ui = currentA.head.getUpperBound();
  3545                 CapturedType Si = (CapturedType)currentS.head;
  3546                 if (Ui == null)
  3547                     Ui = syms.objectType;
  3548                 switch (Ti.kind) {
  3549                 case UNBOUND:
  3550                     Si.bound = subst(Ui, A, S);
  3551                     Si.lower = syms.botType;
  3552                     break;
  3553                 case EXTENDS:
  3554                     Si.bound = glb(Ti.getExtendsBound(), subst(Ui, A, S));
  3555                     Si.lower = syms.botType;
  3556                     break;
  3557                 case SUPER:
  3558                     Si.bound = subst(Ui, A, S);
  3559                     Si.lower = Ti.getSuperBound();
  3560                     break;
  3562                 if (Si.bound == Si.lower)
  3563                     currentS.head = Si.bound;
  3565             currentA = currentA.tail;
  3566             currentT = currentT.tail;
  3567             currentS = currentS.tail;
  3569         if (!currentA.isEmpty() || !currentT.isEmpty() || !currentS.isEmpty())
  3570             return erasure(t); // some "rare" type involved
  3572         if (captured)
  3573             return new ClassType(cls.getEnclosingType(), S, cls.tsym);
  3574         else
  3575             return t;
  3577     // where
  3578         public List<Type> freshTypeVariables(List<Type> types) {
  3579             ListBuffer<Type> result = lb();
  3580             for (Type t : types) {
  3581                 if (t.tag == WILDCARD) {
  3582                     Type bound = ((WildcardType)t).getExtendsBound();
  3583                     if (bound == null)
  3584                         bound = syms.objectType;
  3585                     result.append(new CapturedType(capturedName,
  3586                                                    syms.noSymbol,
  3587                                                    bound,
  3588                                                    syms.botType,
  3589                                                    (WildcardType)t));
  3590                 } else {
  3591                     result.append(t);
  3594             return result.toList();
  3596     // </editor-fold>
  3598     // <editor-fold defaultstate="collapsed" desc="Internal utility methods">
  3599     private List<Type> upperBounds(List<Type> ss) {
  3600         if (ss.isEmpty()) return ss;
  3601         Type head = upperBound(ss.head);
  3602         List<Type> tail = upperBounds(ss.tail);
  3603         if (head != ss.head || tail != ss.tail)
  3604             return tail.prepend(head);
  3605         else
  3606             return ss;
  3609     private boolean sideCast(Type from, Type to, Warner warn) {
  3610         // We are casting from type $from$ to type $to$, which are
  3611         // non-final unrelated types.  This method
  3612         // tries to reject a cast by transferring type parameters
  3613         // from $to$ to $from$ by common superinterfaces.
  3614         boolean reverse = false;
  3615         Type target = to;
  3616         if ((to.tsym.flags() & INTERFACE) == 0) {
  3617             Assert.check((from.tsym.flags() & INTERFACE) != 0);
  3618             reverse = true;
  3619             to = from;
  3620             from = target;
  3622         List<Type> commonSupers = superClosure(to, erasure(from));
  3623         boolean giveWarning = commonSupers.isEmpty();
  3624         // The arguments to the supers could be unified here to
  3625         // get a more accurate analysis
  3626         while (commonSupers.nonEmpty()) {
  3627             Type t1 = asSuper(from, commonSupers.head.tsym);
  3628             Type t2 = commonSupers.head; // same as asSuper(to, commonSupers.head.tsym);
  3629             if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
  3630                 return false;
  3631             giveWarning = giveWarning || (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2));
  3632             commonSupers = commonSupers.tail;
  3634         if (giveWarning && !isReifiable(reverse ? from : to))
  3635             warn.warn(LintCategory.UNCHECKED);
  3636         if (!allowCovariantReturns)
  3637             // reject if there is a common method signature with
  3638             // incompatible return types.
  3639             chk.checkCompatibleAbstracts(warn.pos(), from, to);
  3640         return true;
  3643     private boolean sideCastFinal(Type from, Type to, Warner warn) {
  3644         // We are casting from type $from$ to type $to$, which are
  3645         // unrelated types one of which is final and the other of
  3646         // which is an interface.  This method
  3647         // tries to reject a cast by transferring type parameters
  3648         // from the final class to the interface.
  3649         boolean reverse = false;
  3650         Type target = to;
  3651         if ((to.tsym.flags() & INTERFACE) == 0) {
  3652             Assert.check((from.tsym.flags() & INTERFACE) != 0);
  3653             reverse = true;
  3654             to = from;
  3655             from = target;
  3657         Assert.check((from.tsym.flags() & FINAL) != 0);
  3658         Type t1 = asSuper(from, to.tsym);
  3659         if (t1 == null) return false;
  3660         Type t2 = to;
  3661         if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
  3662             return false;
  3663         if (!allowCovariantReturns)
  3664             // reject if there is a common method signature with
  3665             // incompatible return types.
  3666             chk.checkCompatibleAbstracts(warn.pos(), from, to);
  3667         if (!isReifiable(target) &&
  3668             (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2)))
  3669             warn.warn(LintCategory.UNCHECKED);
  3670         return true;
  3673     private boolean giveWarning(Type from, Type to) {
  3674         Type subFrom = asSub(from, to.tsym);
  3675         return to.isParameterized() &&
  3676                 (!(isUnbounded(to) ||
  3677                 isSubtype(from, to) ||
  3678                 ((subFrom != null) && containsType(to.allparams(), subFrom.allparams()))));
  3681     private List<Type> superClosure(Type t, Type s) {
  3682         List<Type> cl = List.nil();
  3683         for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
  3684             if (isSubtype(s, erasure(l.head))) {
  3685                 cl = insert(cl, l.head);
  3686             } else {
  3687                 cl = union(cl, superClosure(l.head, s));
  3690         return cl;
  3693     private boolean containsTypeEquivalent(Type t, Type s) {
  3694         return
  3695             isSameType(t, s) || // shortcut
  3696             containsType(t, s) && containsType(s, t);
  3699     // <editor-fold defaultstate="collapsed" desc="adapt">
  3700     /**
  3701      * Adapt a type by computing a substitution which maps a source
  3702      * type to a target type.
  3704      * @param source    the source type
  3705      * @param target    the target type
  3706      * @param from      the type variables of the computed substitution
  3707      * @param to        the types of the computed substitution.
  3708      */
  3709     public void adapt(Type source,
  3710                        Type target,
  3711                        ListBuffer<Type> from,
  3712                        ListBuffer<Type> to) throws AdaptFailure {
  3713         new Adapter(from, to).adapt(source, target);
  3716     class Adapter extends SimpleVisitor<Void, Type> {
  3718         ListBuffer<Type> from;
  3719         ListBuffer<Type> to;
  3720         Map<Symbol,Type> mapping;
  3722         Adapter(ListBuffer<Type> from, ListBuffer<Type> to) {
  3723             this.from = from;
  3724             this.to = to;
  3725             mapping = new HashMap<Symbol,Type>();
  3728         public void adapt(Type source, Type target) throws AdaptFailure {
  3729             visit(source, target);
  3730             List<Type> fromList = from.toList();
  3731             List<Type> toList = to.toList();
  3732             while (!fromList.isEmpty()) {
  3733                 Type val = mapping.get(fromList.head.tsym);
  3734                 if (toList.head != val)
  3735                     toList.head = val;
  3736                 fromList = fromList.tail;
  3737                 toList = toList.tail;
  3741         @Override
  3742         public Void visitClassType(ClassType source, Type target) throws AdaptFailure {
  3743             if (target.tag == CLASS)
  3744                 adaptRecursive(source.allparams(), target.allparams());
  3745             return null;
  3748         @Override
  3749         public Void visitArrayType(ArrayType source, Type target) throws AdaptFailure {
  3750             if (target.tag == ARRAY)
  3751                 adaptRecursive(elemtype(source), elemtype(target));
  3752             return null;
  3755         @Override
  3756         public Void visitWildcardType(WildcardType source, Type target) throws AdaptFailure {
  3757             if (source.isExtendsBound())
  3758                 adaptRecursive(upperBound(source), upperBound(target));
  3759             else if (source.isSuperBound())
  3760                 adaptRecursive(lowerBound(source), lowerBound(target));
  3761             return null;
  3764         @Override
  3765         public Void visitTypeVar(TypeVar source, Type target) throws AdaptFailure {
  3766             // Check to see if there is
  3767             // already a mapping for $source$, in which case
  3768             // the old mapping will be merged with the new
  3769             Type val = mapping.get(source.tsym);
  3770             if (val != null) {
  3771                 if (val.isSuperBound() && target.isSuperBound()) {
  3772                     val = isSubtype(lowerBound(val), lowerBound(target))
  3773                         ? target : val;
  3774                 } else if (val.isExtendsBound() && target.isExtendsBound()) {
  3775                     val = isSubtype(upperBound(val), upperBound(target))
  3776                         ? val : target;
  3777                 } else if (!isSameType(val, target)) {
  3778                     throw new AdaptFailure();
  3780             } else {
  3781                 val = target;
  3782                 from.append(source);
  3783                 to.append(target);
  3785             mapping.put(source.tsym, val);
  3786             return null;
  3789         @Override
  3790         public Void visitType(Type source, Type target) {
  3791             return null;
  3794         private Set<TypePair> cache = new HashSet<TypePair>();
  3796         private void adaptRecursive(Type source, Type target) {
  3797             TypePair pair = new TypePair(source, target);
  3798             if (cache.add(pair)) {
  3799                 try {
  3800                     visit(source, target);
  3801                 } finally {
  3802                     cache.remove(pair);
  3807         private void adaptRecursive(List<Type> source, List<Type> target) {
  3808             if (source.length() == target.length()) {
  3809                 while (source.nonEmpty()) {
  3810                     adaptRecursive(source.head, target.head);
  3811                     source = source.tail;
  3812                     target = target.tail;
  3818     public static class AdaptFailure extends RuntimeException {
  3819         static final long serialVersionUID = -7490231548272701566L;
  3822     private void adaptSelf(Type t,
  3823                            ListBuffer<Type> from,
  3824                            ListBuffer<Type> to) {
  3825         try {
  3826             //if (t.tsym.type != t)
  3827                 adapt(t.tsym.type, t, from, to);
  3828         } catch (AdaptFailure ex) {
  3829             // Adapt should never fail calculating a mapping from
  3830             // t.tsym.type to t as there can be no merge problem.
  3831             throw new AssertionError(ex);
  3834     // </editor-fold>
  3836     /**
  3837      * Rewrite all type variables (universal quantifiers) in the given
  3838      * type to wildcards (existential quantifiers).  This is used to
  3839      * determine if a cast is allowed.  For example, if high is true
  3840      * and {@code T <: Number}, then {@code List<T>} is rewritten to
  3841      * {@code List<?  extends Number>}.  Since {@code List<Integer> <:
  3842      * List<? extends Number>} a {@code List<T>} can be cast to {@code
  3843      * List<Integer>} with a warning.
  3844      * @param t a type
  3845      * @param high if true return an upper bound; otherwise a lower
  3846      * bound
  3847      * @param rewriteTypeVars only rewrite captured wildcards if false;
  3848      * otherwise rewrite all type variables
  3849      * @return the type rewritten with wildcards (existential
  3850      * quantifiers) only
  3851      */
  3852     private Type rewriteQuantifiers(Type t, boolean high, boolean rewriteTypeVars) {
  3853         return new Rewriter(high, rewriteTypeVars).visit(t);
  3856     class Rewriter extends UnaryVisitor<Type> {
  3858         boolean high;
  3859         boolean rewriteTypeVars;
  3861         Rewriter(boolean high, boolean rewriteTypeVars) {
  3862             this.high = high;
  3863             this.rewriteTypeVars = rewriteTypeVars;
  3866         @Override
  3867         public Type visitClassType(ClassType t, Void s) {
  3868             ListBuffer<Type> rewritten = new ListBuffer<Type>();
  3869             boolean changed = false;
  3870             for (Type arg : t.allparams()) {
  3871                 Type bound = visit(arg);
  3872                 if (arg != bound) {
  3873                     changed = true;
  3875                 rewritten.append(bound);
  3877             if (changed)
  3878                 return subst(t.tsym.type,
  3879                         t.tsym.type.allparams(),
  3880                         rewritten.toList());
  3881             else
  3882                 return t;
  3885         public Type visitType(Type t, Void s) {
  3886             return high ? upperBound(t) : lowerBound(t);
  3889         @Override
  3890         public Type visitCapturedType(CapturedType t, Void s) {
  3891             Type w_bound = t.wildcard.type;
  3892             Type bound = w_bound.contains(t) ?
  3893                         erasure(w_bound) :
  3894                         visit(w_bound);
  3895             return rewriteAsWildcardType(visit(bound), t.wildcard.bound, t.wildcard.kind);
  3898         @Override
  3899         public Type visitTypeVar(TypeVar t, Void s) {
  3900             if (rewriteTypeVars) {
  3901                 Type bound = t.bound.contains(t) ?
  3902                         erasure(t.bound) :
  3903                         visit(t.bound);
  3904                 return rewriteAsWildcardType(bound, t, EXTENDS);
  3905             } else {
  3906                 return t;
  3910         @Override
  3911         public Type visitWildcardType(WildcardType t, Void s) {
  3912             Type bound2 = visit(t.type);
  3913             return t.type == bound2 ? t : rewriteAsWildcardType(bound2, t.bound, t.kind);
  3916         private Type rewriteAsWildcardType(Type bound, TypeVar formal, BoundKind bk) {
  3917             switch (bk) {
  3918                case EXTENDS: return high ?
  3919                        makeExtendsWildcard(B(bound), formal) :
  3920                        makeExtendsWildcard(syms.objectType, formal);
  3921                case SUPER: return high ?
  3922                        makeSuperWildcard(syms.botType, formal) :
  3923                        makeSuperWildcard(B(bound), formal);
  3924                case UNBOUND: return makeExtendsWildcard(syms.objectType, formal);
  3925                default:
  3926                    Assert.error("Invalid bound kind " + bk);
  3927                    return null;
  3931         Type B(Type t) {
  3932             while (t.tag == WILDCARD) {
  3933                 WildcardType w = (WildcardType)t;
  3934                 t = high ?
  3935                     w.getExtendsBound() :
  3936                     w.getSuperBound();
  3937                 if (t == null) {
  3938                     t = high ? syms.objectType : syms.botType;
  3941             return t;
  3946     /**
  3947      * Create a wildcard with the given upper (extends) bound; create
  3948      * an unbounded wildcard if bound is Object.
  3950      * @param bound the upper bound
  3951      * @param formal the formal type parameter that will be
  3952      * substituted by the wildcard
  3953      */
  3954     private WildcardType makeExtendsWildcard(Type bound, TypeVar formal) {
  3955         if (bound == syms.objectType) {
  3956             return new WildcardType(syms.objectType,
  3957                                     BoundKind.UNBOUND,
  3958                                     syms.boundClass,
  3959                                     formal);
  3960         } else {
  3961             return new WildcardType(bound,
  3962                                     BoundKind.EXTENDS,
  3963                                     syms.boundClass,
  3964                                     formal);
  3968     /**
  3969      * Create a wildcard with the given lower (super) bound; create an
  3970      * unbounded wildcard if bound is bottom (type of {@code null}).
  3972      * @param bound the lower bound
  3973      * @param formal the formal type parameter that will be
  3974      * substituted by the wildcard
  3975      */
  3976     private WildcardType makeSuperWildcard(Type bound, TypeVar formal) {
  3977         if (bound.tag == BOT) {
  3978             return new WildcardType(syms.objectType,
  3979                                     BoundKind.UNBOUND,
  3980                                     syms.boundClass,
  3981                                     formal);
  3982         } else {
  3983             return new WildcardType(bound,
  3984                                     BoundKind.SUPER,
  3985                                     syms.boundClass,
  3986                                     formal);
  3990     /**
  3991      * A wrapper for a type that allows use in sets.
  3992      */
  3993     class SingletonType {
  3994         final Type t;
  3995         SingletonType(Type t) {
  3996             this.t = t;
  3998         public int hashCode() {
  3999             return Types.hashCode(t);
  4001         public boolean equals(Object obj) {
  4002             return (obj instanceof SingletonType) &&
  4003                 isSameType(t, ((SingletonType)obj).t);
  4005         public String toString() {
  4006             return t.toString();
  4009     // </editor-fold>
  4011     // <editor-fold defaultstate="collapsed" desc="Visitors">
  4012     /**
  4013      * A default visitor for types.  All visitor methods except
  4014      * visitType are implemented by delegating to visitType.  Concrete
  4015      * subclasses must provide an implementation of visitType and can
  4016      * override other methods as needed.
  4018      * @param <R> the return type of the operation implemented by this
  4019      * visitor; use Void if no return type is needed.
  4020      * @param <S> the type of the second argument (the first being the
  4021      * type itself) of the operation implemented by this visitor; use
  4022      * Void if a second argument is not needed.
  4023      */
  4024     public static abstract class DefaultTypeVisitor<R,S> implements Type.Visitor<R,S> {
  4025         final public R visit(Type t, S s)               { return t.accept(this, s); }
  4026         public R visitClassType(ClassType t, S s)       { return visitType(t, s); }
  4027         public R visitWildcardType(WildcardType t, S s) { return visitType(t, s); }
  4028         public R visitArrayType(ArrayType t, S s)       { return visitType(t, s); }
  4029         public R visitMethodType(MethodType t, S s)     { return visitType(t, s); }
  4030         public R visitPackageType(PackageType t, S s)   { return visitType(t, s); }
  4031         public R visitTypeVar(TypeVar t, S s)           { return visitType(t, s); }
  4032         public R visitCapturedType(CapturedType t, S s) { return visitType(t, s); }
  4033         public R visitForAll(ForAll t, S s)             { return visitType(t, s); }
  4034         public R visitUndetVar(UndetVar t, S s)         { return visitType(t, s); }
  4035         public R visitErrorType(ErrorType t, S s)       { return visitType(t, s); }
  4038     /**
  4039      * A default visitor for symbols.  All visitor methods except
  4040      * visitSymbol are implemented by delegating to visitSymbol.  Concrete
  4041      * subclasses must provide an implementation of visitSymbol and can
  4042      * override other methods as needed.
  4044      * @param <R> the return type of the operation implemented by this
  4045      * visitor; use Void if no return type is needed.
  4046      * @param <S> the type of the second argument (the first being the
  4047      * symbol itself) of the operation implemented by this visitor; use
  4048      * Void if a second argument is not needed.
  4049      */
  4050     public static abstract class DefaultSymbolVisitor<R,S> implements Symbol.Visitor<R,S> {
  4051         final public R visit(Symbol s, S arg)                   { return s.accept(this, arg); }
  4052         public R visitClassSymbol(ClassSymbol s, S arg)         { return visitSymbol(s, arg); }
  4053         public R visitMethodSymbol(MethodSymbol s, S arg)       { return visitSymbol(s, arg); }
  4054         public R visitOperatorSymbol(OperatorSymbol s, S arg)   { return visitSymbol(s, arg); }
  4055         public R visitPackageSymbol(PackageSymbol s, S arg)     { return visitSymbol(s, arg); }
  4056         public R visitTypeSymbol(TypeSymbol s, S arg)           { return visitSymbol(s, arg); }
  4057         public R visitVarSymbol(VarSymbol s, S arg)             { return visitSymbol(s, arg); }
  4060     /**
  4061      * A <em>simple</em> visitor for types.  This visitor is simple as
  4062      * captured wildcards, for-all types (generic methods), and
  4063      * undetermined type variables (part of inference) are hidden.
  4064      * Captured wildcards are hidden by treating them as type
  4065      * variables and the rest are hidden by visiting their qtypes.
  4067      * @param <R> the return type of the operation implemented by this
  4068      * visitor; use Void if no return type is needed.
  4069      * @param <S> the type of the second argument (the first being the
  4070      * type itself) of the operation implemented by this visitor; use
  4071      * Void if a second argument is not needed.
  4072      */
  4073     public static abstract class SimpleVisitor<R,S> extends DefaultTypeVisitor<R,S> {
  4074         @Override
  4075         public R visitCapturedType(CapturedType t, S s) {
  4076             return visitTypeVar(t, s);
  4078         @Override
  4079         public R visitForAll(ForAll t, S s) {
  4080             return visit(t.qtype, s);
  4082         @Override
  4083         public R visitUndetVar(UndetVar t, S s) {
  4084             return visit(t.qtype, s);
  4088     /**
  4089      * A plain relation on types.  That is a 2-ary function on the
  4090      * form Type&nbsp;&times;&nbsp;Type&nbsp;&rarr;&nbsp;Boolean.
  4091      * <!-- In plain text: Type x Type -> Boolean -->
  4092      */
  4093     public static abstract class TypeRelation extends SimpleVisitor<Boolean,Type> {}
  4095     /**
  4096      * A convenience visitor for implementing operations that only
  4097      * require one argument (the type itself), that is, unary
  4098      * operations.
  4100      * @param <R> the return type of the operation implemented by this
  4101      * visitor; use Void if no return type is needed.
  4102      */
  4103     public static abstract class UnaryVisitor<R> extends SimpleVisitor<R,Void> {
  4104         final public R visit(Type t) { return t.accept(this, null); }
  4107     /**
  4108      * A visitor for implementing a mapping from types to types.  The
  4109      * default behavior of this class is to implement the identity
  4110      * mapping (mapping a type to itself).  This can be overridden in
  4111      * subclasses.
  4113      * @param <S> the type of the second argument (the first being the
  4114      * type itself) of this mapping; use Void if a second argument is
  4115      * not needed.
  4116      */
  4117     public static class MapVisitor<S> extends DefaultTypeVisitor<Type,S> {
  4118         final public Type visit(Type t) { return t.accept(this, null); }
  4119         public Type visitType(Type t, S s) { return t; }
  4121     // </editor-fold>
  4124     // <editor-fold defaultstate="collapsed" desc="Annotation support">
  4126     public RetentionPolicy getRetention(Attribute.Compound a) {
  4127         return getRetention(a.type.tsym);
  4130     public RetentionPolicy getRetention(Symbol sym) {
  4131         RetentionPolicy vis = RetentionPolicy.CLASS; // the default
  4132         Attribute.Compound c = sym.attribute(syms.retentionType.tsym);
  4133         if (c != null) {
  4134             Attribute value = c.member(names.value);
  4135             if (value != null && value instanceof Attribute.Enum) {
  4136                 Name levelName = ((Attribute.Enum)value).value.name;
  4137                 if (levelName == names.SOURCE) vis = RetentionPolicy.SOURCE;
  4138                 else if (levelName == names.CLASS) vis = RetentionPolicy.CLASS;
  4139                 else if (levelName == names.RUNTIME) vis = RetentionPolicy.RUNTIME;
  4140                 else ;// /* fail soft */ throw new AssertionError(levelName);
  4143         return vis;
  4145     // </editor-fold>

mercurial