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

Tue, 27 Nov 2012 13:55:10 -0800

author
jjg
date
Tue, 27 Nov 2012 13:55:10 -0800
changeset 1430
4d68e2a05b50
parent 1415
01c9d4161882
child 1434
34d1ebaf4645
permissions
-rw-r--r--

8004068: Fix build problems caused by on-demand imports
Reviewed-by: jjg
Contributed-by: eric.caspole@amd.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.Comparator;
    30 import java.util.HashSet;
    31 import java.util.HashMap;
    32 import java.util.Locale;
    33 import java.util.Map;
    34 import java.util.Set;
    35 import java.util.WeakHashMap;
    37 import com.sun.tools.javac.code.Attribute.RetentionPolicy;
    38 import com.sun.tools.javac.code.Lint.LintCategory;
    39 import com.sun.tools.javac.code.Type.UndetVar.InferenceBound;
    40 import com.sun.tools.javac.comp.Check;
    41 import com.sun.tools.javac.jvm.ClassReader;
    42 import com.sun.tools.javac.util.*;
    43 import com.sun.tools.javac.util.List;
    44 import static com.sun.tools.javac.code.BoundKind.*;
    45 import static com.sun.tools.javac.code.Flags.*;
    46 import static com.sun.tools.javac.code.Scope.*;
    47 import static com.sun.tools.javac.code.Symbol.*;
    48 import static com.sun.tools.javac.code.Type.*;
    49 import static com.sun.tools.javac.code.TypeTag.*;
    50 import static com.sun.tools.javac.util.ListBuffer.lb;
    52 /**
    53  * Utility class containing various operations on types.
    54  *
    55  * <p>Unless other names are more illustrative, the following naming
    56  * conventions should be observed in this file:
    57  *
    58  * <dl>
    59  * <dt>t</dt>
    60  * <dd>If the first argument to an operation is a type, it should be named t.</dd>
    61  * <dt>s</dt>
    62  * <dd>Similarly, if the second argument to an operation is a type, it should be named s.</dd>
    63  * <dt>ts</dt>
    64  * <dd>If an operations takes a list of types, the first should be named ts.</dd>
    65  * <dt>ss</dt>
    66  * <dd>A second list of types should be named ss.</dd>
    67  * </dl>
    68  *
    69  * <p><b>This is NOT part of any supported API.
    70  * If you write code that depends on this, you do so at your own risk.
    71  * This code and its internal interfaces are subject to change or
    72  * deletion without notice.</b>
    73  */
    74 public class Types {
    75     protected static final Context.Key<Types> typesKey =
    76         new Context.Key<Types>();
    78     final Symtab syms;
    79     final JavacMessages messages;
    80     final Names names;
    81     final boolean allowBoxing;
    82     final boolean allowCovariantReturns;
    83     final boolean allowObjectToPrimitiveCast;
    84     final boolean allowDefaultMethods;
    85     final ClassReader reader;
    86     final Check chk;
    87     JCDiagnostic.Factory diags;
    88     List<Warner> warnStack = List.nil();
    89     final Name capturedName;
    90     private final FunctionDescriptorLookupError functionDescriptorLookupError;
    92     public final Warner noWarnings;
    94     // <editor-fold defaultstate="collapsed" desc="Instantiating">
    95     public static Types instance(Context context) {
    96         Types instance = context.get(typesKey);
    97         if (instance == null)
    98             instance = new Types(context);
    99         return instance;
   100     }
   102     protected Types(Context context) {
   103         context.put(typesKey, this);
   104         syms = Symtab.instance(context);
   105         names = Names.instance(context);
   106         Source source = Source.instance(context);
   107         allowBoxing = source.allowBoxing();
   108         allowCovariantReturns = source.allowCovariantReturns();
   109         allowObjectToPrimitiveCast = source.allowObjectToPrimitiveCast();
   110         allowDefaultMethods = source.allowDefaultMethods();
   111         reader = ClassReader.instance(context);
   112         chk = Check.instance(context);
   113         capturedName = names.fromString("<captured wildcard>");
   114         messages = JavacMessages.instance(context);
   115         diags = JCDiagnostic.Factory.instance(context);
   116         functionDescriptorLookupError = new FunctionDescriptorLookupError();
   117         noWarnings = new Warner(null);
   118     }
   119     // </editor-fold>
   121     // <editor-fold defaultstate="collapsed" desc="upperBound">
   122     /**
   123      * The "rvalue conversion".<br>
   124      * The upper bound of most types is the type
   125      * itself.  Wildcards, on the other hand have upper
   126      * and lower bounds.
   127      * @param t a type
   128      * @return the upper bound of the given type
   129      */
   130     public Type upperBound(Type t) {
   131         return upperBound.visit(t);
   132     }
   133     // where
   134         private final MapVisitor<Void> upperBound = new MapVisitor<Void>() {
   136             @Override
   137             public Type visitWildcardType(WildcardType t, Void ignored) {
   138                 if (t.isSuperBound())
   139                     return t.bound == null ? syms.objectType : t.bound.bound;
   140                 else
   141                     return visit(t.type);
   142             }
   144             @Override
   145             public Type visitCapturedType(CapturedType t, Void ignored) {
   146                 return visit(t.bound);
   147             }
   148         };
   149     // </editor-fold>
   151     // <editor-fold defaultstate="collapsed" desc="lowerBound">
   152     /**
   153      * The "lvalue conversion".<br>
   154      * The lower bound of most types is the type
   155      * itself.  Wildcards, on the other hand have upper
   156      * and lower bounds.
   157      * @param t a type
   158      * @return the lower bound of the given type
   159      */
   160     public Type lowerBound(Type t) {
   161         return lowerBound.visit(t);
   162     }
   163     // where
   164         private final MapVisitor<Void> lowerBound = new MapVisitor<Void>() {
   166             @Override
   167             public Type visitWildcardType(WildcardType t, Void ignored) {
   168                 return t.isExtendsBound() ? syms.botType : visit(t.type);
   169             }
   171             @Override
   172             public Type visitCapturedType(CapturedType t, Void ignored) {
   173                 return visit(t.getLowerBound());
   174             }
   175         };
   176     // </editor-fold>
   178     // <editor-fold defaultstate="collapsed" desc="isUnbounded">
   179     /**
   180      * Checks that all the arguments to a class are unbounded
   181      * wildcards or something else that doesn't make any restrictions
   182      * on the arguments. If a class isUnbounded, a raw super- or
   183      * subclass can be cast to it without a warning.
   184      * @param t a type
   185      * @return true iff the given type is unbounded or raw
   186      */
   187     public boolean isUnbounded(Type t) {
   188         return isUnbounded.visit(t);
   189     }
   190     // where
   191         private final UnaryVisitor<Boolean> isUnbounded = new UnaryVisitor<Boolean>() {
   193             public Boolean visitType(Type t, Void ignored) {
   194                 return true;
   195             }
   197             @Override
   198             public Boolean visitClassType(ClassType t, Void ignored) {
   199                 List<Type> parms = t.tsym.type.allparams();
   200                 List<Type> args = t.allparams();
   201                 while (parms.nonEmpty()) {
   202                     WildcardType unb = new WildcardType(syms.objectType,
   203                                                         BoundKind.UNBOUND,
   204                                                         syms.boundClass,
   205                                                         (TypeVar)parms.head);
   206                     if (!containsType(args.head, unb))
   207                         return false;
   208                     parms = parms.tail;
   209                     args = args.tail;
   210                 }
   211                 return true;
   212             }
   213         };
   214     // </editor-fold>
   216     // <editor-fold defaultstate="collapsed" desc="asSub">
   217     /**
   218      * Return the least specific subtype of t that starts with symbol
   219      * sym.  If none exists, return null.  The least specific subtype
   220      * is determined as follows:
   221      *
   222      * <p>If there is exactly one parameterized instance of sym that is a
   223      * subtype of t, that parameterized instance is returned.<br>
   224      * Otherwise, if the plain type or raw type `sym' is a subtype of
   225      * type t, the type `sym' itself is returned.  Otherwise, null is
   226      * returned.
   227      */
   228     public Type asSub(Type t, Symbol sym) {
   229         return asSub.visit(t, sym);
   230     }
   231     // where
   232         private final SimpleVisitor<Type,Symbol> asSub = new SimpleVisitor<Type,Symbol>() {
   234             public Type visitType(Type t, Symbol sym) {
   235                 return null;
   236             }
   238             @Override
   239             public Type visitClassType(ClassType t, Symbol sym) {
   240                 if (t.tsym == sym)
   241                     return t;
   242                 Type base = asSuper(sym.type, t.tsym);
   243                 if (base == null)
   244                     return null;
   245                 ListBuffer<Type> from = new ListBuffer<Type>();
   246                 ListBuffer<Type> to = new ListBuffer<Type>();
   247                 try {
   248                     adapt(base, t, from, to);
   249                 } catch (AdaptFailure ex) {
   250                     return null;
   251                 }
   252                 Type res = subst(sym.type, from.toList(), to.toList());
   253                 if (!isSubtype(res, t))
   254                     return null;
   255                 ListBuffer<Type> openVars = new ListBuffer<Type>();
   256                 for (List<Type> l = sym.type.allparams();
   257                      l.nonEmpty(); l = l.tail)
   258                     if (res.contains(l.head) && !t.contains(l.head))
   259                         openVars.append(l.head);
   260                 if (openVars.nonEmpty()) {
   261                     if (t.isRaw()) {
   262                         // The subtype of a raw type is raw
   263                         res = erasure(res);
   264                     } else {
   265                         // Unbound type arguments default to ?
   266                         List<Type> opens = openVars.toList();
   267                         ListBuffer<Type> qs = new ListBuffer<Type>();
   268                         for (List<Type> iter = opens; iter.nonEmpty(); iter = iter.tail) {
   269                             qs.append(new WildcardType(syms.objectType, BoundKind.UNBOUND, syms.boundClass, (TypeVar) iter.head));
   270                         }
   271                         res = subst(res, opens, qs.toList());
   272                     }
   273                 }
   274                 return res;
   275             }
   277             @Override
   278             public Type visitErrorType(ErrorType t, Symbol sym) {
   279                 return t;
   280             }
   281         };
   282     // </editor-fold>
   284     // <editor-fold defaultstate="collapsed" desc="isConvertible">
   285     /**
   286      * Is t a subtype of or convertible via boxing/unboxing
   287      * conversion to s?
   288      */
   289     public boolean isConvertible(Type t, Type s, Warner warn) {
   290         if (t.tag == ERROR)
   291             return true;
   292         boolean tPrimitive = t.isPrimitive();
   293         boolean sPrimitive = s.isPrimitive();
   294         if (tPrimitive == sPrimitive) {
   295             return isSubtypeUnchecked(t, s, warn);
   296         }
   297         if (!allowBoxing) return false;
   298         return tPrimitive
   299             ? isSubtype(boxedClass(t).type, s)
   300             : isSubtype(unboxedType(t), s);
   301     }
   303     /**
   304      * Is t a subtype of or convertiable via boxing/unboxing
   305      * convertions to s?
   306      */
   307     public boolean isConvertible(Type t, Type s) {
   308         return isConvertible(t, s, noWarnings);
   309     }
   310     // </editor-fold>
   312     // <editor-fold defaultstate="collapsed" desc="findSam">
   314     /**
   315      * Exception used to report a function descriptor lookup failure. The exception
   316      * wraps a diagnostic that can be used to generate more details error
   317      * messages.
   318      */
   319     public static class FunctionDescriptorLookupError extends RuntimeException {
   320         private static final long serialVersionUID = 0;
   322         JCDiagnostic diagnostic;
   324         FunctionDescriptorLookupError() {
   325             this.diagnostic = null;
   326         }
   328         FunctionDescriptorLookupError setMessage(JCDiagnostic diag) {
   329             this.diagnostic = diag;
   330             return this;
   331         }
   333         public JCDiagnostic getDiagnostic() {
   334             return diagnostic;
   335         }
   336     }
   338     /**
   339      * A cache that keeps track of function descriptors associated with given
   340      * functional interfaces.
   341      */
   342     class DescriptorCache {
   344         private WeakHashMap<TypeSymbol, Entry> _map = new WeakHashMap<TypeSymbol, Entry>();
   346         class FunctionDescriptor {
   347             Symbol descSym;
   349             FunctionDescriptor(Symbol descSym) {
   350                 this.descSym = descSym;
   351             }
   353             public Symbol getSymbol() {
   354                 return descSym;
   355             }
   357             public Type getType(Type origin) {
   358                 return memberType(origin, descSym);
   359             }
   360         }
   362         class Entry {
   363             final FunctionDescriptor cachedDescRes;
   364             final int prevMark;
   366             public Entry(FunctionDescriptor cachedDescRes,
   367                     int prevMark) {
   368                 this.cachedDescRes = cachedDescRes;
   369                 this.prevMark = prevMark;
   370             }
   372             boolean matches(int mark) {
   373                 return  this.prevMark == mark;
   374             }
   375         }
   377         FunctionDescriptor get(TypeSymbol origin) throws FunctionDescriptorLookupError {
   378             Entry e = _map.get(origin);
   379             CompoundScope members = membersClosure(origin.type, false);
   380             if (e == null ||
   381                     !e.matches(members.getMark())) {
   382                 FunctionDescriptor descRes = findDescriptorInternal(origin, members);
   383                 _map.put(origin, new Entry(descRes, members.getMark()));
   384                 return descRes;
   385             }
   386             else {
   387                 return e.cachedDescRes;
   388             }
   389         }
   391         /**
   392          * Scope filter used to skip methods that should be ignored during
   393          * function interface conversion (such as methods overridden by
   394          * j.l.Object)
   395          */
   396         class DescriptorFilter implements Filter<Symbol> {
   398             TypeSymbol origin;
   400             DescriptorFilter(TypeSymbol origin) {
   401                 this.origin = origin;
   402             }
   404             @Override
   405             public boolean accepts(Symbol sym) {
   406                 return sym.kind == Kinds.MTH &&
   407                         (sym.flags() & (ABSTRACT | DEFAULT)) == ABSTRACT &&
   408                         !overridesObjectMethod(origin, sym) &&
   409                         (interfaceCandidates(origin.type, (MethodSymbol)sym).head.flags() & DEFAULT) == 0;
   410             }
   411         };
   413         /**
   414          * Compute the function descriptor associated with a given functional interface
   415          */
   416         public FunctionDescriptor findDescriptorInternal(TypeSymbol origin, CompoundScope membersCache) throws FunctionDescriptorLookupError {
   417             if (!origin.isInterface()) {
   418                 //t must be an interface
   419                 throw failure("not.a.functional.intf");
   420             }
   422             final ListBuffer<Symbol> abstracts = ListBuffer.lb();
   423             for (Symbol sym : membersCache.getElements(new DescriptorFilter(origin))) {
   424                 Type mtype = memberType(origin.type, sym);
   425                 if (abstracts.isEmpty() ||
   426                         (sym.name == abstracts.first().name &&
   427                         overrideEquivalent(mtype, memberType(origin.type, abstracts.first())))) {
   428                     abstracts.append(sym);
   429                 } else {
   430                     //the target method(s) should be the only abstract members of t
   431                     throw failure("not.a.functional.intf.1",
   432                             diags.fragment("incompatible.abstracts", Kinds.kindName(origin), origin));
   433                 }
   434             }
   435             if (abstracts.isEmpty()) {
   436                 //t must define a suitable non-generic method
   437                 throw failure("not.a.functional.intf.1",
   438                             diags.fragment("no.abstracts", Kinds.kindName(origin), origin));
   439             } else if (abstracts.size() == 1) {
   440                 if (abstracts.first().type.tag == FORALL) {
   441                     throw failure("invalid.generic.desc.in.functional.intf",
   442                             abstracts.first(),
   443                             Kinds.kindName(origin),
   444                             origin);
   445                 } else {
   446                     return new FunctionDescriptor(abstracts.first());
   447                 }
   448             } else { // size > 1
   449                 for (Symbol msym : abstracts) {
   450                     if (msym.type.tag == FORALL) {
   451                         throw failure("invalid.generic.desc.in.functional.intf",
   452                                 abstracts.first(),
   453                                 Kinds.kindName(origin),
   454                                 origin);
   455                     }
   456                 }
   457                 FunctionDescriptor descRes = mergeDescriptors(origin, abstracts.toList());
   458                 if (descRes == null) {
   459                     //we can get here if the functional interface is ill-formed
   460                     ListBuffer<JCDiagnostic> descriptors = ListBuffer.lb();
   461                     for (Symbol desc : abstracts) {
   462                         String key = desc.type.getThrownTypes().nonEmpty() ?
   463                                 "descriptor.throws" : "descriptor";
   464                         descriptors.append(diags.fragment(key, desc.name,
   465                                 desc.type.getParameterTypes(),
   466                                 desc.type.getReturnType(),
   467                                 desc.type.getThrownTypes()));
   468                     }
   469                     JCDiagnostic.MultilineDiagnostic incompatibleDescriptors =
   470                             new JCDiagnostic.MultilineDiagnostic(diags.fragment("incompatible.descs.in.functional.intf",
   471                             Kinds.kindName(origin), origin), descriptors.toList());
   472                     throw failure(incompatibleDescriptors);
   473                 }
   474                 return descRes;
   475             }
   476         }
   478         /**
   479          * Compute a synthetic type for the target descriptor given a list
   480          * of override-equivalent methods in the functional interface type.
   481          * The resulting method type is a method type that is override-equivalent
   482          * and return-type substitutable with each method in the original list.
   483          */
   484         private FunctionDescriptor mergeDescriptors(TypeSymbol origin, List<Symbol> methodSyms) {
   485             //pick argument types - simply take the signature that is a
   486             //subsignature of all other signatures in the list (as per JLS 8.4.2)
   487             List<Symbol> mostSpecific = List.nil();
   488             outer: for (Symbol msym1 : methodSyms) {
   489                 Type mt1 = memberType(origin.type, msym1);
   490                 for (Symbol msym2 : methodSyms) {
   491                     Type mt2 = memberType(origin.type, msym2);
   492                     if (!isSubSignature(mt1, mt2)) {
   493                         continue outer;
   494                     }
   495                 }
   496                 mostSpecific = mostSpecific.prepend(msym1);
   497             }
   498             if (mostSpecific.isEmpty()) {
   499                 return null;
   500             }
   503             //pick return types - this is done in two phases: (i) first, the most
   504             //specific return type is chosen using strict subtyping; if this fails,
   505             //a second attempt is made using return type substitutability (see JLS 8.4.5)
   506             boolean phase2 = false;
   507             Symbol bestSoFar = null;
   508             while (bestSoFar == null) {
   509                 outer: for (Symbol msym1 : mostSpecific) {
   510                     Type mt1 = memberType(origin.type, msym1);
   511                     for (Symbol msym2 : methodSyms) {
   512                         Type mt2 = memberType(origin.type, msym2);
   513                         if (phase2 ?
   514                                 !returnTypeSubstitutable(mt1, mt2) :
   515                                 !isSubtypeInternal(mt1.getReturnType(), mt2.getReturnType())) {
   516                             continue outer;
   517                         }
   518                     }
   519                     bestSoFar = msym1;
   520                 }
   521                 if (phase2) {
   522                     break;
   523                 } else {
   524                     phase2 = true;
   525                 }
   526             }
   527             if (bestSoFar == null) return null;
   529             //merge thrown types - form the intersection of all the thrown types in
   530             //all the signatures in the list
   531             List<Type> thrown = null;
   532             for (Symbol msym1 : methodSyms) {
   533                 Type mt1 = memberType(origin.type, msym1);
   534                 thrown = (thrown == null) ?
   535                     mt1.getThrownTypes() :
   536                     chk.intersect(mt1.getThrownTypes(), thrown);
   537             }
   539             final List<Type> thrown1 = thrown;
   540             return new FunctionDescriptor(bestSoFar) {
   541                 @Override
   542                 public Type getType(Type origin) {
   543                     Type mt = memberType(origin, getSymbol());
   544                     return new MethodType(mt.getParameterTypes(), mt.getReturnType(), thrown1, syms.methodClass);
   545                 }
   546             };
   547         }
   549         boolean isSubtypeInternal(Type s, Type t) {
   550             return (s.isPrimitive() && t.isPrimitive()) ?
   551                     isSameType(t, s) :
   552                     isSubtype(s, t);
   553         }
   555         FunctionDescriptorLookupError failure(String msg, Object... args) {
   556             return failure(diags.fragment(msg, args));
   557         }
   559         FunctionDescriptorLookupError failure(JCDiagnostic diag) {
   560             return functionDescriptorLookupError.setMessage(diag);
   561         }
   562     }
   564     private DescriptorCache descCache = new DescriptorCache();
   566     /**
   567      * Find the method descriptor associated to this class symbol - if the
   568      * symbol 'origin' is not a functional interface, an exception is thrown.
   569      */
   570     public Symbol findDescriptorSymbol(TypeSymbol origin) throws FunctionDescriptorLookupError {
   571         return descCache.get(origin).getSymbol();
   572     }
   574     /**
   575      * Find the type of the method descriptor associated to this class symbol -
   576      * if the symbol 'origin' is not a functional interface, an exception is thrown.
   577      */
   578     public Type findDescriptorType(Type origin) throws FunctionDescriptorLookupError {
   579         return descCache.get(origin.tsym).getType(origin);
   580     }
   582     /**
   583      * Is given type a functional interface?
   584      */
   585     public boolean isFunctionalInterface(TypeSymbol tsym) {
   586         try {
   587             findDescriptorSymbol(tsym);
   588             return true;
   589         } catch (FunctionDescriptorLookupError ex) {
   590             return false;
   591         }
   592     }
   593     // </editor-fold>
   595     // <editor-fold defaultstate="collapsed" desc="isSubtype">
   596     /**
   597      * Is t an unchecked subtype of s?
   598      */
   599     public boolean isSubtypeUnchecked(Type t, Type s) {
   600         return isSubtypeUnchecked(t, s, noWarnings);
   601     }
   602     /**
   603      * Is t an unchecked subtype of s?
   604      */
   605     public boolean isSubtypeUnchecked(Type t, Type s, Warner warn) {
   606         boolean result = isSubtypeUncheckedInternal(t, s, warn);
   607         if (result) {
   608             checkUnsafeVarargsConversion(t, s, warn);
   609         }
   610         return result;
   611     }
   612     //where
   613         private boolean isSubtypeUncheckedInternal(Type t, Type s, Warner warn) {
   614             if (t.hasTag(ARRAY) && s.hasTag(ARRAY)) {
   615                 if (((ArrayType)t).elemtype.isPrimitive()) {
   616                     return isSameType(elemtype(t), elemtype(s));
   617                 } else {
   618                     return isSubtypeUnchecked(elemtype(t), elemtype(s), warn);
   619                 }
   620             } else if (isSubtype(t, s)) {
   621                 return true;
   622             }
   623             else if (t.tag == TYPEVAR) {
   624                 return isSubtypeUnchecked(t.getUpperBound(), s, warn);
   625             }
   626             else if (!s.isRaw()) {
   627                 Type t2 = asSuper(t, s.tsym);
   628                 if (t2 != null && t2.isRaw()) {
   629                     if (isReifiable(s))
   630                         warn.silentWarn(LintCategory.UNCHECKED);
   631                     else
   632                         warn.warn(LintCategory.UNCHECKED);
   633                     return true;
   634                 }
   635             }
   636             return false;
   637         }
   639         private void checkUnsafeVarargsConversion(Type t, Type s, Warner warn) {
   640             if (t.tag != ARRAY || isReifiable(t)) return;
   641             ArrayType from = (ArrayType)t;
   642             boolean shouldWarn = false;
   643             switch (s.tag) {
   644                 case ARRAY:
   645                     ArrayType to = (ArrayType)s;
   646                     shouldWarn = from.isVarargs() &&
   647                             !to.isVarargs() &&
   648                             !isReifiable(from);
   649                     break;
   650                 case CLASS:
   651                     shouldWarn = from.isVarargs();
   652                     break;
   653             }
   654             if (shouldWarn) {
   655                 warn.warn(LintCategory.VARARGS);
   656             }
   657         }
   659     /**
   660      * Is t a subtype of s?<br>
   661      * (not defined for Method and ForAll types)
   662      */
   663     final public boolean isSubtype(Type t, Type s) {
   664         return isSubtype(t, s, true);
   665     }
   666     final public boolean isSubtypeNoCapture(Type t, Type s) {
   667         return isSubtype(t, s, false);
   668     }
   669     public boolean isSubtype(Type t, Type s, boolean capture) {
   670         if (t == s)
   671             return true;
   673         if (s.isPartial())
   674             return isSuperType(s, t);
   676         if (s.isCompound()) {
   677             for (Type s2 : interfaces(s).prepend(supertype(s))) {
   678                 if (!isSubtype(t, s2, capture))
   679                     return false;
   680             }
   681             return true;
   682         }
   684         Type lower = lowerBound(s);
   685         if (s != lower)
   686             return isSubtype(capture ? capture(t) : t, lower, false);
   688         return isSubtype.visit(capture ? capture(t) : t, s);
   689     }
   690     // where
   691         private TypeRelation isSubtype = new TypeRelation()
   692         {
   693             public Boolean visitType(Type t, Type s) {
   694                 switch (t.tag) {
   695                  case BYTE:
   696                      return (!s.hasTag(CHAR) && t.getTag().isSubRangeOf(s.getTag()));
   697                  case CHAR:
   698                      return (!s.hasTag(SHORT) && t.getTag().isSubRangeOf(s.getTag()));
   699                  case SHORT: case INT: case LONG:
   700                  case FLOAT: case DOUBLE:
   701                      return t.getTag().isSubRangeOf(s.getTag());
   702                  case BOOLEAN: case VOID:
   703                      return t.hasTag(s.getTag());
   704                  case TYPEVAR:
   705                      return isSubtypeNoCapture(t.getUpperBound(), s);
   706                  case BOT:
   707                      return
   708                          s.hasTag(BOT) || s.hasTag(CLASS) ||
   709                          s.hasTag(ARRAY) || s.hasTag(TYPEVAR);
   710                  case WILDCARD: //we shouldn't be here - avoids crash (see 7034495)
   711                  case NONE:
   712                      return false;
   713                  default:
   714                      throw new AssertionError("isSubtype " + t.tag);
   715                  }
   716             }
   718             private Set<TypePair> cache = new HashSet<TypePair>();
   720             private boolean containsTypeRecursive(Type t, Type s) {
   721                 TypePair pair = new TypePair(t, s);
   722                 if (cache.add(pair)) {
   723                     try {
   724                         return containsType(t.getTypeArguments(),
   725                                             s.getTypeArguments());
   726                     } finally {
   727                         cache.remove(pair);
   728                     }
   729                 } else {
   730                     return containsType(t.getTypeArguments(),
   731                                         rewriteSupers(s).getTypeArguments());
   732                 }
   733             }
   735             private Type rewriteSupers(Type t) {
   736                 if (!t.isParameterized())
   737                     return t;
   738                 ListBuffer<Type> from = lb();
   739                 ListBuffer<Type> to = lb();
   740                 adaptSelf(t, from, to);
   741                 if (from.isEmpty())
   742                     return t;
   743                 ListBuffer<Type> rewrite = lb();
   744                 boolean changed = false;
   745                 for (Type orig : to.toList()) {
   746                     Type s = rewriteSupers(orig);
   747                     if (s.isSuperBound() && !s.isExtendsBound()) {
   748                         s = new WildcardType(syms.objectType,
   749                                              BoundKind.UNBOUND,
   750                                              syms.boundClass);
   751                         changed = true;
   752                     } else if (s != orig) {
   753                         s = new WildcardType(upperBound(s),
   754                                              BoundKind.EXTENDS,
   755                                              syms.boundClass);
   756                         changed = true;
   757                     }
   758                     rewrite.append(s);
   759                 }
   760                 if (changed)
   761                     return subst(t.tsym.type, from.toList(), rewrite.toList());
   762                 else
   763                     return t;
   764             }
   766             @Override
   767             public Boolean visitClassType(ClassType t, Type s) {
   768                 Type sup = asSuper(t, s.tsym);
   769                 return sup != null
   770                     && sup.tsym == s.tsym
   771                     // You're not allowed to write
   772                     //     Vector<Object> vec = new Vector<String>();
   773                     // But with wildcards you can write
   774                     //     Vector<? extends Object> vec = new Vector<String>();
   775                     // which means that subtype checking must be done
   776                     // here instead of same-type checking (via containsType).
   777                     && (!s.isParameterized() || containsTypeRecursive(s, sup))
   778                     && isSubtypeNoCapture(sup.getEnclosingType(),
   779                                           s.getEnclosingType());
   780             }
   782             @Override
   783             public Boolean visitArrayType(ArrayType t, Type s) {
   784                 if (s.tag == ARRAY) {
   785                     if (t.elemtype.isPrimitive())
   786                         return isSameType(t.elemtype, elemtype(s));
   787                     else
   788                         return isSubtypeNoCapture(t.elemtype, elemtype(s));
   789                 }
   791                 if (s.tag == CLASS) {
   792                     Name sname = s.tsym.getQualifiedName();
   793                     return sname == names.java_lang_Object
   794                         || sname == names.java_lang_Cloneable
   795                         || sname == names.java_io_Serializable;
   796                 }
   798                 return false;
   799             }
   801             @Override
   802             public Boolean visitUndetVar(UndetVar t, Type s) {
   803                 //todo: test against origin needed? or replace with substitution?
   804                 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN) {
   805                     return true;
   806                 } else if (s.tag == BOT) {
   807                     //if 's' is 'null' there's no instantiated type U for which
   808                     //U <: s (but 'null' itself, which is not a valid type)
   809                     return false;
   810                 }
   812                 t.addBound(InferenceBound.UPPER, s, Types.this);
   813                 return true;
   814             }
   816             @Override
   817             public Boolean visitErrorType(ErrorType t, Type s) {
   818                 return true;
   819             }
   820         };
   822     /**
   823      * Is t a subtype of every type in given list `ts'?<br>
   824      * (not defined for Method and ForAll types)<br>
   825      * Allows unchecked conversions.
   826      */
   827     public boolean isSubtypeUnchecked(Type t, List<Type> ts, Warner warn) {
   828         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
   829             if (!isSubtypeUnchecked(t, l.head, warn))
   830                 return false;
   831         return true;
   832     }
   834     /**
   835      * Are corresponding elements of ts subtypes of ss?  If lists are
   836      * of different length, return false.
   837      */
   838     public boolean isSubtypes(List<Type> ts, List<Type> ss) {
   839         while (ts.tail != null && ss.tail != null
   840                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   841                isSubtype(ts.head, ss.head)) {
   842             ts = ts.tail;
   843             ss = ss.tail;
   844         }
   845         return ts.tail == null && ss.tail == null;
   846         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   847     }
   849     /**
   850      * Are corresponding elements of ts subtypes of ss, allowing
   851      * unchecked conversions?  If lists are of different length,
   852      * return false.
   853      **/
   854     public boolean isSubtypesUnchecked(List<Type> ts, List<Type> ss, Warner warn) {
   855         while (ts.tail != null && ss.tail != null
   856                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   857                isSubtypeUnchecked(ts.head, ss.head, warn)) {
   858             ts = ts.tail;
   859             ss = ss.tail;
   860         }
   861         return ts.tail == null && ss.tail == null;
   862         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   863     }
   864     // </editor-fold>
   866     // <editor-fold defaultstate="collapsed" desc="isSuperType">
   867     /**
   868      * Is t a supertype of s?
   869      */
   870     public boolean isSuperType(Type t, Type s) {
   871         switch (t.tag) {
   872         case ERROR:
   873             return true;
   874         case UNDETVAR: {
   875             UndetVar undet = (UndetVar)t;
   876             if (t == s ||
   877                 undet.qtype == s ||
   878                 s.tag == ERROR ||
   879                 s.tag == BOT) return true;
   880             undet.addBound(InferenceBound.LOWER, s, this);
   881             return true;
   882         }
   883         default:
   884             return isSubtype(s, t);
   885         }
   886     }
   887     // </editor-fold>
   889     // <editor-fold defaultstate="collapsed" desc="isSameType">
   890     /**
   891      * Are corresponding elements of the lists the same type?  If
   892      * lists are of different length, return false.
   893      */
   894     public boolean isSameTypes(List<Type> ts, List<Type> ss) {
   895         while (ts.tail != null && ss.tail != null
   896                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   897                isSameType(ts.head, ss.head)) {
   898             ts = ts.tail;
   899             ss = ss.tail;
   900         }
   901         return ts.tail == null && ss.tail == null;
   902         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   903     }
   905     /**
   906      * Is t the same type as s?
   907      */
   908     public boolean isSameType(Type t, Type s) {
   909         return isSameType.visit(t, s);
   910     }
   911     // where
   912         private TypeRelation isSameType = new TypeRelation() {
   914             public Boolean visitType(Type t, Type s) {
   915                 if (t == s)
   916                     return true;
   918                 if (s.isPartial())
   919                     return visit(s, t);
   921                 switch (t.tag) {
   922                 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
   923                 case DOUBLE: case BOOLEAN: case VOID: case BOT: case NONE:
   924                     return t.tag == s.tag;
   925                 case TYPEVAR: {
   926                     if (s.tag == TYPEVAR) {
   927                         //type-substitution does not preserve type-var types
   928                         //check that type var symbols and bounds are indeed the same
   929                         return t.tsym == s.tsym &&
   930                                 visit(t.getUpperBound(), s.getUpperBound());
   931                     }
   932                     else {
   933                         //special case for s == ? super X, where upper(s) = u
   934                         //check that u == t, where u has been set by Type.withTypeVar
   935                         return s.isSuperBound() &&
   936                                 !s.isExtendsBound() &&
   937                                 visit(t, upperBound(s));
   938                     }
   939                 }
   940                 default:
   941                     throw new AssertionError("isSameType " + t.tag);
   942                 }
   943             }
   945             @Override
   946             public Boolean visitWildcardType(WildcardType t, Type s) {
   947                 if (s.isPartial())
   948                     return visit(s, t);
   949                 else
   950                     return false;
   951             }
   953             @Override
   954             public Boolean visitClassType(ClassType t, Type s) {
   955                 if (t == s)
   956                     return true;
   958                 if (s.isPartial())
   959                     return visit(s, t);
   961                 if (s.isSuperBound() && !s.isExtendsBound())
   962                     return visit(t, upperBound(s)) && visit(t, lowerBound(s));
   964                 if (t.isCompound() && s.isCompound()) {
   965                     if (!visit(supertype(t), supertype(s)))
   966                         return false;
   968                     HashSet<SingletonType> set = new HashSet<SingletonType>();
   969                     for (Type x : interfaces(t))
   970                         set.add(new SingletonType(x));
   971                     for (Type x : interfaces(s)) {
   972                         if (!set.remove(new SingletonType(x)))
   973                             return false;
   974                     }
   975                     return (set.isEmpty());
   976                 }
   977                 return t.tsym == s.tsym
   978                     && visit(t.getEnclosingType(), s.getEnclosingType())
   979                     && containsTypeEquivalent(t.getTypeArguments(), s.getTypeArguments());
   980             }
   982             @Override
   983             public Boolean visitArrayType(ArrayType t, Type s) {
   984                 if (t == s)
   985                     return true;
   987                 if (s.isPartial())
   988                     return visit(s, t);
   990                 return s.hasTag(ARRAY)
   991                     && containsTypeEquivalent(t.elemtype, elemtype(s));
   992             }
   994             @Override
   995             public Boolean visitMethodType(MethodType t, Type s) {
   996                 // isSameType for methods does not take thrown
   997                 // exceptions into account!
   998                 return hasSameArgs(t, s) && visit(t.getReturnType(), s.getReturnType());
   999             }
  1001             @Override
  1002             public Boolean visitPackageType(PackageType t, Type s) {
  1003                 return t == s;
  1006             @Override
  1007             public Boolean visitForAll(ForAll t, Type s) {
  1008                 if (s.tag != FORALL)
  1009                     return false;
  1011                 ForAll forAll = (ForAll)s;
  1012                 return hasSameBounds(t, forAll)
  1013                     && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
  1016             @Override
  1017             public Boolean visitUndetVar(UndetVar t, Type s) {
  1018                 if (s.tag == WILDCARD)
  1019                     // FIXME, this might be leftovers from before capture conversion
  1020                     return false;
  1022                 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN)
  1023                     return true;
  1025                 t.addBound(InferenceBound.EQ, s, Types.this);
  1027                 return true;
  1030             @Override
  1031             public Boolean visitErrorType(ErrorType t, Type s) {
  1032                 return true;
  1034         };
  1035     // </editor-fold>
  1037     // <editor-fold defaultstate="collapsed" desc="Contains Type">
  1038     public boolean containedBy(Type t, Type s) {
  1039         switch (t.tag) {
  1040         case UNDETVAR:
  1041             if (s.tag == WILDCARD) {
  1042                 UndetVar undetvar = (UndetVar)t;
  1043                 WildcardType wt = (WildcardType)s;
  1044                 switch(wt.kind) {
  1045                     case UNBOUND: //similar to ? extends Object
  1046                     case EXTENDS: {
  1047                         Type bound = upperBound(s);
  1048                         undetvar.addBound(InferenceBound.UPPER, bound, this);
  1049                         break;
  1051                     case SUPER: {
  1052                         Type bound = lowerBound(s);
  1053                         undetvar.addBound(InferenceBound.LOWER, bound, this);
  1054                         break;
  1057                 return true;
  1058             } else {
  1059                 return isSameType(t, s);
  1061         case ERROR:
  1062             return true;
  1063         default:
  1064             return containsType(s, t);
  1068     boolean containsType(List<Type> ts, List<Type> ss) {
  1069         while (ts.nonEmpty() && ss.nonEmpty()
  1070                && containsType(ts.head, ss.head)) {
  1071             ts = ts.tail;
  1072             ss = ss.tail;
  1074         return ts.isEmpty() && ss.isEmpty();
  1077     /**
  1078      * Check if t contains s.
  1080      * <p>T contains S if:
  1082      * <p>{@code L(T) <: L(S) && U(S) <: U(T)}
  1084      * <p>This relation is only used by ClassType.isSubtype(), that
  1085      * is,
  1087      * <p>{@code C<S> <: C<T> if T contains S.}
  1089      * <p>Because of F-bounds, this relation can lead to infinite
  1090      * recursion.  Thus we must somehow break that recursion.  Notice
  1091      * that containsType() is only called from ClassType.isSubtype().
  1092      * Since the arguments have already been checked against their
  1093      * bounds, we know:
  1095      * <p>{@code U(S) <: U(T) if T is "super" bound (U(T) *is* the bound)}
  1097      * <p>{@code L(T) <: L(S) if T is "extends" bound (L(T) is bottom)}
  1099      * @param t a type
  1100      * @param s a type
  1101      */
  1102     public boolean containsType(Type t, Type s) {
  1103         return containsType.visit(t, s);
  1105     // where
  1106         private TypeRelation containsType = new TypeRelation() {
  1108             private Type U(Type t) {
  1109                 while (t.tag == WILDCARD) {
  1110                     WildcardType w = (WildcardType)t;
  1111                     if (w.isSuperBound())
  1112                         return w.bound == null ? syms.objectType : w.bound.bound;
  1113                     else
  1114                         t = w.type;
  1116                 return t;
  1119             private Type L(Type t) {
  1120                 while (t.tag == WILDCARD) {
  1121                     WildcardType w = (WildcardType)t;
  1122                     if (w.isExtendsBound())
  1123                         return syms.botType;
  1124                     else
  1125                         t = w.type;
  1127                 return t;
  1130             public Boolean visitType(Type t, Type s) {
  1131                 if (s.isPartial())
  1132                     return containedBy(s, t);
  1133                 else
  1134                     return isSameType(t, s);
  1137 //            void debugContainsType(WildcardType t, Type s) {
  1138 //                System.err.println();
  1139 //                System.err.format(" does %s contain %s?%n", t, s);
  1140 //                System.err.format(" %s U(%s) <: U(%s) %s = %s%n",
  1141 //                                  upperBound(s), s, t, U(t),
  1142 //                                  t.isSuperBound()
  1143 //                                  || isSubtypeNoCapture(upperBound(s), U(t)));
  1144 //                System.err.format(" %s L(%s) <: L(%s) %s = %s%n",
  1145 //                                  L(t), t, s, lowerBound(s),
  1146 //                                  t.isExtendsBound()
  1147 //                                  || isSubtypeNoCapture(L(t), lowerBound(s)));
  1148 //                System.err.println();
  1149 //            }
  1151             @Override
  1152             public Boolean visitWildcardType(WildcardType t, Type s) {
  1153                 if (s.isPartial())
  1154                     return containedBy(s, t);
  1155                 else {
  1156 //                    debugContainsType(t, s);
  1157                     return isSameWildcard(t, s)
  1158                         || isCaptureOf(s, t)
  1159                         || ((t.isExtendsBound() || isSubtypeNoCapture(L(t), lowerBound(s))) &&
  1160                             (t.isSuperBound() || isSubtypeNoCapture(upperBound(s), U(t))));
  1164             @Override
  1165             public Boolean visitUndetVar(UndetVar t, Type s) {
  1166                 if (s.tag != WILDCARD)
  1167                     return isSameType(t, s);
  1168                 else
  1169                     return false;
  1172             @Override
  1173             public Boolean visitErrorType(ErrorType t, Type s) {
  1174                 return true;
  1176         };
  1178     public boolean isCaptureOf(Type s, WildcardType t) {
  1179         if (s.tag != TYPEVAR || !((TypeVar)s).isCaptured())
  1180             return false;
  1181         return isSameWildcard(t, ((CapturedType)s).wildcard);
  1184     public boolean isSameWildcard(WildcardType t, Type s) {
  1185         if (s.tag != WILDCARD)
  1186             return false;
  1187         WildcardType w = (WildcardType)s;
  1188         return w.kind == t.kind && w.type == t.type;
  1191     public boolean containsTypeEquivalent(List<Type> ts, List<Type> ss) {
  1192         while (ts.nonEmpty() && ss.nonEmpty()
  1193                && containsTypeEquivalent(ts.head, ss.head)) {
  1194             ts = ts.tail;
  1195             ss = ss.tail;
  1197         return ts.isEmpty() && ss.isEmpty();
  1199     // </editor-fold>
  1201     // <editor-fold defaultstate="collapsed" desc="isCastable">
  1202     public boolean isCastable(Type t, Type s) {
  1203         return isCastable(t, s, noWarnings);
  1206     /**
  1207      * Is t is castable to s?<br>
  1208      * s is assumed to be an erased type.<br>
  1209      * (not defined for Method and ForAll types).
  1210      */
  1211     public boolean isCastable(Type t, Type s, Warner warn) {
  1212         if (t == s)
  1213             return true;
  1215         if (t.isPrimitive() != s.isPrimitive())
  1216             return allowBoxing && (
  1217                     isConvertible(t, s, warn)
  1218                     || (allowObjectToPrimitiveCast &&
  1219                         s.isPrimitive() &&
  1220                         isSubtype(boxedClass(s).type, t)));
  1221         if (warn != warnStack.head) {
  1222             try {
  1223                 warnStack = warnStack.prepend(warn);
  1224                 checkUnsafeVarargsConversion(t, s, warn);
  1225                 return isCastable.visit(t,s);
  1226             } finally {
  1227                 warnStack = warnStack.tail;
  1229         } else {
  1230             return isCastable.visit(t,s);
  1233     // where
  1234         private TypeRelation isCastable = new TypeRelation() {
  1236             public Boolean visitType(Type t, Type s) {
  1237                 if (s.tag == ERROR)
  1238                     return true;
  1240                 switch (t.tag) {
  1241                 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
  1242                 case DOUBLE:
  1243                     return s.isNumeric();
  1244                 case BOOLEAN:
  1245                     return s.tag == BOOLEAN;
  1246                 case VOID:
  1247                     return false;
  1248                 case BOT:
  1249                     return isSubtype(t, s);
  1250                 default:
  1251                     throw new AssertionError();
  1255             @Override
  1256             public Boolean visitWildcardType(WildcardType t, Type s) {
  1257                 return isCastable(upperBound(t), s, warnStack.head);
  1260             @Override
  1261             public Boolean visitClassType(ClassType t, Type s) {
  1262                 if (s.tag == ERROR || s.tag == BOT)
  1263                     return true;
  1265                 if (s.tag == TYPEVAR) {
  1266                     if (isCastable(t, s.getUpperBound(), noWarnings)) {
  1267                         warnStack.head.warn(LintCategory.UNCHECKED);
  1268                         return true;
  1269                     } else {
  1270                         return false;
  1274                 if (t.isCompound()) {
  1275                     Warner oldWarner = warnStack.head;
  1276                     warnStack.head = noWarnings;
  1277                     if (!visit(supertype(t), s))
  1278                         return false;
  1279                     for (Type intf : interfaces(t)) {
  1280                         if (!visit(intf, s))
  1281                             return false;
  1283                     if (warnStack.head.hasLint(LintCategory.UNCHECKED))
  1284                         oldWarner.warn(LintCategory.UNCHECKED);
  1285                     return true;
  1288                 if (s.isCompound()) {
  1289                     // call recursively to reuse the above code
  1290                     return visitClassType((ClassType)s, t);
  1293                 if (s.tag == CLASS || s.tag == ARRAY) {
  1294                     boolean upcast;
  1295                     if ((upcast = isSubtype(erasure(t), erasure(s)))
  1296                         || isSubtype(erasure(s), erasure(t))) {
  1297                         if (!upcast && s.tag == ARRAY) {
  1298                             if (!isReifiable(s))
  1299                                 warnStack.head.warn(LintCategory.UNCHECKED);
  1300                             return true;
  1301                         } else if (s.isRaw()) {
  1302                             return true;
  1303                         } else if (t.isRaw()) {
  1304                             if (!isUnbounded(s))
  1305                                 warnStack.head.warn(LintCategory.UNCHECKED);
  1306                             return true;
  1308                         // Assume |a| <: |b|
  1309                         final Type a = upcast ? t : s;
  1310                         final Type b = upcast ? s : t;
  1311                         final boolean HIGH = true;
  1312                         final boolean LOW = false;
  1313                         final boolean DONT_REWRITE_TYPEVARS = false;
  1314                         Type aHigh = rewriteQuantifiers(a, HIGH, DONT_REWRITE_TYPEVARS);
  1315                         Type aLow  = rewriteQuantifiers(a, LOW,  DONT_REWRITE_TYPEVARS);
  1316                         Type bHigh = rewriteQuantifiers(b, HIGH, DONT_REWRITE_TYPEVARS);
  1317                         Type bLow  = rewriteQuantifiers(b, LOW,  DONT_REWRITE_TYPEVARS);
  1318                         Type lowSub = asSub(bLow, aLow.tsym);
  1319                         Type highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
  1320                         if (highSub == null) {
  1321                             final boolean REWRITE_TYPEVARS = true;
  1322                             aHigh = rewriteQuantifiers(a, HIGH, REWRITE_TYPEVARS);
  1323                             aLow  = rewriteQuantifiers(a, LOW,  REWRITE_TYPEVARS);
  1324                             bHigh = rewriteQuantifiers(b, HIGH, REWRITE_TYPEVARS);
  1325                             bLow  = rewriteQuantifiers(b, LOW,  REWRITE_TYPEVARS);
  1326                             lowSub = asSub(bLow, aLow.tsym);
  1327                             highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
  1329                         if (highSub != null) {
  1330                             if (!(a.tsym == highSub.tsym && a.tsym == lowSub.tsym)) {
  1331                                 Assert.error(a.tsym + " != " + highSub.tsym + " != " + lowSub.tsym);
  1333                             if (!disjointTypes(aHigh.allparams(), highSub.allparams())
  1334                                 && !disjointTypes(aHigh.allparams(), lowSub.allparams())
  1335                                 && !disjointTypes(aLow.allparams(), highSub.allparams())
  1336                                 && !disjointTypes(aLow.allparams(), lowSub.allparams())) {
  1337                                 if (upcast ? giveWarning(a, b) :
  1338                                     giveWarning(b, a))
  1339                                     warnStack.head.warn(LintCategory.UNCHECKED);
  1340                                 return true;
  1343                         if (isReifiable(s))
  1344                             return isSubtypeUnchecked(a, b);
  1345                         else
  1346                             return isSubtypeUnchecked(a, b, warnStack.head);
  1349                     // Sidecast
  1350                     if (s.tag == CLASS) {
  1351                         if ((s.tsym.flags() & INTERFACE) != 0) {
  1352                             return ((t.tsym.flags() & FINAL) == 0)
  1353                                 ? sideCast(t, s, warnStack.head)
  1354                                 : sideCastFinal(t, s, warnStack.head);
  1355                         } else if ((t.tsym.flags() & INTERFACE) != 0) {
  1356                             return ((s.tsym.flags() & FINAL) == 0)
  1357                                 ? sideCast(t, s, warnStack.head)
  1358                                 : sideCastFinal(t, s, warnStack.head);
  1359                         } else {
  1360                             // unrelated class types
  1361                             return false;
  1365                 return false;
  1368             @Override
  1369             public Boolean visitArrayType(ArrayType t, Type s) {
  1370                 switch (s.tag) {
  1371                 case ERROR:
  1372                 case BOT:
  1373                     return true;
  1374                 case TYPEVAR:
  1375                     if (isCastable(s, t, noWarnings)) {
  1376                         warnStack.head.warn(LintCategory.UNCHECKED);
  1377                         return true;
  1378                     } else {
  1379                         return false;
  1381                 case CLASS:
  1382                     return isSubtype(t, s);
  1383                 case ARRAY:
  1384                     if (elemtype(t).isPrimitive() || elemtype(s).isPrimitive()) {
  1385                         return elemtype(t).tag == elemtype(s).tag;
  1386                     } else {
  1387                         return visit(elemtype(t), elemtype(s));
  1389                 default:
  1390                     return false;
  1394             @Override
  1395             public Boolean visitTypeVar(TypeVar t, Type s) {
  1396                 switch (s.tag) {
  1397                 case ERROR:
  1398                 case BOT:
  1399                     return true;
  1400                 case TYPEVAR:
  1401                     if (isSubtype(t, s)) {
  1402                         return true;
  1403                     } else if (isCastable(t.bound, s, noWarnings)) {
  1404                         warnStack.head.warn(LintCategory.UNCHECKED);
  1405                         return true;
  1406                     } else {
  1407                         return false;
  1409                 default:
  1410                     return isCastable(t.bound, s, warnStack.head);
  1414             @Override
  1415             public Boolean visitErrorType(ErrorType t, Type s) {
  1416                 return true;
  1418         };
  1419     // </editor-fold>
  1421     // <editor-fold defaultstate="collapsed" desc="disjointTypes">
  1422     public boolean disjointTypes(List<Type> ts, List<Type> ss) {
  1423         while (ts.tail != null && ss.tail != null) {
  1424             if (disjointType(ts.head, ss.head)) return true;
  1425             ts = ts.tail;
  1426             ss = ss.tail;
  1428         return false;
  1431     /**
  1432      * Two types or wildcards are considered disjoint if it can be
  1433      * proven that no type can be contained in both. It is
  1434      * conservative in that it is allowed to say that two types are
  1435      * not disjoint, even though they actually are.
  1437      * The type {@code C<X>} is castable to {@code C<Y>} exactly if
  1438      * {@code X} and {@code Y} are not disjoint.
  1439      */
  1440     public boolean disjointType(Type t, Type s) {
  1441         return disjointType.visit(t, s);
  1443     // where
  1444         private TypeRelation disjointType = new TypeRelation() {
  1446             private Set<TypePair> cache = new HashSet<TypePair>();
  1448             public Boolean visitType(Type t, Type s) {
  1449                 if (s.tag == WILDCARD)
  1450                     return visit(s, t);
  1451                 else
  1452                     return notSoftSubtypeRecursive(t, s) || notSoftSubtypeRecursive(s, t);
  1455             private boolean isCastableRecursive(Type t, Type s) {
  1456                 TypePair pair = new TypePair(t, s);
  1457                 if (cache.add(pair)) {
  1458                     try {
  1459                         return Types.this.isCastable(t, s);
  1460                     } finally {
  1461                         cache.remove(pair);
  1463                 } else {
  1464                     return true;
  1468             private boolean notSoftSubtypeRecursive(Type t, Type s) {
  1469                 TypePair pair = new TypePair(t, s);
  1470                 if (cache.add(pair)) {
  1471                     try {
  1472                         return Types.this.notSoftSubtype(t, s);
  1473                     } finally {
  1474                         cache.remove(pair);
  1476                 } else {
  1477                     return false;
  1481             @Override
  1482             public Boolean visitWildcardType(WildcardType t, Type s) {
  1483                 if (t.isUnbound())
  1484                     return false;
  1486                 if (s.tag != WILDCARD) {
  1487                     if (t.isExtendsBound())
  1488                         return notSoftSubtypeRecursive(s, t.type);
  1489                     else // isSuperBound()
  1490                         return notSoftSubtypeRecursive(t.type, s);
  1493                 if (s.isUnbound())
  1494                     return false;
  1496                 if (t.isExtendsBound()) {
  1497                     if (s.isExtendsBound())
  1498                         return !isCastableRecursive(t.type, upperBound(s));
  1499                     else if (s.isSuperBound())
  1500                         return notSoftSubtypeRecursive(lowerBound(s), t.type);
  1501                 } else if (t.isSuperBound()) {
  1502                     if (s.isExtendsBound())
  1503                         return notSoftSubtypeRecursive(t.type, upperBound(s));
  1505                 return false;
  1507         };
  1508     // </editor-fold>
  1510     // <editor-fold defaultstate="collapsed" desc="lowerBoundArgtypes">
  1511     /**
  1512      * Returns the lower bounds of the formals of a method.
  1513      */
  1514     public List<Type> lowerBoundArgtypes(Type t) {
  1515         return lowerBounds(t.getParameterTypes());
  1517     public List<Type> lowerBounds(List<Type> ts) {
  1518         return map(ts, lowerBoundMapping);
  1520     private final Mapping lowerBoundMapping = new Mapping("lowerBound") {
  1521             public Type apply(Type t) {
  1522                 return lowerBound(t);
  1524         };
  1525     // </editor-fold>
  1527     // <editor-fold defaultstate="collapsed" desc="notSoftSubtype">
  1528     /**
  1529      * This relation answers the question: is impossible that
  1530      * something of type `t' can be a subtype of `s'? This is
  1531      * different from the question "is `t' not a subtype of `s'?"
  1532      * when type variables are involved: Integer is not a subtype of T
  1533      * where {@code <T extends Number>} but it is not true that Integer cannot
  1534      * possibly be a subtype of T.
  1535      */
  1536     public boolean notSoftSubtype(Type t, Type s) {
  1537         if (t == s) return false;
  1538         if (t.tag == TYPEVAR) {
  1539             TypeVar tv = (TypeVar) t;
  1540             return !isCastable(tv.bound,
  1541                                relaxBound(s),
  1542                                noWarnings);
  1544         if (s.tag != WILDCARD)
  1545             s = upperBound(s);
  1547         return !isSubtype(t, relaxBound(s));
  1550     private Type relaxBound(Type t) {
  1551         if (t.tag == TYPEVAR) {
  1552             while (t.tag == TYPEVAR)
  1553                 t = t.getUpperBound();
  1554             t = rewriteQuantifiers(t, true, true);
  1556         return t;
  1558     // </editor-fold>
  1560     // <editor-fold defaultstate="collapsed" desc="isReifiable">
  1561     public boolean isReifiable(Type t) {
  1562         return isReifiable.visit(t);
  1564     // where
  1565         private UnaryVisitor<Boolean> isReifiable = new UnaryVisitor<Boolean>() {
  1567             public Boolean visitType(Type t, Void ignored) {
  1568                 return true;
  1571             @Override
  1572             public Boolean visitClassType(ClassType t, Void ignored) {
  1573                 if (t.isCompound())
  1574                     return false;
  1575                 else {
  1576                     if (!t.isParameterized())
  1577                         return true;
  1579                     for (Type param : t.allparams()) {
  1580                         if (!param.isUnbound())
  1581                             return false;
  1583                     return true;
  1587             @Override
  1588             public Boolean visitArrayType(ArrayType t, Void ignored) {
  1589                 return visit(t.elemtype);
  1592             @Override
  1593             public Boolean visitTypeVar(TypeVar t, Void ignored) {
  1594                 return false;
  1596         };
  1597     // </editor-fold>
  1599     // <editor-fold defaultstate="collapsed" desc="Array Utils">
  1600     public boolean isArray(Type t) {
  1601         while (t.tag == WILDCARD)
  1602             t = upperBound(t);
  1603         return t.tag == ARRAY;
  1606     /**
  1607      * The element type of an array.
  1608      */
  1609     public Type elemtype(Type t) {
  1610         switch (t.tag) {
  1611         case WILDCARD:
  1612             return elemtype(upperBound(t));
  1613         case ARRAY:
  1614             return ((ArrayType)t).elemtype;
  1615         case FORALL:
  1616             return elemtype(((ForAll)t).qtype);
  1617         case ERROR:
  1618             return t;
  1619         default:
  1620             return null;
  1624     public Type elemtypeOrType(Type t) {
  1625         Type elemtype = elemtype(t);
  1626         return elemtype != null ?
  1627             elemtype :
  1628             t;
  1631     /**
  1632      * Mapping to take element type of an arraytype
  1633      */
  1634     private Mapping elemTypeFun = new Mapping ("elemTypeFun") {
  1635         public Type apply(Type t) { return elemtype(t); }
  1636     };
  1638     /**
  1639      * The number of dimensions of an array type.
  1640      */
  1641     public int dimensions(Type t) {
  1642         int result = 0;
  1643         while (t.tag == ARRAY) {
  1644             result++;
  1645             t = elemtype(t);
  1647         return result;
  1650     /**
  1651      * Returns an ArrayType with the component type t
  1653      * @param t The component type of the ArrayType
  1654      * @return the ArrayType for the given component
  1655      */
  1656     public ArrayType makeArrayType(Type t) {
  1657         if (t.tag == VOID ||
  1658             t.tag == PACKAGE) {
  1659             Assert.error("Type t must not be a VOID or PACKAGE type, " + t.toString());
  1661         return new ArrayType(t, syms.arrayClass);
  1663     // </editor-fold>
  1665     // <editor-fold defaultstate="collapsed" desc="asSuper">
  1666     /**
  1667      * Return the (most specific) base type of t that starts with the
  1668      * given symbol.  If none exists, return null.
  1670      * @param t a type
  1671      * @param sym a symbol
  1672      */
  1673     public Type asSuper(Type t, Symbol sym) {
  1674         return asSuper.visit(t, sym);
  1676     // where
  1677         private SimpleVisitor<Type,Symbol> asSuper = new SimpleVisitor<Type,Symbol>() {
  1679             public Type visitType(Type t, Symbol sym) {
  1680                 return null;
  1683             @Override
  1684             public Type visitClassType(ClassType t, Symbol sym) {
  1685                 if (t.tsym == sym)
  1686                     return t;
  1688                 Type st = supertype(t);
  1689                 if (st.tag == CLASS || st.tag == TYPEVAR || st.tag == ERROR) {
  1690                     Type x = asSuper(st, sym);
  1691                     if (x != null)
  1692                         return x;
  1694                 if ((sym.flags() & INTERFACE) != 0) {
  1695                     for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
  1696                         Type x = asSuper(l.head, sym);
  1697                         if (x != null)
  1698                             return x;
  1701                 return null;
  1704             @Override
  1705             public Type visitArrayType(ArrayType t, Symbol sym) {
  1706                 return isSubtype(t, sym.type) ? sym.type : null;
  1709             @Override
  1710             public Type visitTypeVar(TypeVar t, Symbol sym) {
  1711                 if (t.tsym == sym)
  1712                     return t;
  1713                 else
  1714                     return asSuper(t.bound, sym);
  1717             @Override
  1718             public Type visitErrorType(ErrorType t, Symbol sym) {
  1719                 return t;
  1721         };
  1723     /**
  1724      * Return the base type of t or any of its outer types that starts
  1725      * with the given symbol.  If none exists, return null.
  1727      * @param t a type
  1728      * @param sym a symbol
  1729      */
  1730     public Type asOuterSuper(Type t, Symbol sym) {
  1731         switch (t.tag) {
  1732         case CLASS:
  1733             do {
  1734                 Type s = asSuper(t, sym);
  1735                 if (s != null) return s;
  1736                 t = t.getEnclosingType();
  1737             } while (t.tag == CLASS);
  1738             return null;
  1739         case ARRAY:
  1740             return isSubtype(t, sym.type) ? sym.type : null;
  1741         case TYPEVAR:
  1742             return asSuper(t, sym);
  1743         case ERROR:
  1744             return t;
  1745         default:
  1746             return null;
  1750     /**
  1751      * Return the base type of t or any of its enclosing types that
  1752      * starts with the given symbol.  If none exists, return null.
  1754      * @param t a type
  1755      * @param sym a symbol
  1756      */
  1757     public Type asEnclosingSuper(Type t, Symbol sym) {
  1758         switch (t.tag) {
  1759         case CLASS:
  1760             do {
  1761                 Type s = asSuper(t, sym);
  1762                 if (s != null) return s;
  1763                 Type outer = t.getEnclosingType();
  1764                 t = (outer.tag == CLASS) ? outer :
  1765                     (t.tsym.owner.enclClass() != null) ? t.tsym.owner.enclClass().type :
  1766                     Type.noType;
  1767             } while (t.tag == CLASS);
  1768             return null;
  1769         case ARRAY:
  1770             return isSubtype(t, sym.type) ? sym.type : null;
  1771         case TYPEVAR:
  1772             return asSuper(t, sym);
  1773         case ERROR:
  1774             return t;
  1775         default:
  1776             return null;
  1779     // </editor-fold>
  1781     // <editor-fold defaultstate="collapsed" desc="memberType">
  1782     /**
  1783      * The type of given symbol, seen as a member of t.
  1785      * @param t a type
  1786      * @param sym a symbol
  1787      */
  1788     public Type memberType(Type t, Symbol sym) {
  1789         return (sym.flags() & STATIC) != 0
  1790             ? sym.type
  1791             : memberType.visit(t, sym);
  1793     // where
  1794         private SimpleVisitor<Type,Symbol> memberType = new SimpleVisitor<Type,Symbol>() {
  1796             public Type visitType(Type t, Symbol sym) {
  1797                 return sym.type;
  1800             @Override
  1801             public Type visitWildcardType(WildcardType t, Symbol sym) {
  1802                 return memberType(upperBound(t), sym);
  1805             @Override
  1806             public Type visitClassType(ClassType t, Symbol sym) {
  1807                 Symbol owner = sym.owner;
  1808                 long flags = sym.flags();
  1809                 if (((flags & STATIC) == 0) && owner.type.isParameterized()) {
  1810                     Type base = asOuterSuper(t, owner);
  1811                     //if t is an intersection type T = CT & I1 & I2 ... & In
  1812                     //its supertypes CT, I1, ... In might contain wildcards
  1813                     //so we need to go through capture conversion
  1814                     base = t.isCompound() ? capture(base) : base;
  1815                     if (base != null) {
  1816                         List<Type> ownerParams = owner.type.allparams();
  1817                         List<Type> baseParams = base.allparams();
  1818                         if (ownerParams.nonEmpty()) {
  1819                             if (baseParams.isEmpty()) {
  1820                                 // then base is a raw type
  1821                                 return erasure(sym.type);
  1822                             } else {
  1823                                 return subst(sym.type, ownerParams, baseParams);
  1828                 return sym.type;
  1831             @Override
  1832             public Type visitTypeVar(TypeVar t, Symbol sym) {
  1833                 return memberType(t.bound, sym);
  1836             @Override
  1837             public Type visitErrorType(ErrorType t, Symbol sym) {
  1838                 return t;
  1840         };
  1841     // </editor-fold>
  1843     // <editor-fold defaultstate="collapsed" desc="isAssignable">
  1844     public boolean isAssignable(Type t, Type s) {
  1845         return isAssignable(t, s, noWarnings);
  1848     /**
  1849      * Is t assignable to s?<br>
  1850      * Equivalent to subtype except for constant values and raw
  1851      * types.<br>
  1852      * (not defined for Method and ForAll types)
  1853      */
  1854     public boolean isAssignable(Type t, Type s, Warner warn) {
  1855         if (t.tag == ERROR)
  1856             return true;
  1857         if (t.tag.isSubRangeOf(INT) && t.constValue() != null) {
  1858             int value = ((Number)t.constValue()).intValue();
  1859             switch (s.tag) {
  1860             case BYTE:
  1861                 if (Byte.MIN_VALUE <= value && value <= Byte.MAX_VALUE)
  1862                     return true;
  1863                 break;
  1864             case CHAR:
  1865                 if (Character.MIN_VALUE <= value && value <= Character.MAX_VALUE)
  1866                     return true;
  1867                 break;
  1868             case SHORT:
  1869                 if (Short.MIN_VALUE <= value && value <= Short.MAX_VALUE)
  1870                     return true;
  1871                 break;
  1872             case INT:
  1873                 return true;
  1874             case CLASS:
  1875                 switch (unboxedType(s).tag) {
  1876                 case BYTE:
  1877                 case CHAR:
  1878                 case SHORT:
  1879                     return isAssignable(t, unboxedType(s), warn);
  1881                 break;
  1884         return isConvertible(t, s, warn);
  1886     // </editor-fold>
  1888     // <editor-fold defaultstate="collapsed" desc="erasure">
  1889     /**
  1890      * The erasure of t {@code |t|} -- the type that results when all
  1891      * type parameters in t are deleted.
  1892      */
  1893     public Type erasure(Type t) {
  1894         return eraseNotNeeded(t)? t : erasure(t, false);
  1896     //where
  1897     private boolean eraseNotNeeded(Type t) {
  1898         // We don't want to erase primitive types and String type as that
  1899         // operation is idempotent. Also, erasing these could result in loss
  1900         // of information such as constant values attached to such types.
  1901         return (t.isPrimitive()) || (syms.stringType.tsym == t.tsym);
  1904     private Type erasure(Type t, boolean recurse) {
  1905         if (t.isPrimitive())
  1906             return t; /* fast special case */
  1907         else
  1908             return erasure.visit(t, recurse);
  1910     // where
  1911         private SimpleVisitor<Type, Boolean> erasure = new SimpleVisitor<Type, Boolean>() {
  1912             public Type visitType(Type t, Boolean recurse) {
  1913                 if (t.isPrimitive())
  1914                     return t; /*fast special case*/
  1915                 else
  1916                     return t.map(recurse ? erasureRecFun : erasureFun);
  1919             @Override
  1920             public Type visitWildcardType(WildcardType t, Boolean recurse) {
  1921                 return erasure(upperBound(t), recurse);
  1924             @Override
  1925             public Type visitClassType(ClassType t, Boolean recurse) {
  1926                 Type erased = t.tsym.erasure(Types.this);
  1927                 if (recurse) {
  1928                     erased = new ErasedClassType(erased.getEnclosingType(),erased.tsym);
  1930                 return erased;
  1933             @Override
  1934             public Type visitTypeVar(TypeVar t, Boolean recurse) {
  1935                 return erasure(t.bound, recurse);
  1938             @Override
  1939             public Type visitErrorType(ErrorType t, Boolean recurse) {
  1940                 return t;
  1942         };
  1944     private Mapping erasureFun = new Mapping ("erasure") {
  1945             public Type apply(Type t) { return erasure(t); }
  1946         };
  1948     private Mapping erasureRecFun = new Mapping ("erasureRecursive") {
  1949         public Type apply(Type t) { return erasureRecursive(t); }
  1950     };
  1952     public List<Type> erasure(List<Type> ts) {
  1953         return Type.map(ts, erasureFun);
  1956     public Type erasureRecursive(Type t) {
  1957         return erasure(t, true);
  1960     public List<Type> erasureRecursive(List<Type> ts) {
  1961         return Type.map(ts, erasureRecFun);
  1963     // </editor-fold>
  1965     // <editor-fold defaultstate="collapsed" desc="makeCompoundType">
  1966     /**
  1967      * Make a compound type from non-empty list of types
  1969      * @param bounds            the types from which the compound type is formed
  1970      * @param supertype         is objectType if all bounds are interfaces,
  1971      *                          null otherwise.
  1972      */
  1973     public Type makeCompoundType(List<Type> bounds,
  1974                                  Type supertype) {
  1975         ClassSymbol bc =
  1976             new ClassSymbol(ABSTRACT|PUBLIC|SYNTHETIC|COMPOUND|ACYCLIC,
  1977                             Type.moreInfo
  1978                                 ? names.fromString(bounds.toString())
  1979                                 : names.empty,
  1980                             syms.noSymbol);
  1981         if (bounds.head.tag == TYPEVAR)
  1982             // error condition, recover
  1983                 bc.erasure_field = syms.objectType;
  1984             else
  1985                 bc.erasure_field = erasure(bounds.head);
  1986             bc.members_field = new Scope(bc);
  1987         ClassType bt = (ClassType)bc.type;
  1988         bt.allparams_field = List.nil();
  1989         if (supertype != null) {
  1990             bt.supertype_field = supertype;
  1991             bt.interfaces_field = bounds;
  1992         } else {
  1993             bt.supertype_field = bounds.head;
  1994             bt.interfaces_field = bounds.tail;
  1996         Assert.check(bt.supertype_field.tsym.completer != null
  1997                 || !bt.supertype_field.isInterface(),
  1998             bt.supertype_field);
  1999         return bt;
  2002     /**
  2003      * Same as {@link #makeCompoundType(List,Type)}, except that the
  2004      * second parameter is computed directly. Note that this might
  2005      * cause a symbol completion.  Hence, this version of
  2006      * makeCompoundType may not be called during a classfile read.
  2007      */
  2008     public Type makeCompoundType(List<Type> bounds) {
  2009         Type supertype = (bounds.head.tsym.flags() & INTERFACE) != 0 ?
  2010             supertype(bounds.head) : null;
  2011         return makeCompoundType(bounds, supertype);
  2014     /**
  2015      * A convenience wrapper for {@link #makeCompoundType(List)}; the
  2016      * arguments are converted to a list and passed to the other
  2017      * method.  Note that this might cause a symbol completion.
  2018      * Hence, this version of makeCompoundType may not be called
  2019      * during a classfile read.
  2020      */
  2021     public Type makeCompoundType(Type bound1, Type bound2) {
  2022         return makeCompoundType(List.of(bound1, bound2));
  2024     // </editor-fold>
  2026     // <editor-fold defaultstate="collapsed" desc="supertype">
  2027     public Type supertype(Type t) {
  2028         return supertype.visit(t);
  2030     // where
  2031         private UnaryVisitor<Type> supertype = new UnaryVisitor<Type>() {
  2033             public Type visitType(Type t, Void ignored) {
  2034                 // A note on wildcards: there is no good way to
  2035                 // determine a supertype for a super bounded wildcard.
  2036                 return null;
  2039             @Override
  2040             public Type visitClassType(ClassType t, Void ignored) {
  2041                 if (t.supertype_field == null) {
  2042                     Type supertype = ((ClassSymbol)t.tsym).getSuperclass();
  2043                     // An interface has no superclass; its supertype is Object.
  2044                     if (t.isInterface())
  2045                         supertype = ((ClassType)t.tsym.type).supertype_field;
  2046                     if (t.supertype_field == null) {
  2047                         List<Type> actuals = classBound(t).allparams();
  2048                         List<Type> formals = t.tsym.type.allparams();
  2049                         if (t.hasErasedSupertypes()) {
  2050                             t.supertype_field = erasureRecursive(supertype);
  2051                         } else if (formals.nonEmpty()) {
  2052                             t.supertype_field = subst(supertype, formals, actuals);
  2054                         else {
  2055                             t.supertype_field = supertype;
  2059                 return t.supertype_field;
  2062             /**
  2063              * The supertype is always a class type. If the type
  2064              * variable's bounds start with a class type, this is also
  2065              * the supertype.  Otherwise, the supertype is
  2066              * java.lang.Object.
  2067              */
  2068             @Override
  2069             public Type visitTypeVar(TypeVar t, Void ignored) {
  2070                 if (t.bound.tag == TYPEVAR ||
  2071                     (!t.bound.isCompound() && !t.bound.isInterface())) {
  2072                     return t.bound;
  2073                 } else {
  2074                     return supertype(t.bound);
  2078             @Override
  2079             public Type visitArrayType(ArrayType t, Void ignored) {
  2080                 if (t.elemtype.isPrimitive() || isSameType(t.elemtype, syms.objectType))
  2081                     return arraySuperType();
  2082                 else
  2083                     return new ArrayType(supertype(t.elemtype), t.tsym);
  2086             @Override
  2087             public Type visitErrorType(ErrorType t, Void ignored) {
  2088                 return t;
  2090         };
  2091     // </editor-fold>
  2093     // <editor-fold defaultstate="collapsed" desc="interfaces">
  2094     /**
  2095      * Return the interfaces implemented by this class.
  2096      */
  2097     public List<Type> interfaces(Type t) {
  2098         return interfaces.visit(t);
  2100     // where
  2101         private UnaryVisitor<List<Type>> interfaces = new UnaryVisitor<List<Type>>() {
  2103             public List<Type> visitType(Type t, Void ignored) {
  2104                 return List.nil();
  2107             @Override
  2108             public List<Type> visitClassType(ClassType t, Void ignored) {
  2109                 if (t.interfaces_field == null) {
  2110                     List<Type> interfaces = ((ClassSymbol)t.tsym).getInterfaces();
  2111                     if (t.interfaces_field == null) {
  2112                         // If t.interfaces_field is null, then t must
  2113                         // be a parameterized type (not to be confused
  2114                         // with a generic type declaration).
  2115                         // Terminology:
  2116                         //    Parameterized type: List<String>
  2117                         //    Generic type declaration: class List<E> { ... }
  2118                         // So t corresponds to List<String> and
  2119                         // t.tsym.type corresponds to List<E>.
  2120                         // The reason t must be parameterized type is
  2121                         // that completion will happen as a side
  2122                         // effect of calling
  2123                         // ClassSymbol.getInterfaces.  Since
  2124                         // t.interfaces_field is null after
  2125                         // completion, we can assume that t is not the
  2126                         // type of a class/interface declaration.
  2127                         Assert.check(t != t.tsym.type, t);
  2128                         List<Type> actuals = t.allparams();
  2129                         List<Type> formals = t.tsym.type.allparams();
  2130                         if (t.hasErasedSupertypes()) {
  2131                             t.interfaces_field = erasureRecursive(interfaces);
  2132                         } else if (formals.nonEmpty()) {
  2133                             t.interfaces_field =
  2134                                 upperBounds(subst(interfaces, formals, actuals));
  2136                         else {
  2137                             t.interfaces_field = interfaces;
  2141                 return t.interfaces_field;
  2144             @Override
  2145             public List<Type> visitTypeVar(TypeVar t, Void ignored) {
  2146                 if (t.bound.isCompound())
  2147                     return interfaces(t.bound);
  2149                 if (t.bound.isInterface())
  2150                     return List.of(t.bound);
  2152                 return List.nil();
  2154         };
  2156     public boolean isDirectSuperInterface(TypeSymbol isym, TypeSymbol origin) {
  2157         for (Type i2 : interfaces(origin.type)) {
  2158             if (isym == i2.tsym) return true;
  2160         return false;
  2162     // </editor-fold>
  2164     // <editor-fold defaultstate="collapsed" desc="isDerivedRaw">
  2165     Map<Type,Boolean> isDerivedRawCache = new HashMap<Type,Boolean>();
  2167     public boolean isDerivedRaw(Type t) {
  2168         Boolean result = isDerivedRawCache.get(t);
  2169         if (result == null) {
  2170             result = isDerivedRawInternal(t);
  2171             isDerivedRawCache.put(t, result);
  2173         return result;
  2176     public boolean isDerivedRawInternal(Type t) {
  2177         if (t.isErroneous())
  2178             return false;
  2179         return
  2180             t.isRaw() ||
  2181             supertype(t) != null && isDerivedRaw(supertype(t)) ||
  2182             isDerivedRaw(interfaces(t));
  2185     public boolean isDerivedRaw(List<Type> ts) {
  2186         List<Type> l = ts;
  2187         while (l.nonEmpty() && !isDerivedRaw(l.head)) l = l.tail;
  2188         return l.nonEmpty();
  2190     // </editor-fold>
  2192     // <editor-fold defaultstate="collapsed" desc="setBounds">
  2193     /**
  2194      * Set the bounds field of the given type variable to reflect a
  2195      * (possibly multiple) list of bounds.
  2196      * @param t                 a type variable
  2197      * @param bounds            the bounds, must be nonempty
  2198      * @param supertype         is objectType if all bounds are interfaces,
  2199      *                          null otherwise.
  2200      */
  2201     public void setBounds(TypeVar t, List<Type> bounds, Type supertype) {
  2202         if (bounds.tail.isEmpty())
  2203             t.bound = bounds.head;
  2204         else
  2205             t.bound = makeCompoundType(bounds, supertype);
  2206         t.rank_field = -1;
  2209     /**
  2210      * Same as {@link #setBounds(Type.TypeVar,List,Type)}, except that
  2211      * third parameter is computed directly, as follows: if all
  2212      * all bounds are interface types, the computed supertype is Object,
  2213      * otherwise the supertype is simply left null (in this case, the supertype
  2214      * is assumed to be the head of the bound list passed as second argument).
  2215      * Note that this check might cause a symbol completion. Hence, this version of
  2216      * setBounds may not be called during a classfile read.
  2217      */
  2218     public void setBounds(TypeVar t, List<Type> bounds) {
  2219         Type supertype = (bounds.head.tsym.flags() & INTERFACE) != 0 ?
  2220             syms.objectType : null;
  2221         setBounds(t, bounds, supertype);
  2222         t.rank_field = -1;
  2224     // </editor-fold>
  2226     // <editor-fold defaultstate="collapsed" desc="getBounds">
  2227     /**
  2228      * Return list of bounds of the given type variable.
  2229      */
  2230     public List<Type> getBounds(TypeVar t) {
  2231                 if (t.bound.hasTag(NONE))
  2232             return List.nil();
  2233         else if (t.bound.isErroneous() || !t.bound.isCompound())
  2234             return List.of(t.bound);
  2235         else if ((erasure(t).tsym.flags() & INTERFACE) == 0)
  2236             return interfaces(t).prepend(supertype(t));
  2237         else
  2238             // No superclass was given in bounds.
  2239             // In this case, supertype is Object, erasure is first interface.
  2240             return interfaces(t);
  2242     // </editor-fold>
  2244     // <editor-fold defaultstate="collapsed" desc="classBound">
  2245     /**
  2246      * If the given type is a (possibly selected) type variable,
  2247      * return the bounding class of this type, otherwise return the
  2248      * type itself.
  2249      */
  2250     public Type classBound(Type t) {
  2251         return classBound.visit(t);
  2253     // where
  2254         private UnaryVisitor<Type> classBound = new UnaryVisitor<Type>() {
  2256             public Type visitType(Type t, Void ignored) {
  2257                 return t;
  2260             @Override
  2261             public Type visitClassType(ClassType t, Void ignored) {
  2262                 Type outer1 = classBound(t.getEnclosingType());
  2263                 if (outer1 != t.getEnclosingType())
  2264                     return new ClassType(outer1, t.getTypeArguments(), t.tsym);
  2265                 else
  2266                     return t;
  2269             @Override
  2270             public Type visitTypeVar(TypeVar t, Void ignored) {
  2271                 return classBound(supertype(t));
  2274             @Override
  2275             public Type visitErrorType(ErrorType t, Void ignored) {
  2276                 return t;
  2278         };
  2279     // </editor-fold>
  2281     // <editor-fold defaultstate="collapsed" desc="sub signature / override equivalence">
  2282     /**
  2283      * Returns true iff the first signature is a <em>sub
  2284      * signature</em> of the other.  This is <b>not</b> an equivalence
  2285      * relation.
  2287      * @jls section 8.4.2.
  2288      * @see #overrideEquivalent(Type t, Type s)
  2289      * @param t first signature (possibly raw).
  2290      * @param s second signature (could be subjected to erasure).
  2291      * @return true if t is a sub signature of s.
  2292      */
  2293     public boolean isSubSignature(Type t, Type s) {
  2294         return isSubSignature(t, s, true);
  2297     public boolean isSubSignature(Type t, Type s, boolean strict) {
  2298         return hasSameArgs(t, s, strict) || hasSameArgs(t, erasure(s), strict);
  2301     /**
  2302      * Returns true iff these signatures are related by <em>override
  2303      * equivalence</em>.  This is the natural extension of
  2304      * isSubSignature to an equivalence relation.
  2306      * @jls section 8.4.2.
  2307      * @see #isSubSignature(Type t, Type s)
  2308      * @param t a signature (possible raw, could be subjected to
  2309      * erasure).
  2310      * @param s a signature (possible raw, could be subjected to
  2311      * erasure).
  2312      * @return true if either argument is a sub signature of the other.
  2313      */
  2314     public boolean overrideEquivalent(Type t, Type s) {
  2315         return hasSameArgs(t, s) ||
  2316             hasSameArgs(t, erasure(s)) || hasSameArgs(erasure(t), s);
  2319     public boolean overridesObjectMethod(TypeSymbol origin, Symbol msym) {
  2320         for (Scope.Entry e = syms.objectType.tsym.members().lookup(msym.name) ; e.scope != null ; e = e.next()) {
  2321             if (msym.overrides(e.sym, origin, Types.this, true)) {
  2322                 return true;
  2325         return false;
  2328     // <editor-fold defaultstate="collapsed" desc="Determining method implementation in given site">
  2329     class ImplementationCache {
  2331         private WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>> _map =
  2332                 new WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>>();
  2334         class Entry {
  2335             final MethodSymbol cachedImpl;
  2336             final Filter<Symbol> implFilter;
  2337             final boolean checkResult;
  2338             final int prevMark;
  2340             public Entry(MethodSymbol cachedImpl,
  2341                     Filter<Symbol> scopeFilter,
  2342                     boolean checkResult,
  2343                     int prevMark) {
  2344                 this.cachedImpl = cachedImpl;
  2345                 this.implFilter = scopeFilter;
  2346                 this.checkResult = checkResult;
  2347                 this.prevMark = prevMark;
  2350             boolean matches(Filter<Symbol> scopeFilter, boolean checkResult, int mark) {
  2351                 return this.implFilter == scopeFilter &&
  2352                         this.checkResult == checkResult &&
  2353                         this.prevMark == mark;
  2357         MethodSymbol get(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
  2358             SoftReference<Map<TypeSymbol, Entry>> ref_cache = _map.get(ms);
  2359             Map<TypeSymbol, Entry> cache = ref_cache != null ? ref_cache.get() : null;
  2360             if (cache == null) {
  2361                 cache = new HashMap<TypeSymbol, Entry>();
  2362                 _map.put(ms, new SoftReference<Map<TypeSymbol, Entry>>(cache));
  2364             Entry e = cache.get(origin);
  2365             CompoundScope members = membersClosure(origin.type, true);
  2366             if (e == null ||
  2367                     !e.matches(implFilter, checkResult, members.getMark())) {
  2368                 MethodSymbol impl = implementationInternal(ms, origin, checkResult, implFilter);
  2369                 cache.put(origin, new Entry(impl, implFilter, checkResult, members.getMark()));
  2370                 return impl;
  2372             else {
  2373                 return e.cachedImpl;
  2377         private MethodSymbol implementationInternal(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
  2378             for (Type t = origin.type; t.tag == CLASS || t.tag == TYPEVAR; t = supertype(t)) {
  2379                 while (t.tag == TYPEVAR)
  2380                     t = t.getUpperBound();
  2381                 TypeSymbol c = t.tsym;
  2382                 for (Scope.Entry e = c.members().lookup(ms.name, implFilter);
  2383                      e.scope != null;
  2384                      e = e.next(implFilter)) {
  2385                     if (e.sym != null &&
  2386                              e.sym.overrides(ms, origin, Types.this, checkResult))
  2387                         return (MethodSymbol)e.sym;
  2390             return null;
  2394     private ImplementationCache implCache = new ImplementationCache();
  2396     public MethodSymbol implementation(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
  2397         return implCache.get(ms, origin, checkResult, implFilter);
  2399     // </editor-fold>
  2401     // <editor-fold defaultstate="collapsed" desc="compute transitive closure of all members in given site">
  2402     class MembersClosureCache extends SimpleVisitor<CompoundScope, Boolean> {
  2404         private WeakHashMap<TypeSymbol, Entry> _map =
  2405                 new WeakHashMap<TypeSymbol, Entry>();
  2407         class Entry {
  2408             final boolean skipInterfaces;
  2409             final CompoundScope compoundScope;
  2411             public Entry(boolean skipInterfaces, CompoundScope compoundScope) {
  2412                 this.skipInterfaces = skipInterfaces;
  2413                 this.compoundScope = compoundScope;
  2416             boolean matches(boolean skipInterfaces) {
  2417                 return this.skipInterfaces == skipInterfaces;
  2421         List<TypeSymbol> seenTypes = List.nil();
  2423         /** members closure visitor methods **/
  2425         public CompoundScope visitType(Type t, Boolean skipInterface) {
  2426             return null;
  2429         @Override
  2430         public CompoundScope visitClassType(ClassType t, Boolean skipInterface) {
  2431             if (seenTypes.contains(t.tsym)) {
  2432                 //this is possible when an interface is implemented in multiple
  2433                 //superclasses, or when a classs hierarchy is circular - in such
  2434                 //cases we don't need to recurse (empty scope is returned)
  2435                 return new CompoundScope(t.tsym);
  2437             try {
  2438                 seenTypes = seenTypes.prepend(t.tsym);
  2439                 ClassSymbol csym = (ClassSymbol)t.tsym;
  2440                 Entry e = _map.get(csym);
  2441                 if (e == null || !e.matches(skipInterface)) {
  2442                     CompoundScope membersClosure = new CompoundScope(csym);
  2443                     if (!skipInterface) {
  2444                         for (Type i : interfaces(t)) {
  2445                             membersClosure.addSubScope(visit(i, skipInterface));
  2448                     membersClosure.addSubScope(visit(supertype(t), skipInterface));
  2449                     membersClosure.addSubScope(csym.members());
  2450                     e = new Entry(skipInterface, membersClosure);
  2451                     _map.put(csym, e);
  2453                 return e.compoundScope;
  2455             finally {
  2456                 seenTypes = seenTypes.tail;
  2460         @Override
  2461         public CompoundScope visitTypeVar(TypeVar t, Boolean skipInterface) {
  2462             return visit(t.getUpperBound(), skipInterface);
  2466     private MembersClosureCache membersCache = new MembersClosureCache();
  2468     public CompoundScope membersClosure(Type site, boolean skipInterface) {
  2469         return membersCache.visit(site, skipInterface);
  2471     // </editor-fold>
  2474     //where
  2475     public List<MethodSymbol> interfaceCandidates(Type site, MethodSymbol ms) {
  2476         Filter<Symbol> filter = new MethodFilter(ms, site);
  2477         List<MethodSymbol> candidates = List.nil();
  2478         for (Symbol s : membersClosure(site, false).getElements(filter)) {
  2479             if (!site.tsym.isInterface() && !s.owner.isInterface()) {
  2480                 return List.of((MethodSymbol)s);
  2481             } else if (!candidates.contains(s)) {
  2482                 candidates = candidates.prepend((MethodSymbol)s);
  2485         return prune(candidates, ownerComparator);
  2488     public List<MethodSymbol> prune(List<MethodSymbol> methods, Comparator<MethodSymbol> cmp) {
  2489         ListBuffer<MethodSymbol> methodsMin = ListBuffer.lb();
  2490         for (MethodSymbol m1 : methods) {
  2491             boolean isMin_m1 = true;
  2492             for (MethodSymbol m2 : methods) {
  2493                 if (m1 == m2) continue;
  2494                 if (cmp.compare(m2, m1) < 0) {
  2495                     isMin_m1 = false;
  2496                     break;
  2499             if (isMin_m1)
  2500                 methodsMin.append(m1);
  2502         return methodsMin.toList();
  2505     Comparator<MethodSymbol> ownerComparator = new Comparator<MethodSymbol>() {
  2506         public int compare(MethodSymbol s1, MethodSymbol s2) {
  2507             return s1.owner.isSubClass(s2.owner, Types.this) ? -1 : 1;
  2509     };
  2510     // where
  2511             private class MethodFilter implements Filter<Symbol> {
  2513                 Symbol msym;
  2514                 Type site;
  2516                 MethodFilter(Symbol msym, Type site) {
  2517                     this.msym = msym;
  2518                     this.site = site;
  2521                 public boolean accepts(Symbol s) {
  2522                     return s.kind == Kinds.MTH &&
  2523                             s.name == msym.name &&
  2524                             s.isInheritedIn(site.tsym, Types.this) &&
  2525                             overrideEquivalent(memberType(site, s), memberType(site, msym));
  2527             };
  2528     // </editor-fold>
  2530     /**
  2531      * Does t have the same arguments as s?  It is assumed that both
  2532      * types are (possibly polymorphic) method types.  Monomorphic
  2533      * method types "have the same arguments", if their argument lists
  2534      * are equal.  Polymorphic method types "have the same arguments",
  2535      * if they have the same arguments after renaming all type
  2536      * variables of one to corresponding type variables in the other,
  2537      * where correspondence is by position in the type parameter list.
  2538      */
  2539     public boolean hasSameArgs(Type t, Type s) {
  2540         return hasSameArgs(t, s, true);
  2543     public boolean hasSameArgs(Type t, Type s, boolean strict) {
  2544         return hasSameArgs(t, s, strict ? hasSameArgs_strict : hasSameArgs_nonstrict);
  2547     private boolean hasSameArgs(Type t, Type s, TypeRelation hasSameArgs) {
  2548         return hasSameArgs.visit(t, s);
  2550     // where
  2551         private class HasSameArgs extends TypeRelation {
  2553             boolean strict;
  2555             public HasSameArgs(boolean strict) {
  2556                 this.strict = strict;
  2559             public Boolean visitType(Type t, Type s) {
  2560                 throw new AssertionError();
  2563             @Override
  2564             public Boolean visitMethodType(MethodType t, Type s) {
  2565                 return s.tag == METHOD
  2566                     && containsTypeEquivalent(t.argtypes, s.getParameterTypes());
  2569             @Override
  2570             public Boolean visitForAll(ForAll t, Type s) {
  2571                 if (s.tag != FORALL)
  2572                     return strict ? false : visitMethodType(t.asMethodType(), s);
  2574                 ForAll forAll = (ForAll)s;
  2575                 return hasSameBounds(t, forAll)
  2576                     && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
  2579             @Override
  2580             public Boolean visitErrorType(ErrorType t, Type s) {
  2581                 return false;
  2583         };
  2585         TypeRelation hasSameArgs_strict = new HasSameArgs(true);
  2586         TypeRelation hasSameArgs_nonstrict = new HasSameArgs(false);
  2588     // </editor-fold>
  2590     // <editor-fold defaultstate="collapsed" desc="subst">
  2591     public List<Type> subst(List<Type> ts,
  2592                             List<Type> from,
  2593                             List<Type> to) {
  2594         return new Subst(from, to).subst(ts);
  2597     /**
  2598      * Substitute all occurrences of a type in `from' with the
  2599      * corresponding type in `to' in 't'. Match lists `from' and `to'
  2600      * from the right: If lists have different length, discard leading
  2601      * elements of the longer list.
  2602      */
  2603     public Type subst(Type t, List<Type> from, List<Type> to) {
  2604         return new Subst(from, to).subst(t);
  2607     private class Subst extends UnaryVisitor<Type> {
  2608         List<Type> from;
  2609         List<Type> to;
  2611         public Subst(List<Type> from, List<Type> to) {
  2612             int fromLength = from.length();
  2613             int toLength = to.length();
  2614             while (fromLength > toLength) {
  2615                 fromLength--;
  2616                 from = from.tail;
  2618             while (fromLength < toLength) {
  2619                 toLength--;
  2620                 to = to.tail;
  2622             this.from = from;
  2623             this.to = to;
  2626         Type subst(Type t) {
  2627             if (from.tail == null)
  2628                 return t;
  2629             else
  2630                 return visit(t);
  2633         List<Type> subst(List<Type> ts) {
  2634             if (from.tail == null)
  2635                 return ts;
  2636             boolean wild = false;
  2637             if (ts.nonEmpty() && from.nonEmpty()) {
  2638                 Type head1 = subst(ts.head);
  2639                 List<Type> tail1 = subst(ts.tail);
  2640                 if (head1 != ts.head || tail1 != ts.tail)
  2641                     return tail1.prepend(head1);
  2643             return ts;
  2646         public Type visitType(Type t, Void ignored) {
  2647             return t;
  2650         @Override
  2651         public Type visitMethodType(MethodType t, Void ignored) {
  2652             List<Type> argtypes = subst(t.argtypes);
  2653             Type restype = subst(t.restype);
  2654             List<Type> thrown = subst(t.thrown);
  2655             if (argtypes == t.argtypes &&
  2656                 restype == t.restype &&
  2657                 thrown == t.thrown)
  2658                 return t;
  2659             else
  2660                 return new MethodType(argtypes, restype, thrown, t.tsym);
  2663         @Override
  2664         public Type visitTypeVar(TypeVar t, Void ignored) {
  2665             for (List<Type> from = this.from, to = this.to;
  2666                  from.nonEmpty();
  2667                  from = from.tail, to = to.tail) {
  2668                 if (t == from.head) {
  2669                     return to.head.withTypeVar(t);
  2672             return t;
  2675         @Override
  2676         public Type visitClassType(ClassType t, Void ignored) {
  2677             if (!t.isCompound()) {
  2678                 List<Type> typarams = t.getTypeArguments();
  2679                 List<Type> typarams1 = subst(typarams);
  2680                 Type outer = t.getEnclosingType();
  2681                 Type outer1 = subst(outer);
  2682                 if (typarams1 == typarams && outer1 == outer)
  2683                     return t;
  2684                 else
  2685                     return new ClassType(outer1, typarams1, t.tsym);
  2686             } else {
  2687                 Type st = subst(supertype(t));
  2688                 List<Type> is = upperBounds(subst(interfaces(t)));
  2689                 if (st == supertype(t) && is == interfaces(t))
  2690                     return t;
  2691                 else
  2692                     return makeCompoundType(is.prepend(st));
  2696         @Override
  2697         public Type visitWildcardType(WildcardType t, Void ignored) {
  2698             Type bound = t.type;
  2699             if (t.kind != BoundKind.UNBOUND)
  2700                 bound = subst(bound);
  2701             if (bound == t.type) {
  2702                 return t;
  2703             } else {
  2704                 if (t.isExtendsBound() && bound.isExtendsBound())
  2705                     bound = upperBound(bound);
  2706                 return new WildcardType(bound, t.kind, syms.boundClass, t.bound);
  2710         @Override
  2711         public Type visitArrayType(ArrayType t, Void ignored) {
  2712             Type elemtype = subst(t.elemtype);
  2713             if (elemtype == t.elemtype)
  2714                 return t;
  2715             else
  2716                 return new ArrayType(upperBound(elemtype), t.tsym);
  2719         @Override
  2720         public Type visitForAll(ForAll t, Void ignored) {
  2721             if (Type.containsAny(to, t.tvars)) {
  2722                 //perform alpha-renaming of free-variables in 't'
  2723                 //if 'to' types contain variables that are free in 't'
  2724                 List<Type> freevars = newInstances(t.tvars);
  2725                 t = new ForAll(freevars,
  2726                         Types.this.subst(t.qtype, t.tvars, freevars));
  2728             List<Type> tvars1 = substBounds(t.tvars, from, to);
  2729             Type qtype1 = subst(t.qtype);
  2730             if (tvars1 == t.tvars && qtype1 == t.qtype) {
  2731                 return t;
  2732             } else if (tvars1 == t.tvars) {
  2733                 return new ForAll(tvars1, qtype1);
  2734             } else {
  2735                 return new ForAll(tvars1, Types.this.subst(qtype1, t.tvars, tvars1));
  2739         @Override
  2740         public Type visitErrorType(ErrorType t, Void ignored) {
  2741             return t;
  2745     public List<Type> substBounds(List<Type> tvars,
  2746                                   List<Type> from,
  2747                                   List<Type> to) {
  2748         if (tvars.isEmpty())
  2749             return tvars;
  2750         ListBuffer<Type> newBoundsBuf = lb();
  2751         boolean changed = false;
  2752         // calculate new bounds
  2753         for (Type t : tvars) {
  2754             TypeVar tv = (TypeVar) t;
  2755             Type bound = subst(tv.bound, from, to);
  2756             if (bound != tv.bound)
  2757                 changed = true;
  2758             newBoundsBuf.append(bound);
  2760         if (!changed)
  2761             return tvars;
  2762         ListBuffer<Type> newTvars = lb();
  2763         // create new type variables without bounds
  2764         for (Type t : tvars) {
  2765             newTvars.append(new TypeVar(t.tsym, null, syms.botType));
  2767         // the new bounds should use the new type variables in place
  2768         // of the old
  2769         List<Type> newBounds = newBoundsBuf.toList();
  2770         from = tvars;
  2771         to = newTvars.toList();
  2772         for (; !newBounds.isEmpty(); newBounds = newBounds.tail) {
  2773             newBounds.head = subst(newBounds.head, from, to);
  2775         newBounds = newBoundsBuf.toList();
  2776         // set the bounds of new type variables to the new bounds
  2777         for (Type t : newTvars.toList()) {
  2778             TypeVar tv = (TypeVar) t;
  2779             tv.bound = newBounds.head;
  2780             newBounds = newBounds.tail;
  2782         return newTvars.toList();
  2785     public TypeVar substBound(TypeVar t, List<Type> from, List<Type> to) {
  2786         Type bound1 = subst(t.bound, from, to);
  2787         if (bound1 == t.bound)
  2788             return t;
  2789         else {
  2790             // create new type variable without bounds
  2791             TypeVar tv = new TypeVar(t.tsym, null, syms.botType);
  2792             // the new bound should use the new type variable in place
  2793             // of the old
  2794             tv.bound = subst(bound1, List.<Type>of(t), List.<Type>of(tv));
  2795             return tv;
  2798     // </editor-fold>
  2800     // <editor-fold defaultstate="collapsed" desc="hasSameBounds">
  2801     /**
  2802      * Does t have the same bounds for quantified variables as s?
  2803      */
  2804     boolean hasSameBounds(ForAll t, ForAll s) {
  2805         List<Type> l1 = t.tvars;
  2806         List<Type> l2 = s.tvars;
  2807         while (l1.nonEmpty() && l2.nonEmpty() &&
  2808                isSameType(l1.head.getUpperBound(),
  2809                           subst(l2.head.getUpperBound(),
  2810                                 s.tvars,
  2811                                 t.tvars))) {
  2812             l1 = l1.tail;
  2813             l2 = l2.tail;
  2815         return l1.isEmpty() && l2.isEmpty();
  2817     // </editor-fold>
  2819     // <editor-fold defaultstate="collapsed" desc="newInstances">
  2820     /** Create new vector of type variables from list of variables
  2821      *  changing all recursive bounds from old to new list.
  2822      */
  2823     public List<Type> newInstances(List<Type> tvars) {
  2824         List<Type> tvars1 = Type.map(tvars, newInstanceFun);
  2825         for (List<Type> l = tvars1; l.nonEmpty(); l = l.tail) {
  2826             TypeVar tv = (TypeVar) l.head;
  2827             tv.bound = subst(tv.bound, tvars, tvars1);
  2829         return tvars1;
  2831     static private Mapping newInstanceFun = new Mapping("newInstanceFun") {
  2832             public Type apply(Type t) { return new TypeVar(t.tsym, t.getUpperBound(), t.getLowerBound()); }
  2833         };
  2834     // </editor-fold>
  2836     public Type createMethodTypeWithParameters(Type original, List<Type> newParams) {
  2837         return original.accept(methodWithParameters, newParams);
  2839     // where
  2840         private final MapVisitor<List<Type>> methodWithParameters = new MapVisitor<List<Type>>() {
  2841             public Type visitType(Type t, List<Type> newParams) {
  2842                 throw new IllegalArgumentException("Not a method type: " + t);
  2844             public Type visitMethodType(MethodType t, List<Type> newParams) {
  2845                 return new MethodType(newParams, t.restype, t.thrown, t.tsym);
  2847             public Type visitForAll(ForAll t, List<Type> newParams) {
  2848                 return new ForAll(t.tvars, t.qtype.accept(this, newParams));
  2850         };
  2852     public Type createMethodTypeWithThrown(Type original, List<Type> newThrown) {
  2853         return original.accept(methodWithThrown, newThrown);
  2855     // where
  2856         private final MapVisitor<List<Type>> methodWithThrown = new MapVisitor<List<Type>>() {
  2857             public Type visitType(Type t, List<Type> newThrown) {
  2858                 throw new IllegalArgumentException("Not a method type: " + t);
  2860             public Type visitMethodType(MethodType t, List<Type> newThrown) {
  2861                 return new MethodType(t.argtypes, t.restype, newThrown, t.tsym);
  2863             public Type visitForAll(ForAll t, List<Type> newThrown) {
  2864                 return new ForAll(t.tvars, t.qtype.accept(this, newThrown));
  2866         };
  2868     public Type createMethodTypeWithReturn(Type original, Type newReturn) {
  2869         return original.accept(methodWithReturn, newReturn);
  2871     // where
  2872         private final MapVisitor<Type> methodWithReturn = new MapVisitor<Type>() {
  2873             public Type visitType(Type t, Type newReturn) {
  2874                 throw new IllegalArgumentException("Not a method type: " + t);
  2876             public Type visitMethodType(MethodType t, Type newReturn) {
  2877                 return new MethodType(t.argtypes, newReturn, t.thrown, t.tsym);
  2879             public Type visitForAll(ForAll t, Type newReturn) {
  2880                 return new ForAll(t.tvars, t.qtype.accept(this, newReturn));
  2882         };
  2884     // <editor-fold defaultstate="collapsed" desc="createErrorType">
  2885     public Type createErrorType(Type originalType) {
  2886         return new ErrorType(originalType, syms.errSymbol);
  2889     public Type createErrorType(ClassSymbol c, Type originalType) {
  2890         return new ErrorType(c, originalType);
  2893     public Type createErrorType(Name name, TypeSymbol container, Type originalType) {
  2894         return new ErrorType(name, container, originalType);
  2896     // </editor-fold>
  2898     // <editor-fold defaultstate="collapsed" desc="rank">
  2899     /**
  2900      * The rank of a class is the length of the longest path between
  2901      * the class and java.lang.Object in the class inheritance
  2902      * graph. Undefined for all but reference types.
  2903      */
  2904     public int rank(Type t) {
  2905         switch(t.tag) {
  2906         case CLASS: {
  2907             ClassType cls = (ClassType)t;
  2908             if (cls.rank_field < 0) {
  2909                 Name fullname = cls.tsym.getQualifiedName();
  2910                 if (fullname == names.java_lang_Object)
  2911                     cls.rank_field = 0;
  2912                 else {
  2913                     int r = rank(supertype(cls));
  2914                     for (List<Type> l = interfaces(cls);
  2915                          l.nonEmpty();
  2916                          l = l.tail) {
  2917                         if (rank(l.head) > r)
  2918                             r = rank(l.head);
  2920                     cls.rank_field = r + 1;
  2923             return cls.rank_field;
  2925         case TYPEVAR: {
  2926             TypeVar tvar = (TypeVar)t;
  2927             if (tvar.rank_field < 0) {
  2928                 int r = rank(supertype(tvar));
  2929                 for (List<Type> l = interfaces(tvar);
  2930                      l.nonEmpty();
  2931                      l = l.tail) {
  2932                     if (rank(l.head) > r) r = rank(l.head);
  2934                 tvar.rank_field = r + 1;
  2936             return tvar.rank_field;
  2938         case ERROR:
  2939             return 0;
  2940         default:
  2941             throw new AssertionError();
  2944     // </editor-fold>
  2946     /**
  2947      * Helper method for generating a string representation of a given type
  2948      * accordingly to a given locale
  2949      */
  2950     public String toString(Type t, Locale locale) {
  2951         return Printer.createStandardPrinter(messages).visit(t, locale);
  2954     /**
  2955      * Helper method for generating a string representation of a given type
  2956      * accordingly to a given locale
  2957      */
  2958     public String toString(Symbol t, Locale locale) {
  2959         return Printer.createStandardPrinter(messages).visit(t, locale);
  2962     // <editor-fold defaultstate="collapsed" desc="toString">
  2963     /**
  2964      * This toString is slightly more descriptive than the one on Type.
  2966      * @deprecated Types.toString(Type t, Locale l) provides better support
  2967      * for localization
  2968      */
  2969     @Deprecated
  2970     public String toString(Type t) {
  2971         if (t.tag == FORALL) {
  2972             ForAll forAll = (ForAll)t;
  2973             return typaramsString(forAll.tvars) + forAll.qtype;
  2975         return "" + t;
  2977     // where
  2978         private String typaramsString(List<Type> tvars) {
  2979             StringBuilder s = new StringBuilder();
  2980             s.append('<');
  2981             boolean first = true;
  2982             for (Type t : tvars) {
  2983                 if (!first) s.append(", ");
  2984                 first = false;
  2985                 appendTyparamString(((TypeVar)t), s);
  2987             s.append('>');
  2988             return s.toString();
  2990         private void appendTyparamString(TypeVar t, StringBuilder buf) {
  2991             buf.append(t);
  2992             if (t.bound == null ||
  2993                 t.bound.tsym.getQualifiedName() == names.java_lang_Object)
  2994                 return;
  2995             buf.append(" extends "); // Java syntax; no need for i18n
  2996             Type bound = t.bound;
  2997             if (!bound.isCompound()) {
  2998                 buf.append(bound);
  2999             } else if ((erasure(t).tsym.flags() & INTERFACE) == 0) {
  3000                 buf.append(supertype(t));
  3001                 for (Type intf : interfaces(t)) {
  3002                     buf.append('&');
  3003                     buf.append(intf);
  3005             } else {
  3006                 // No superclass was given in bounds.
  3007                 // In this case, supertype is Object, erasure is first interface.
  3008                 boolean first = true;
  3009                 for (Type intf : interfaces(t)) {
  3010                     if (!first) buf.append('&');
  3011                     first = false;
  3012                     buf.append(intf);
  3016     // </editor-fold>
  3018     // <editor-fold defaultstate="collapsed" desc="Determining least upper bounds of types">
  3019     /**
  3020      * A cache for closures.
  3022      * <p>A closure is a list of all the supertypes and interfaces of
  3023      * a class or interface type, ordered by ClassSymbol.precedes
  3024      * (that is, subclasses come first, arbitrary but fixed
  3025      * otherwise).
  3026      */
  3027     private Map<Type,List<Type>> closureCache = new HashMap<Type,List<Type>>();
  3029     /**
  3030      * Returns the closure of a class or interface type.
  3031      */
  3032     public List<Type> closure(Type t) {
  3033         List<Type> cl = closureCache.get(t);
  3034         if (cl == null) {
  3035             Type st = supertype(t);
  3036             if (!t.isCompound()) {
  3037                 if (st.tag == CLASS) {
  3038                     cl = insert(closure(st), t);
  3039                 } else if (st.tag == TYPEVAR) {
  3040                     cl = closure(st).prepend(t);
  3041                 } else {
  3042                     cl = List.of(t);
  3044             } else {
  3045                 cl = closure(supertype(t));
  3047             for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail)
  3048                 cl = union(cl, closure(l.head));
  3049             closureCache.put(t, cl);
  3051         return cl;
  3054     /**
  3055      * Insert a type in a closure
  3056      */
  3057     public List<Type> insert(List<Type> cl, Type t) {
  3058         if (cl.isEmpty() || t.tsym.precedes(cl.head.tsym, this)) {
  3059             return cl.prepend(t);
  3060         } else if (cl.head.tsym.precedes(t.tsym, this)) {
  3061             return insert(cl.tail, t).prepend(cl.head);
  3062         } else {
  3063             return cl;
  3067     /**
  3068      * Form the union of two closures
  3069      */
  3070     public List<Type> union(List<Type> cl1, List<Type> cl2) {
  3071         if (cl1.isEmpty()) {
  3072             return cl2;
  3073         } else if (cl2.isEmpty()) {
  3074             return cl1;
  3075         } else if (cl1.head.tsym.precedes(cl2.head.tsym, this)) {
  3076             return union(cl1.tail, cl2).prepend(cl1.head);
  3077         } else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) {
  3078             return union(cl1, cl2.tail).prepend(cl2.head);
  3079         } else {
  3080             return union(cl1.tail, cl2.tail).prepend(cl1.head);
  3084     /**
  3085      * Intersect two closures
  3086      */
  3087     public List<Type> intersect(List<Type> cl1, List<Type> cl2) {
  3088         if (cl1 == cl2)
  3089             return cl1;
  3090         if (cl1.isEmpty() || cl2.isEmpty())
  3091             return List.nil();
  3092         if (cl1.head.tsym.precedes(cl2.head.tsym, this))
  3093             return intersect(cl1.tail, cl2);
  3094         if (cl2.head.tsym.precedes(cl1.head.tsym, this))
  3095             return intersect(cl1, cl2.tail);
  3096         if (isSameType(cl1.head, cl2.head))
  3097             return intersect(cl1.tail, cl2.tail).prepend(cl1.head);
  3098         if (cl1.head.tsym == cl2.head.tsym &&
  3099             cl1.head.tag == CLASS && cl2.head.tag == CLASS) {
  3100             if (cl1.head.isParameterized() && cl2.head.isParameterized()) {
  3101                 Type merge = merge(cl1.head,cl2.head);
  3102                 return intersect(cl1.tail, cl2.tail).prepend(merge);
  3104             if (cl1.head.isRaw() || cl2.head.isRaw())
  3105                 return intersect(cl1.tail, cl2.tail).prepend(erasure(cl1.head));
  3107         return intersect(cl1.tail, cl2.tail);
  3109     // where
  3110         class TypePair {
  3111             final Type t1;
  3112             final Type t2;
  3113             TypePair(Type t1, Type t2) {
  3114                 this.t1 = t1;
  3115                 this.t2 = t2;
  3117             @Override
  3118             public int hashCode() {
  3119                 return 127 * Types.hashCode(t1) + Types.hashCode(t2);
  3121             @Override
  3122             public boolean equals(Object obj) {
  3123                 if (!(obj instanceof TypePair))
  3124                     return false;
  3125                 TypePair typePair = (TypePair)obj;
  3126                 return isSameType(t1, typePair.t1)
  3127                     && isSameType(t2, typePair.t2);
  3130         Set<TypePair> mergeCache = new HashSet<TypePair>();
  3131         private Type merge(Type c1, Type c2) {
  3132             ClassType class1 = (ClassType) c1;
  3133             List<Type> act1 = class1.getTypeArguments();
  3134             ClassType class2 = (ClassType) c2;
  3135             List<Type> act2 = class2.getTypeArguments();
  3136             ListBuffer<Type> merged = new ListBuffer<Type>();
  3137             List<Type> typarams = class1.tsym.type.getTypeArguments();
  3139             while (act1.nonEmpty() && act2.nonEmpty() && typarams.nonEmpty()) {
  3140                 if (containsType(act1.head, act2.head)) {
  3141                     merged.append(act1.head);
  3142                 } else if (containsType(act2.head, act1.head)) {
  3143                     merged.append(act2.head);
  3144                 } else {
  3145                     TypePair pair = new TypePair(c1, c2);
  3146                     Type m;
  3147                     if (mergeCache.add(pair)) {
  3148                         m = new WildcardType(lub(upperBound(act1.head),
  3149                                                  upperBound(act2.head)),
  3150                                              BoundKind.EXTENDS,
  3151                                              syms.boundClass);
  3152                         mergeCache.remove(pair);
  3153                     } else {
  3154                         m = new WildcardType(syms.objectType,
  3155                                              BoundKind.UNBOUND,
  3156                                              syms.boundClass);
  3158                     merged.append(m.withTypeVar(typarams.head));
  3160                 act1 = act1.tail;
  3161                 act2 = act2.tail;
  3162                 typarams = typarams.tail;
  3164             Assert.check(act1.isEmpty() && act2.isEmpty() && typarams.isEmpty());
  3165             return new ClassType(class1.getEnclosingType(), merged.toList(), class1.tsym);
  3168     /**
  3169      * Return the minimum type of a closure, a compound type if no
  3170      * unique minimum exists.
  3171      */
  3172     private Type compoundMin(List<Type> cl) {
  3173         if (cl.isEmpty()) return syms.objectType;
  3174         List<Type> compound = closureMin(cl);
  3175         if (compound.isEmpty())
  3176             return null;
  3177         else if (compound.tail.isEmpty())
  3178             return compound.head;
  3179         else
  3180             return makeCompoundType(compound);
  3183     /**
  3184      * Return the minimum types of a closure, suitable for computing
  3185      * compoundMin or glb.
  3186      */
  3187     private List<Type> closureMin(List<Type> cl) {
  3188         ListBuffer<Type> classes = lb();
  3189         ListBuffer<Type> interfaces = lb();
  3190         while (!cl.isEmpty()) {
  3191             Type current = cl.head;
  3192             if (current.isInterface())
  3193                 interfaces.append(current);
  3194             else
  3195                 classes.append(current);
  3196             ListBuffer<Type> candidates = lb();
  3197             for (Type t : cl.tail) {
  3198                 if (!isSubtypeNoCapture(current, t))
  3199                     candidates.append(t);
  3201             cl = candidates.toList();
  3203         return classes.appendList(interfaces).toList();
  3206     /**
  3207      * Return the least upper bound of pair of types.  if the lub does
  3208      * not exist return null.
  3209      */
  3210     public Type lub(Type t1, Type t2) {
  3211         return lub(List.of(t1, t2));
  3214     /**
  3215      * Return the least upper bound (lub) of set of types.  If the lub
  3216      * does not exist return the type of null (bottom).
  3217      */
  3218     public Type lub(List<Type> ts) {
  3219         final int ARRAY_BOUND = 1;
  3220         final int CLASS_BOUND = 2;
  3221         int boundkind = 0;
  3222         for (Type t : ts) {
  3223             switch (t.tag) {
  3224             case CLASS:
  3225                 boundkind |= CLASS_BOUND;
  3226                 break;
  3227             case ARRAY:
  3228                 boundkind |= ARRAY_BOUND;
  3229                 break;
  3230             case  TYPEVAR:
  3231                 do {
  3232                     t = t.getUpperBound();
  3233                 } while (t.tag == TYPEVAR);
  3234                 if (t.tag == ARRAY) {
  3235                     boundkind |= ARRAY_BOUND;
  3236                 } else {
  3237                     boundkind |= CLASS_BOUND;
  3239                 break;
  3240             default:
  3241                 if (t.isPrimitive())
  3242                     return syms.errType;
  3245         switch (boundkind) {
  3246         case 0:
  3247             return syms.botType;
  3249         case ARRAY_BOUND:
  3250             // calculate lub(A[], B[])
  3251             List<Type> elements = Type.map(ts, elemTypeFun);
  3252             for (Type t : elements) {
  3253                 if (t.isPrimitive()) {
  3254                     // if a primitive type is found, then return
  3255                     // arraySuperType unless all the types are the
  3256                     // same
  3257                     Type first = ts.head;
  3258                     for (Type s : ts.tail) {
  3259                         if (!isSameType(first, s)) {
  3260                              // lub(int[], B[]) is Cloneable & Serializable
  3261                             return arraySuperType();
  3264                     // all the array types are the same, return one
  3265                     // lub(int[], int[]) is int[]
  3266                     return first;
  3269             // lub(A[], B[]) is lub(A, B)[]
  3270             return new ArrayType(lub(elements), syms.arrayClass);
  3272         case CLASS_BOUND:
  3273             // calculate lub(A, B)
  3274             while (ts.head.tag != CLASS && ts.head.tag != TYPEVAR)
  3275                 ts = ts.tail;
  3276             Assert.check(!ts.isEmpty());
  3277             //step 1 - compute erased candidate set (EC)
  3278             List<Type> cl = erasedSupertypes(ts.head);
  3279             for (Type t : ts.tail) {
  3280                 if (t.tag == CLASS || t.tag == TYPEVAR)
  3281                     cl = intersect(cl, erasedSupertypes(t));
  3283             //step 2 - compute minimal erased candidate set (MEC)
  3284             List<Type> mec = closureMin(cl);
  3285             //step 3 - for each element G in MEC, compute lci(Inv(G))
  3286             List<Type> candidates = List.nil();
  3287             for (Type erasedSupertype : mec) {
  3288                 List<Type> lci = List.of(asSuper(ts.head, erasedSupertype.tsym));
  3289                 for (Type t : ts) {
  3290                     lci = intersect(lci, List.of(asSuper(t, erasedSupertype.tsym)));
  3292                 candidates = candidates.appendList(lci);
  3294             //step 4 - let MEC be { G1, G2 ... Gn }, then we have that
  3295             //lub = lci(Inv(G1)) & lci(Inv(G2)) & ... & lci(Inv(Gn))
  3296             return compoundMin(candidates);
  3298         default:
  3299             // calculate lub(A, B[])
  3300             List<Type> classes = List.of(arraySuperType());
  3301             for (Type t : ts) {
  3302                 if (t.tag != ARRAY) // Filter out any arrays
  3303                     classes = classes.prepend(t);
  3305             // lub(A, B[]) is lub(A, arraySuperType)
  3306             return lub(classes);
  3309     // where
  3310         List<Type> erasedSupertypes(Type t) {
  3311             ListBuffer<Type> buf = lb();
  3312             for (Type sup : closure(t)) {
  3313                 if (sup.tag == TYPEVAR) {
  3314                     buf.append(sup);
  3315                 } else {
  3316                     buf.append(erasure(sup));
  3319             return buf.toList();
  3322         private Type arraySuperType = null;
  3323         private Type arraySuperType() {
  3324             // initialized lazily to avoid problems during compiler startup
  3325             if (arraySuperType == null) {
  3326                 synchronized (this) {
  3327                     if (arraySuperType == null) {
  3328                         // JLS 10.8: all arrays implement Cloneable and Serializable.
  3329                         arraySuperType = makeCompoundType(List.of(syms.serializableType,
  3330                                                                   syms.cloneableType),
  3331                                                           syms.objectType);
  3335             return arraySuperType;
  3337     // </editor-fold>
  3339     // <editor-fold defaultstate="collapsed" desc="Greatest lower bound">
  3340     public Type glb(List<Type> ts) {
  3341         Type t1 = ts.head;
  3342         for (Type t2 : ts.tail) {
  3343             if (t1.isErroneous())
  3344                 return t1;
  3345             t1 = glb(t1, t2);
  3347         return t1;
  3349     //where
  3350     public Type glb(Type t, Type s) {
  3351         if (s == null)
  3352             return t;
  3353         else if (t.isPrimitive() || s.isPrimitive())
  3354             return syms.errType;
  3355         else if (isSubtypeNoCapture(t, s))
  3356             return t;
  3357         else if (isSubtypeNoCapture(s, t))
  3358             return s;
  3360         List<Type> closure = union(closure(t), closure(s));
  3361         List<Type> bounds = closureMin(closure);
  3363         if (bounds.isEmpty()) {             // length == 0
  3364             return syms.objectType;
  3365         } else if (bounds.tail.isEmpty()) { // length == 1
  3366             return bounds.head;
  3367         } else {                            // length > 1
  3368             int classCount = 0;
  3369             for (Type bound : bounds)
  3370                 if (!bound.isInterface())
  3371                     classCount++;
  3372             if (classCount > 1)
  3373                 return createErrorType(t);
  3375         return makeCompoundType(bounds);
  3377     // </editor-fold>
  3379     // <editor-fold defaultstate="collapsed" desc="hashCode">
  3380     /**
  3381      * Compute a hash code on a type.
  3382      */
  3383     public static int hashCode(Type t) {
  3384         return hashCode.visit(t);
  3386     // where
  3387         private static final UnaryVisitor<Integer> hashCode = new UnaryVisitor<Integer>() {
  3389             public Integer visitType(Type t, Void ignored) {
  3390                 return t.tag.ordinal();
  3393             @Override
  3394             public Integer visitClassType(ClassType t, Void ignored) {
  3395                 int result = visit(t.getEnclosingType());
  3396                 result *= 127;
  3397                 result += t.tsym.flatName().hashCode();
  3398                 for (Type s : t.getTypeArguments()) {
  3399                     result *= 127;
  3400                     result += visit(s);
  3402                 return result;
  3405             @Override
  3406             public Integer visitWildcardType(WildcardType t, Void ignored) {
  3407                 int result = t.kind.hashCode();
  3408                 if (t.type != null) {
  3409                     result *= 127;
  3410                     result += visit(t.type);
  3412                 return result;
  3415             @Override
  3416             public Integer visitArrayType(ArrayType t, Void ignored) {
  3417                 return visit(t.elemtype) + 12;
  3420             @Override
  3421             public Integer visitTypeVar(TypeVar t, Void ignored) {
  3422                 return System.identityHashCode(t.tsym);
  3425             @Override
  3426             public Integer visitUndetVar(UndetVar t, Void ignored) {
  3427                 return System.identityHashCode(t);
  3430             @Override
  3431             public Integer visitErrorType(ErrorType t, Void ignored) {
  3432                 return 0;
  3434         };
  3435     // </editor-fold>
  3437     // <editor-fold defaultstate="collapsed" desc="Return-Type-Substitutable">
  3438     /**
  3439      * Does t have a result that is a subtype of the result type of s,
  3440      * suitable for covariant returns?  It is assumed that both types
  3441      * are (possibly polymorphic) method types.  Monomorphic method
  3442      * types are handled in the obvious way.  Polymorphic method types
  3443      * require renaming all type variables of one to corresponding
  3444      * type variables in the other, where correspondence is by
  3445      * position in the type parameter list. */
  3446     public boolean resultSubtype(Type t, Type s, Warner warner) {
  3447         List<Type> tvars = t.getTypeArguments();
  3448         List<Type> svars = s.getTypeArguments();
  3449         Type tres = t.getReturnType();
  3450         Type sres = subst(s.getReturnType(), svars, tvars);
  3451         return covariantReturnType(tres, sres, warner);
  3454     /**
  3455      * Return-Type-Substitutable.
  3456      * @jls section 8.4.5
  3457      */
  3458     public boolean returnTypeSubstitutable(Type r1, Type r2) {
  3459         if (hasSameArgs(r1, r2))
  3460             return resultSubtype(r1, r2, noWarnings);
  3461         else
  3462             return covariantReturnType(r1.getReturnType(),
  3463                                        erasure(r2.getReturnType()),
  3464                                        noWarnings);
  3467     public boolean returnTypeSubstitutable(Type r1,
  3468                                            Type r2, Type r2res,
  3469                                            Warner warner) {
  3470         if (isSameType(r1.getReturnType(), r2res))
  3471             return true;
  3472         if (r1.getReturnType().isPrimitive() || r2res.isPrimitive())
  3473             return false;
  3475         if (hasSameArgs(r1, r2))
  3476             return covariantReturnType(r1.getReturnType(), r2res, warner);
  3477         if (!allowCovariantReturns)
  3478             return false;
  3479         if (isSubtypeUnchecked(r1.getReturnType(), r2res, warner))
  3480             return true;
  3481         if (!isSubtype(r1.getReturnType(), erasure(r2res)))
  3482             return false;
  3483         warner.warn(LintCategory.UNCHECKED);
  3484         return true;
  3487     /**
  3488      * Is t an appropriate return type in an overrider for a
  3489      * method that returns s?
  3490      */
  3491     public boolean covariantReturnType(Type t, Type s, Warner warner) {
  3492         return
  3493             isSameType(t, s) ||
  3494             allowCovariantReturns &&
  3495             !t.isPrimitive() &&
  3496             !s.isPrimitive() &&
  3497             isAssignable(t, s, warner);
  3499     // </editor-fold>
  3501     // <editor-fold defaultstate="collapsed" desc="Box/unbox support">
  3502     /**
  3503      * Return the class that boxes the given primitive.
  3504      */
  3505     public ClassSymbol boxedClass(Type t) {
  3506         return reader.enterClass(syms.boxedName[t.tag.ordinal()]);
  3509     /**
  3510      * Return the boxed type if 't' is primitive, otherwise return 't' itself.
  3511      */
  3512     public Type boxedTypeOrType(Type t) {
  3513         return t.isPrimitive() ?
  3514             boxedClass(t).type :
  3515             t;
  3518     /**
  3519      * Return the primitive type corresponding to a boxed type.
  3520      */
  3521     public Type unboxedType(Type t) {
  3522         if (allowBoxing) {
  3523             for (int i=0; i<syms.boxedName.length; i++) {
  3524                 Name box = syms.boxedName[i];
  3525                 if (box != null &&
  3526                     asSuper(t, reader.enterClass(box)) != null)
  3527                     return syms.typeOfTag[i];
  3530         return Type.noType;
  3533     /**
  3534      * Return the unboxed type if 't' is a boxed class, otherwise return 't' itself.
  3535      */
  3536     public Type unboxedTypeOrType(Type t) {
  3537         Type unboxedType = unboxedType(t);
  3538         return unboxedType.tag == NONE ? t : unboxedType;
  3540     // </editor-fold>
  3542     // <editor-fold defaultstate="collapsed" desc="Capture conversion">
  3543     /*
  3544      * JLS 5.1.10 Capture Conversion:
  3546      * Let G name a generic type declaration with n formal type
  3547      * parameters A1 ... An with corresponding bounds U1 ... Un. There
  3548      * exists a capture conversion from G<T1 ... Tn> to G<S1 ... Sn>,
  3549      * where, for 1 <= i <= n:
  3551      * + If Ti is a wildcard type argument (4.5.1) of the form ? then
  3552      *   Si is a fresh type variable whose upper bound is
  3553      *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is the null
  3554      *   type.
  3556      * + If Ti is a wildcard type argument of the form ? extends Bi,
  3557      *   then Si is a fresh type variable whose upper bound is
  3558      *   glb(Bi, Ui[A1 := S1, ..., An := Sn]) and whose lower bound is
  3559      *   the null type, where glb(V1,... ,Vm) is V1 & ... & Vm. It is
  3560      *   a compile-time error if for any two classes (not interfaces)
  3561      *   Vi and Vj,Vi is not a subclass of Vj or vice versa.
  3563      * + If Ti is a wildcard type argument of the form ? super Bi,
  3564      *   then Si is a fresh type variable whose upper bound is
  3565      *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is Bi.
  3567      * + Otherwise, Si = Ti.
  3569      * Capture conversion on any type other than a parameterized type
  3570      * (4.5) acts as an identity conversion (5.1.1). Capture
  3571      * conversions never require a special action at run time and
  3572      * therefore never throw an exception at run time.
  3574      * Capture conversion is not applied recursively.
  3575      */
  3576     /**
  3577      * Capture conversion as specified by the JLS.
  3578      */
  3580     public List<Type> capture(List<Type> ts) {
  3581         List<Type> buf = List.nil();
  3582         for (Type t : ts) {
  3583             buf = buf.prepend(capture(t));
  3585         return buf.reverse();
  3587     public Type capture(Type t) {
  3588         if (t.tag != CLASS)
  3589             return t;
  3590         if (t.getEnclosingType() != Type.noType) {
  3591             Type capturedEncl = capture(t.getEnclosingType());
  3592             if (capturedEncl != t.getEnclosingType()) {
  3593                 Type type1 = memberType(capturedEncl, t.tsym);
  3594                 t = subst(type1, t.tsym.type.getTypeArguments(), t.getTypeArguments());
  3597         ClassType cls = (ClassType)t;
  3598         if (cls.isRaw() || !cls.isParameterized())
  3599             return cls;
  3601         ClassType G = (ClassType)cls.asElement().asType();
  3602         List<Type> A = G.getTypeArguments();
  3603         List<Type> T = cls.getTypeArguments();
  3604         List<Type> S = freshTypeVariables(T);
  3606         List<Type> currentA = A;
  3607         List<Type> currentT = T;
  3608         List<Type> currentS = S;
  3609         boolean captured = false;
  3610         while (!currentA.isEmpty() &&
  3611                !currentT.isEmpty() &&
  3612                !currentS.isEmpty()) {
  3613             if (currentS.head != currentT.head) {
  3614                 captured = true;
  3615                 WildcardType Ti = (WildcardType)currentT.head;
  3616                 Type Ui = currentA.head.getUpperBound();
  3617                 CapturedType Si = (CapturedType)currentS.head;
  3618                 if (Ui == null)
  3619                     Ui = syms.objectType;
  3620                 switch (Ti.kind) {
  3621                 case UNBOUND:
  3622                     Si.bound = subst(Ui, A, S);
  3623                     Si.lower = syms.botType;
  3624                     break;
  3625                 case EXTENDS:
  3626                     Si.bound = glb(Ti.getExtendsBound(), subst(Ui, A, S));
  3627                     Si.lower = syms.botType;
  3628                     break;
  3629                 case SUPER:
  3630                     Si.bound = subst(Ui, A, S);
  3631                     Si.lower = Ti.getSuperBound();
  3632                     break;
  3634                 if (Si.bound == Si.lower)
  3635                     currentS.head = Si.bound;
  3637             currentA = currentA.tail;
  3638             currentT = currentT.tail;
  3639             currentS = currentS.tail;
  3641         if (!currentA.isEmpty() || !currentT.isEmpty() || !currentS.isEmpty())
  3642             return erasure(t); // some "rare" type involved
  3644         if (captured)
  3645             return new ClassType(cls.getEnclosingType(), S, cls.tsym);
  3646         else
  3647             return t;
  3649     // where
  3650         public List<Type> freshTypeVariables(List<Type> types) {
  3651             ListBuffer<Type> result = lb();
  3652             for (Type t : types) {
  3653                 if (t.tag == WILDCARD) {
  3654                     Type bound = ((WildcardType)t).getExtendsBound();
  3655                     if (bound == null)
  3656                         bound = syms.objectType;
  3657                     result.append(new CapturedType(capturedName,
  3658                                                    syms.noSymbol,
  3659                                                    bound,
  3660                                                    syms.botType,
  3661                                                    (WildcardType)t));
  3662                 } else {
  3663                     result.append(t);
  3666             return result.toList();
  3668     // </editor-fold>
  3670     // <editor-fold defaultstate="collapsed" desc="Internal utility methods">
  3671     private List<Type> upperBounds(List<Type> ss) {
  3672         if (ss.isEmpty()) return ss;
  3673         Type head = upperBound(ss.head);
  3674         List<Type> tail = upperBounds(ss.tail);
  3675         if (head != ss.head || tail != ss.tail)
  3676             return tail.prepend(head);
  3677         else
  3678             return ss;
  3681     private boolean sideCast(Type from, Type to, Warner warn) {
  3682         // We are casting from type $from$ to type $to$, which are
  3683         // non-final unrelated types.  This method
  3684         // tries to reject a cast by transferring type parameters
  3685         // from $to$ to $from$ by common superinterfaces.
  3686         boolean reverse = false;
  3687         Type target = to;
  3688         if ((to.tsym.flags() & INTERFACE) == 0) {
  3689             Assert.check((from.tsym.flags() & INTERFACE) != 0);
  3690             reverse = true;
  3691             to = from;
  3692             from = target;
  3694         List<Type> commonSupers = superClosure(to, erasure(from));
  3695         boolean giveWarning = commonSupers.isEmpty();
  3696         // The arguments to the supers could be unified here to
  3697         // get a more accurate analysis
  3698         while (commonSupers.nonEmpty()) {
  3699             Type t1 = asSuper(from, commonSupers.head.tsym);
  3700             Type t2 = commonSupers.head; // same as asSuper(to, commonSupers.head.tsym);
  3701             if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
  3702                 return false;
  3703             giveWarning = giveWarning || (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2));
  3704             commonSupers = commonSupers.tail;
  3706         if (giveWarning && !isReifiable(reverse ? from : to))
  3707             warn.warn(LintCategory.UNCHECKED);
  3708         if (!allowCovariantReturns)
  3709             // reject if there is a common method signature with
  3710             // incompatible return types.
  3711             chk.checkCompatibleAbstracts(warn.pos(), from, to);
  3712         return true;
  3715     private boolean sideCastFinal(Type from, Type to, Warner warn) {
  3716         // We are casting from type $from$ to type $to$, which are
  3717         // unrelated types one of which is final and the other of
  3718         // which is an interface.  This method
  3719         // tries to reject a cast by transferring type parameters
  3720         // from the final class to the interface.
  3721         boolean reverse = false;
  3722         Type target = to;
  3723         if ((to.tsym.flags() & INTERFACE) == 0) {
  3724             Assert.check((from.tsym.flags() & INTERFACE) != 0);
  3725             reverse = true;
  3726             to = from;
  3727             from = target;
  3729         Assert.check((from.tsym.flags() & FINAL) != 0);
  3730         Type t1 = asSuper(from, to.tsym);
  3731         if (t1 == null) return false;
  3732         Type t2 = to;
  3733         if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
  3734             return false;
  3735         if (!allowCovariantReturns)
  3736             // reject if there is a common method signature with
  3737             // incompatible return types.
  3738             chk.checkCompatibleAbstracts(warn.pos(), from, to);
  3739         if (!isReifiable(target) &&
  3740             (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2)))
  3741             warn.warn(LintCategory.UNCHECKED);
  3742         return true;
  3745     private boolean giveWarning(Type from, Type to) {
  3746         Type subFrom = asSub(from, to.tsym);
  3747         return to.isParameterized() &&
  3748                 (!(isUnbounded(to) ||
  3749                 isSubtype(from, to) ||
  3750                 ((subFrom != null) && containsType(to.allparams(), subFrom.allparams()))));
  3753     private List<Type> superClosure(Type t, Type s) {
  3754         List<Type> cl = List.nil();
  3755         for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
  3756             if (isSubtype(s, erasure(l.head))) {
  3757                 cl = insert(cl, l.head);
  3758             } else {
  3759                 cl = union(cl, superClosure(l.head, s));
  3762         return cl;
  3765     private boolean containsTypeEquivalent(Type t, Type s) {
  3766         return
  3767             isSameType(t, s) || // shortcut
  3768             containsType(t, s) && containsType(s, t);
  3771     // <editor-fold defaultstate="collapsed" desc="adapt">
  3772     /**
  3773      * Adapt a type by computing a substitution which maps a source
  3774      * type to a target type.
  3776      * @param source    the source type
  3777      * @param target    the target type
  3778      * @param from      the type variables of the computed substitution
  3779      * @param to        the types of the computed substitution.
  3780      */
  3781     public void adapt(Type source,
  3782                        Type target,
  3783                        ListBuffer<Type> from,
  3784                        ListBuffer<Type> to) throws AdaptFailure {
  3785         new Adapter(from, to).adapt(source, target);
  3788     class Adapter extends SimpleVisitor<Void, Type> {
  3790         ListBuffer<Type> from;
  3791         ListBuffer<Type> to;
  3792         Map<Symbol,Type> mapping;
  3794         Adapter(ListBuffer<Type> from, ListBuffer<Type> to) {
  3795             this.from = from;
  3796             this.to = to;
  3797             mapping = new HashMap<Symbol,Type>();
  3800         public void adapt(Type source, Type target) throws AdaptFailure {
  3801             visit(source, target);
  3802             List<Type> fromList = from.toList();
  3803             List<Type> toList = to.toList();
  3804             while (!fromList.isEmpty()) {
  3805                 Type val = mapping.get(fromList.head.tsym);
  3806                 if (toList.head != val)
  3807                     toList.head = val;
  3808                 fromList = fromList.tail;
  3809                 toList = toList.tail;
  3813         @Override
  3814         public Void visitClassType(ClassType source, Type target) throws AdaptFailure {
  3815             if (target.tag == CLASS)
  3816                 adaptRecursive(source.allparams(), target.allparams());
  3817             return null;
  3820         @Override
  3821         public Void visitArrayType(ArrayType source, Type target) throws AdaptFailure {
  3822             if (target.tag == ARRAY)
  3823                 adaptRecursive(elemtype(source), elemtype(target));
  3824             return null;
  3827         @Override
  3828         public Void visitWildcardType(WildcardType source, Type target) throws AdaptFailure {
  3829             if (source.isExtendsBound())
  3830                 adaptRecursive(upperBound(source), upperBound(target));
  3831             else if (source.isSuperBound())
  3832                 adaptRecursive(lowerBound(source), lowerBound(target));
  3833             return null;
  3836         @Override
  3837         public Void visitTypeVar(TypeVar source, Type target) throws AdaptFailure {
  3838             // Check to see if there is
  3839             // already a mapping for $source$, in which case
  3840             // the old mapping will be merged with the new
  3841             Type val = mapping.get(source.tsym);
  3842             if (val != null) {
  3843                 if (val.isSuperBound() && target.isSuperBound()) {
  3844                     val = isSubtype(lowerBound(val), lowerBound(target))
  3845                         ? target : val;
  3846                 } else if (val.isExtendsBound() && target.isExtendsBound()) {
  3847                     val = isSubtype(upperBound(val), upperBound(target))
  3848                         ? val : target;
  3849                 } else if (!isSameType(val, target)) {
  3850                     throw new AdaptFailure();
  3852             } else {
  3853                 val = target;
  3854                 from.append(source);
  3855                 to.append(target);
  3857             mapping.put(source.tsym, val);
  3858             return null;
  3861         @Override
  3862         public Void visitType(Type source, Type target) {
  3863             return null;
  3866         private Set<TypePair> cache = new HashSet<TypePair>();
  3868         private void adaptRecursive(Type source, Type target) {
  3869             TypePair pair = new TypePair(source, target);
  3870             if (cache.add(pair)) {
  3871                 try {
  3872                     visit(source, target);
  3873                 } finally {
  3874                     cache.remove(pair);
  3879         private void adaptRecursive(List<Type> source, List<Type> target) {
  3880             if (source.length() == target.length()) {
  3881                 while (source.nonEmpty()) {
  3882                     adaptRecursive(source.head, target.head);
  3883                     source = source.tail;
  3884                     target = target.tail;
  3890     public static class AdaptFailure extends RuntimeException {
  3891         static final long serialVersionUID = -7490231548272701566L;
  3894     private void adaptSelf(Type t,
  3895                            ListBuffer<Type> from,
  3896                            ListBuffer<Type> to) {
  3897         try {
  3898             //if (t.tsym.type != t)
  3899                 adapt(t.tsym.type, t, from, to);
  3900         } catch (AdaptFailure ex) {
  3901             // Adapt should never fail calculating a mapping from
  3902             // t.tsym.type to t as there can be no merge problem.
  3903             throw new AssertionError(ex);
  3906     // </editor-fold>
  3908     /**
  3909      * Rewrite all type variables (universal quantifiers) in the given
  3910      * type to wildcards (existential quantifiers).  This is used to
  3911      * determine if a cast is allowed.  For example, if high is true
  3912      * and {@code T <: Number}, then {@code List<T>} is rewritten to
  3913      * {@code List<?  extends Number>}.  Since {@code List<Integer> <:
  3914      * List<? extends Number>} a {@code List<T>} can be cast to {@code
  3915      * List<Integer>} with a warning.
  3916      * @param t a type
  3917      * @param high if true return an upper bound; otherwise a lower
  3918      * bound
  3919      * @param rewriteTypeVars only rewrite captured wildcards if false;
  3920      * otherwise rewrite all type variables
  3921      * @return the type rewritten with wildcards (existential
  3922      * quantifiers) only
  3923      */
  3924     private Type rewriteQuantifiers(Type t, boolean high, boolean rewriteTypeVars) {
  3925         return new Rewriter(high, rewriteTypeVars).visit(t);
  3928     class Rewriter extends UnaryVisitor<Type> {
  3930         boolean high;
  3931         boolean rewriteTypeVars;
  3933         Rewriter(boolean high, boolean rewriteTypeVars) {
  3934             this.high = high;
  3935             this.rewriteTypeVars = rewriteTypeVars;
  3938         @Override
  3939         public Type visitClassType(ClassType t, Void s) {
  3940             ListBuffer<Type> rewritten = new ListBuffer<Type>();
  3941             boolean changed = false;
  3942             for (Type arg : t.allparams()) {
  3943                 Type bound = visit(arg);
  3944                 if (arg != bound) {
  3945                     changed = true;
  3947                 rewritten.append(bound);
  3949             if (changed)
  3950                 return subst(t.tsym.type,
  3951                         t.tsym.type.allparams(),
  3952                         rewritten.toList());
  3953             else
  3954                 return t;
  3957         public Type visitType(Type t, Void s) {
  3958             return high ? upperBound(t) : lowerBound(t);
  3961         @Override
  3962         public Type visitCapturedType(CapturedType t, Void s) {
  3963             Type w_bound = t.wildcard.type;
  3964             Type bound = w_bound.contains(t) ?
  3965                         erasure(w_bound) :
  3966                         visit(w_bound);
  3967             return rewriteAsWildcardType(visit(bound), t.wildcard.bound, t.wildcard.kind);
  3970         @Override
  3971         public Type visitTypeVar(TypeVar t, Void s) {
  3972             if (rewriteTypeVars) {
  3973                 Type bound = t.bound.contains(t) ?
  3974                         erasure(t.bound) :
  3975                         visit(t.bound);
  3976                 return rewriteAsWildcardType(bound, t, EXTENDS);
  3977             } else {
  3978                 return t;
  3982         @Override
  3983         public Type visitWildcardType(WildcardType t, Void s) {
  3984             Type bound2 = visit(t.type);
  3985             return t.type == bound2 ? t : rewriteAsWildcardType(bound2, t.bound, t.kind);
  3988         private Type rewriteAsWildcardType(Type bound, TypeVar formal, BoundKind bk) {
  3989             switch (bk) {
  3990                case EXTENDS: return high ?
  3991                        makeExtendsWildcard(B(bound), formal) :
  3992                        makeExtendsWildcard(syms.objectType, formal);
  3993                case SUPER: return high ?
  3994                        makeSuperWildcard(syms.botType, formal) :
  3995                        makeSuperWildcard(B(bound), formal);
  3996                case UNBOUND: return makeExtendsWildcard(syms.objectType, formal);
  3997                default:
  3998                    Assert.error("Invalid bound kind " + bk);
  3999                    return null;
  4003         Type B(Type t) {
  4004             while (t.tag == WILDCARD) {
  4005                 WildcardType w = (WildcardType)t;
  4006                 t = high ?
  4007                     w.getExtendsBound() :
  4008                     w.getSuperBound();
  4009                 if (t == null) {
  4010                     t = high ? syms.objectType : syms.botType;
  4013             return t;
  4018     /**
  4019      * Create a wildcard with the given upper (extends) bound; create
  4020      * an unbounded wildcard if bound is Object.
  4022      * @param bound the upper bound
  4023      * @param formal the formal type parameter that will be
  4024      * substituted by the wildcard
  4025      */
  4026     private WildcardType makeExtendsWildcard(Type bound, TypeVar formal) {
  4027         if (bound == syms.objectType) {
  4028             return new WildcardType(syms.objectType,
  4029                                     BoundKind.UNBOUND,
  4030                                     syms.boundClass,
  4031                                     formal);
  4032         } else {
  4033             return new WildcardType(bound,
  4034                                     BoundKind.EXTENDS,
  4035                                     syms.boundClass,
  4036                                     formal);
  4040     /**
  4041      * Create a wildcard with the given lower (super) bound; create an
  4042      * unbounded wildcard if bound is bottom (type of {@code null}).
  4044      * @param bound the lower bound
  4045      * @param formal the formal type parameter that will be
  4046      * substituted by the wildcard
  4047      */
  4048     private WildcardType makeSuperWildcard(Type bound, TypeVar formal) {
  4049         if (bound.tag == BOT) {
  4050             return new WildcardType(syms.objectType,
  4051                                     BoundKind.UNBOUND,
  4052                                     syms.boundClass,
  4053                                     formal);
  4054         } else {
  4055             return new WildcardType(bound,
  4056                                     BoundKind.SUPER,
  4057                                     syms.boundClass,
  4058                                     formal);
  4062     /**
  4063      * A wrapper for a type that allows use in sets.
  4064      */
  4065     class SingletonType {
  4066         final Type t;
  4067         SingletonType(Type t) {
  4068             this.t = t;
  4070         public int hashCode() {
  4071             return Types.hashCode(t);
  4073         public boolean equals(Object obj) {
  4074             return (obj instanceof SingletonType) &&
  4075                 isSameType(t, ((SingletonType)obj).t);
  4077         public String toString() {
  4078             return t.toString();
  4081     // </editor-fold>
  4083     // <editor-fold defaultstate="collapsed" desc="Visitors">
  4084     /**
  4085      * A default visitor for types.  All visitor methods except
  4086      * visitType are implemented by delegating to visitType.  Concrete
  4087      * subclasses must provide an implementation of visitType and can
  4088      * override other methods as needed.
  4090      * @param <R> the return type of the operation implemented by this
  4091      * visitor; use Void if no return type is needed.
  4092      * @param <S> the type of the second argument (the first being the
  4093      * type itself) of the operation implemented by this visitor; use
  4094      * Void if a second argument is not needed.
  4095      */
  4096     public static abstract class DefaultTypeVisitor<R,S> implements Type.Visitor<R,S> {
  4097         final public R visit(Type t, S s)               { return t.accept(this, s); }
  4098         public R visitClassType(ClassType t, S s)       { return visitType(t, s); }
  4099         public R visitWildcardType(WildcardType t, S s) { return visitType(t, s); }
  4100         public R visitArrayType(ArrayType t, S s)       { return visitType(t, s); }
  4101         public R visitMethodType(MethodType t, S s)     { return visitType(t, s); }
  4102         public R visitPackageType(PackageType t, S s)   { return visitType(t, s); }
  4103         public R visitTypeVar(TypeVar t, S s)           { return visitType(t, s); }
  4104         public R visitCapturedType(CapturedType t, S s) { return visitType(t, s); }
  4105         public R visitForAll(ForAll t, S s)             { return visitType(t, s); }
  4106         public R visitUndetVar(UndetVar t, S s)         { return visitType(t, s); }
  4107         public R visitErrorType(ErrorType t, S s)       { return visitType(t, s); }
  4110     /**
  4111      * A default visitor for symbols.  All visitor methods except
  4112      * visitSymbol are implemented by delegating to visitSymbol.  Concrete
  4113      * subclasses must provide an implementation of visitSymbol and can
  4114      * override other methods as needed.
  4116      * @param <R> the return type of the operation implemented by this
  4117      * visitor; use Void if no return type is needed.
  4118      * @param <S> the type of the second argument (the first being the
  4119      * symbol itself) of the operation implemented by this visitor; use
  4120      * Void if a second argument is not needed.
  4121      */
  4122     public static abstract class DefaultSymbolVisitor<R,S> implements Symbol.Visitor<R,S> {
  4123         final public R visit(Symbol s, S arg)                   { return s.accept(this, arg); }
  4124         public R visitClassSymbol(ClassSymbol s, S arg)         { return visitSymbol(s, arg); }
  4125         public R visitMethodSymbol(MethodSymbol s, S arg)       { return visitSymbol(s, arg); }
  4126         public R visitOperatorSymbol(OperatorSymbol s, S arg)   { return visitSymbol(s, arg); }
  4127         public R visitPackageSymbol(PackageSymbol s, S arg)     { return visitSymbol(s, arg); }
  4128         public R visitTypeSymbol(TypeSymbol s, S arg)           { return visitSymbol(s, arg); }
  4129         public R visitVarSymbol(VarSymbol s, S arg)             { return visitSymbol(s, arg); }
  4132     /**
  4133      * A <em>simple</em> visitor for types.  This visitor is simple as
  4134      * captured wildcards, for-all types (generic methods), and
  4135      * undetermined type variables (part of inference) are hidden.
  4136      * Captured wildcards are hidden by treating them as type
  4137      * variables and the rest are hidden by visiting their qtypes.
  4139      * @param <R> the return type of the operation implemented by this
  4140      * visitor; use Void if no return type is needed.
  4141      * @param <S> the type of the second argument (the first being the
  4142      * type itself) of the operation implemented by this visitor; use
  4143      * Void if a second argument is not needed.
  4144      */
  4145     public static abstract class SimpleVisitor<R,S> extends DefaultTypeVisitor<R,S> {
  4146         @Override
  4147         public R visitCapturedType(CapturedType t, S s) {
  4148             return visitTypeVar(t, s);
  4150         @Override
  4151         public R visitForAll(ForAll t, S s) {
  4152             return visit(t.qtype, s);
  4154         @Override
  4155         public R visitUndetVar(UndetVar t, S s) {
  4156             return visit(t.qtype, s);
  4160     /**
  4161      * A plain relation on types.  That is a 2-ary function on the
  4162      * form Type&nbsp;&times;&nbsp;Type&nbsp;&rarr;&nbsp;Boolean.
  4163      * <!-- In plain text: Type x Type -> Boolean -->
  4164      */
  4165     public static abstract class TypeRelation extends SimpleVisitor<Boolean,Type> {}
  4167     /**
  4168      * A convenience visitor for implementing operations that only
  4169      * require one argument (the type itself), that is, unary
  4170      * operations.
  4172      * @param <R> the return type of the operation implemented by this
  4173      * visitor; use Void if no return type is needed.
  4174      */
  4175     public static abstract class UnaryVisitor<R> extends SimpleVisitor<R,Void> {
  4176         final public R visit(Type t) { return t.accept(this, null); }
  4179     /**
  4180      * A visitor for implementing a mapping from types to types.  The
  4181      * default behavior of this class is to implement the identity
  4182      * mapping (mapping a type to itself).  This can be overridden in
  4183      * subclasses.
  4185      * @param <S> the type of the second argument (the first being the
  4186      * type itself) of this mapping; use Void if a second argument is
  4187      * not needed.
  4188      */
  4189     public static class MapVisitor<S> extends DefaultTypeVisitor<Type,S> {
  4190         final public Type visit(Type t) { return t.accept(this, null); }
  4191         public Type visitType(Type t, S s) { return t; }
  4193     // </editor-fold>
  4196     // <editor-fold defaultstate="collapsed" desc="Annotation support">
  4198     public RetentionPolicy getRetention(Attribute.Compound a) {
  4199         return getRetention(a.type.tsym);
  4202     public RetentionPolicy getRetention(Symbol sym) {
  4203         RetentionPolicy vis = RetentionPolicy.CLASS; // the default
  4204         Attribute.Compound c = sym.attribute(syms.retentionType.tsym);
  4205         if (c != null) {
  4206             Attribute value = c.member(names.value);
  4207             if (value != null && value instanceof Attribute.Enum) {
  4208                 Name levelName = ((Attribute.Enum)value).value.name;
  4209                 if (levelName == names.SOURCE) vis = RetentionPolicy.SOURCE;
  4210                 else if (levelName == names.CLASS) vis = RetentionPolicy.CLASS;
  4211                 else if (levelName == names.RUNTIME) vis = RetentionPolicy.RUNTIME;
  4212                 else ;// /* fail soft */ throw new AssertionError(levelName);
  4215         return vis;
  4217     // </editor-fold>

mercurial