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

Wed, 23 Jan 2013 13:27:24 -0800

author
jjg
date
Wed, 23 Jan 2013 13:27:24 -0800
changeset 1521
71f35e4b93a5
parent 1510
7873d37f5b37
child 1550
1df20330f6bd
permissions
-rw-r--r--

8006775: JSR 308: Compiler changes in JDK8
Reviewed-by: jjg
Contributed-by: mernst@cs.washington.edu, wmdietl@cs.washington.edu, mpapi@csail.mit.edu, mahmood@notnoop.com

     1 /*
     2  * Copyright (c) 2003, 2013, 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 javax.lang.model.type.TypeKind;
    39 import com.sun.tools.javac.code.Attribute.RetentionPolicy;
    40 import com.sun.tools.javac.code.Lint.LintCategory;
    41 import com.sun.tools.javac.code.Type.UndetVar.InferenceBound;
    42 import com.sun.tools.javac.comp.Check;
    43 import com.sun.tools.javac.jvm.ClassReader;
    44 import com.sun.tools.javac.util.*;
    45 import static com.sun.tools.javac.code.BoundKind.*;
    46 import static com.sun.tools.javac.code.Flags.*;
    47 import static com.sun.tools.javac.code.Scope.*;
    48 import static com.sun.tools.javac.code.Symbol.*;
    49 import static com.sun.tools.javac.code.Type.*;
    50 import static com.sun.tools.javac.code.TypeTag.*;
    51 import static com.sun.tools.javac.util.ListBuffer.lb;
    53 /**
    54  * Utility class containing various operations on types.
    55  *
    56  * <p>Unless other names are more illustrative, the following naming
    57  * conventions should be observed in this file:
    58  *
    59  * <dl>
    60  * <dt>t</dt>
    61  * <dd>If the first argument to an operation is a type, it should be named t.</dd>
    62  * <dt>s</dt>
    63  * <dd>Similarly, if the second argument to an operation is a type, it should be named s.</dd>
    64  * <dt>ts</dt>
    65  * <dd>If an operations takes a list of types, the first should be named ts.</dd>
    66  * <dt>ss</dt>
    67  * <dd>A second list of types should be named ss.</dd>
    68  * </dl>
    69  *
    70  * <p><b>This is NOT part of any supported API.
    71  * If you write code that depends on this, you do so at your own risk.
    72  * This code and its internal interfaces are subject to change or
    73  * deletion without notice.</b>
    74  */
    75 public class Types {
    76     protected static final Context.Key<Types> typesKey =
    77         new Context.Key<Types>();
    79     final Symtab syms;
    80     final JavacMessages messages;
    81     final Names names;
    82     final boolean allowBoxing;
    83     final boolean allowCovariantReturns;
    84     final boolean allowObjectToPrimitiveCast;
    85     final boolean allowDefaultMethods;
    86     final ClassReader reader;
    87     final Check chk;
    88     JCDiagnostic.Factory diags;
    89     List<Warner> warnStack = List.nil();
    90     final Name capturedName;
    91     private final FunctionDescriptorLookupError functionDescriptorLookupError;
    93     public final Warner noWarnings;
    95     // <editor-fold defaultstate="collapsed" desc="Instantiating">
    96     public static Types instance(Context context) {
    97         Types instance = context.get(typesKey);
    98         if (instance == null)
    99             instance = new Types(context);
   100         return instance;
   101     }
   103     protected Types(Context context) {
   104         context.put(typesKey, this);
   105         syms = Symtab.instance(context);
   106         names = Names.instance(context);
   107         Source source = Source.instance(context);
   108         allowBoxing = source.allowBoxing();
   109         allowCovariantReturns = source.allowCovariantReturns();
   110         allowObjectToPrimitiveCast = source.allowObjectToPrimitiveCast();
   111         allowDefaultMethods = source.allowDefaultMethods();
   112         reader = ClassReader.instance(context);
   113         chk = Check.instance(context);
   114         capturedName = names.fromString("<captured wildcard>");
   115         messages = JavacMessages.instance(context);
   116         diags = JCDiagnostic.Factory.instance(context);
   117         functionDescriptorLookupError = new FunctionDescriptorLookupError();
   118         noWarnings = new Warner(null);
   119     }
   120     // </editor-fold>
   122     // <editor-fold defaultstate="collapsed" desc="upperBound">
   123     /**
   124      * The "rvalue conversion".<br>
   125      * The upper bound of most types is the type
   126      * itself.  Wildcards, on the other hand have upper
   127      * and lower bounds.
   128      * @param t a type
   129      * @return the upper bound of the given type
   130      */
   131     public Type upperBound(Type t) {
   132         return upperBound.visit(t);
   133     }
   134     // where
   135         private final MapVisitor<Void> upperBound = new MapVisitor<Void>() {
   137             @Override
   138             public Type visitWildcardType(WildcardType t, Void ignored) {
   139                 if (t.isSuperBound())
   140                     return t.bound == null ? syms.objectType : t.bound.bound;
   141                 else
   142                     return visit(t.type);
   143             }
   145             @Override
   146             public Type visitCapturedType(CapturedType t, Void ignored) {
   147                 return visit(t.bound);
   148             }
   149         };
   150     // </editor-fold>
   152     // <editor-fold defaultstate="collapsed" desc="lowerBound">
   153     /**
   154      * The "lvalue conversion".<br>
   155      * The lower bound of most types is the type
   156      * itself.  Wildcards, on the other hand have upper
   157      * and lower bounds.
   158      * @param t a type
   159      * @return the lower bound of the given type
   160      */
   161     public Type lowerBound(Type t) {
   162         return lowerBound.visit(t);
   163     }
   164     // where
   165         private final MapVisitor<Void> lowerBound = new MapVisitor<Void>() {
   167             @Override
   168             public Type visitWildcardType(WildcardType t, Void ignored) {
   169                 return t.isExtendsBound() ? syms.botType : visit(t.type);
   170             }
   172             @Override
   173             public Type visitCapturedType(CapturedType t, Void ignored) {
   174                 return visit(t.getLowerBound());
   175             }
   176         };
   177     // </editor-fold>
   179     // <editor-fold defaultstate="collapsed" desc="isUnbounded">
   180     /**
   181      * Checks that all the arguments to a class are unbounded
   182      * wildcards or something else that doesn't make any restrictions
   183      * on the arguments. If a class isUnbounded, a raw super- or
   184      * subclass can be cast to it without a warning.
   185      * @param t a type
   186      * @return true iff the given type is unbounded or raw
   187      */
   188     public boolean isUnbounded(Type t) {
   189         return isUnbounded.visit(t);
   190     }
   191     // where
   192         private final UnaryVisitor<Boolean> isUnbounded = new UnaryVisitor<Boolean>() {
   194             public Boolean visitType(Type t, Void ignored) {
   195                 return true;
   196             }
   198             @Override
   199             public Boolean visitClassType(ClassType t, Void ignored) {
   200                 List<Type> parms = t.tsym.type.allparams();
   201                 List<Type> args = t.allparams();
   202                 while (parms.nonEmpty()) {
   203                     WildcardType unb = new WildcardType(syms.objectType,
   204                                                         BoundKind.UNBOUND,
   205                                                         syms.boundClass,
   206                                                         (TypeVar)parms.head);
   207                     if (!containsType(args.head, unb))
   208                         return false;
   209                     parms = parms.tail;
   210                     args = args.tail;
   211                 }
   212                 return true;
   213             }
   214         };
   215     // </editor-fold>
   217     // <editor-fold defaultstate="collapsed" desc="asSub">
   218     /**
   219      * Return the least specific subtype of t that starts with symbol
   220      * sym.  If none exists, return null.  The least specific subtype
   221      * is determined as follows:
   222      *
   223      * <p>If there is exactly one parameterized instance of sym that is a
   224      * subtype of t, that parameterized instance is returned.<br>
   225      * Otherwise, if the plain type or raw type `sym' is a subtype of
   226      * type t, the type `sym' itself is returned.  Otherwise, null is
   227      * returned.
   228      */
   229     public Type asSub(Type t, Symbol sym) {
   230         return asSub.visit(t, sym);
   231     }
   232     // where
   233         private final SimpleVisitor<Type,Symbol> asSub = new SimpleVisitor<Type,Symbol>() {
   235             public Type visitType(Type t, Symbol sym) {
   236                 return null;
   237             }
   239             @Override
   240             public Type visitClassType(ClassType t, Symbol sym) {
   241                 if (t.tsym == sym)
   242                     return t;
   243                 Type base = asSuper(sym.type, t.tsym);
   244                 if (base == null)
   245                     return null;
   246                 ListBuffer<Type> from = new ListBuffer<Type>();
   247                 ListBuffer<Type> to = new ListBuffer<Type>();
   248                 try {
   249                     adapt(base, t, from, to);
   250                 } catch (AdaptFailure ex) {
   251                     return null;
   252                 }
   253                 Type res = subst(sym.type, from.toList(), to.toList());
   254                 if (!isSubtype(res, t))
   255                     return null;
   256                 ListBuffer<Type> openVars = new ListBuffer<Type>();
   257                 for (List<Type> l = sym.type.allparams();
   258                      l.nonEmpty(); l = l.tail)
   259                     if (res.contains(l.head) && !t.contains(l.head))
   260                         openVars.append(l.head);
   261                 if (openVars.nonEmpty()) {
   262                     if (t.isRaw()) {
   263                         // The subtype of a raw type is raw
   264                         res = erasure(res);
   265                     } else {
   266                         // Unbound type arguments default to ?
   267                         List<Type> opens = openVars.toList();
   268                         ListBuffer<Type> qs = new ListBuffer<Type>();
   269                         for (List<Type> iter = opens; iter.nonEmpty(); iter = iter.tail) {
   270                             qs.append(new WildcardType(syms.objectType, BoundKind.UNBOUND, syms.boundClass, (TypeVar) iter.head));
   271                         }
   272                         res = subst(res, opens, qs.toList());
   273                     }
   274                 }
   275                 return res;
   276             }
   278             @Override
   279             public Type visitErrorType(ErrorType t, Symbol sym) {
   280                 return t;
   281             }
   282         };
   283     // </editor-fold>
   285     // <editor-fold defaultstate="collapsed" desc="isConvertible">
   286     /**
   287      * Is t a subtype of or convertible via boxing/unboxing
   288      * conversion to s?
   289      */
   290     public boolean isConvertible(Type t, Type s, Warner warn) {
   291         if (t.tag == ERROR)
   292             return true;
   293         boolean tPrimitive = t.isPrimitive();
   294         boolean sPrimitive = s.isPrimitive();
   295         if (tPrimitive == sPrimitive) {
   296             return isSubtypeUnchecked(t, s, warn);
   297         }
   298         if (!allowBoxing) return false;
   299         return tPrimitive
   300             ? isSubtype(boxedClass(t).type, s)
   301             : isSubtype(unboxedType(t), s);
   302     }
   304     /**
   305      * Is t a subtype of or convertiable via boxing/unboxing
   306      * convertions to s?
   307      */
   308     public boolean isConvertible(Type t, Type s) {
   309         return isConvertible(t, s, noWarnings);
   310     }
   311     // </editor-fold>
   313     // <editor-fold defaultstate="collapsed" desc="findSam">
   315     /**
   316      * Exception used to report a function descriptor lookup failure. The exception
   317      * wraps a diagnostic that can be used to generate more details error
   318      * messages.
   319      */
   320     public static class FunctionDescriptorLookupError extends RuntimeException {
   321         private static final long serialVersionUID = 0;
   323         JCDiagnostic diagnostic;
   325         FunctionDescriptorLookupError() {
   326             this.diagnostic = null;
   327         }
   329         FunctionDescriptorLookupError setMessage(JCDiagnostic diag) {
   330             this.diagnostic = diag;
   331             return this;
   332         }
   334         public JCDiagnostic getDiagnostic() {
   335             return diagnostic;
   336         }
   337     }
   339     /**
   340      * A cache that keeps track of function descriptors associated with given
   341      * functional interfaces.
   342      */
   343     class DescriptorCache {
   345         private WeakHashMap<TypeSymbol, Entry> _map = new WeakHashMap<TypeSymbol, Entry>();
   347         class FunctionDescriptor {
   348             Symbol descSym;
   350             FunctionDescriptor(Symbol descSym) {
   351                 this.descSym = descSym;
   352             }
   354             public Symbol getSymbol() {
   355                 return descSym;
   356             }
   358             public Type getType(Type site) {
   359                 if (capture(site) != site) {
   360                     Type formalInterface = site.tsym.type;
   361                     ListBuffer<Type> typeargs = ListBuffer.lb();
   362                     List<Type> actualTypeargs = site.getTypeArguments();
   363                     //simply replace the wildcards with its bound
   364                     for (Type t : formalInterface.getTypeArguments()) {
   365                         if (actualTypeargs.head.hasTag(WILDCARD)) {
   366                             WildcardType wt = (WildcardType)actualTypeargs.head;
   367                             typeargs.append(wt.type);
   368                         } else {
   369                             typeargs.append(actualTypeargs.head);
   370                         }
   371                         actualTypeargs = actualTypeargs.tail;
   372                     }
   373                     site = subst(formalInterface, formalInterface.getTypeArguments(), typeargs.toList());
   374                     if (!chk.checkValidGenericType(site)) {
   375                         //if the inferred functional interface type is not well-formed,
   376                         //or if it's not a subtype of the original target, issue an error
   377                         throw failure(diags.fragment("no.suitable.functional.intf.inst", site));
   378                     }
   379                 }
   380                 return memberType(site, descSym);
   381             }
   382         }
   384         class Entry {
   385             final FunctionDescriptor cachedDescRes;
   386             final int prevMark;
   388             public Entry(FunctionDescriptor cachedDescRes,
   389                     int prevMark) {
   390                 this.cachedDescRes = cachedDescRes;
   391                 this.prevMark = prevMark;
   392             }
   394             boolean matches(int mark) {
   395                 return  this.prevMark == mark;
   396             }
   397         }
   399         FunctionDescriptor get(TypeSymbol origin) throws FunctionDescriptorLookupError {
   400             Entry e = _map.get(origin);
   401             CompoundScope members = membersClosure(origin.type, false);
   402             if (e == null ||
   403                     !e.matches(members.getMark())) {
   404                 FunctionDescriptor descRes = findDescriptorInternal(origin, members);
   405                 _map.put(origin, new Entry(descRes, members.getMark()));
   406                 return descRes;
   407             }
   408             else {
   409                 return e.cachedDescRes;
   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() || (origin.flags() & ANNOTATION) != 0) {
   418                 //t must be an interface
   419                 throw failure("not.a.functional.intf", origin);
   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",  origin,
   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", origin,
   438                             diags.fragment("no.abstracts", Kinds.kindName(origin), origin));
   439             } else if (abstracts.size() == 1) {
   440                 return new FunctionDescriptor(abstracts.first());
   441             } else { // size > 1
   442                 FunctionDescriptor descRes = mergeDescriptors(origin, abstracts.toList());
   443                 if (descRes == null) {
   444                     //we can get here if the functional interface is ill-formed
   445                     ListBuffer<JCDiagnostic> descriptors = ListBuffer.lb();
   446                     for (Symbol desc : abstracts) {
   447                         String key = desc.type.getThrownTypes().nonEmpty() ?
   448                                 "descriptor.throws" : "descriptor";
   449                         descriptors.append(diags.fragment(key, desc.name,
   450                                 desc.type.getParameterTypes(),
   451                                 desc.type.getReturnType(),
   452                                 desc.type.getThrownTypes()));
   453                     }
   454                     JCDiagnostic.MultilineDiagnostic incompatibleDescriptors =
   455                             new JCDiagnostic.MultilineDiagnostic(diags.fragment("incompatible.descs.in.functional.intf",
   456                             Kinds.kindName(origin), origin), descriptors.toList());
   457                     throw failure(incompatibleDescriptors);
   458                 }
   459                 return descRes;
   460             }
   461         }
   463         /**
   464          * Compute a synthetic type for the target descriptor given a list
   465          * of override-equivalent methods in the functional interface type.
   466          * The resulting method type is a method type that is override-equivalent
   467          * and return-type substitutable with each method in the original list.
   468          */
   469         private FunctionDescriptor mergeDescriptors(TypeSymbol origin, List<Symbol> methodSyms) {
   470             //pick argument types - simply take the signature that is a
   471             //subsignature of all other signatures in the list (as per JLS 8.4.2)
   472             List<Symbol> mostSpecific = List.nil();
   473             outer: for (Symbol msym1 : methodSyms) {
   474                 Type mt1 = memberType(origin.type, msym1);
   475                 for (Symbol msym2 : methodSyms) {
   476                     Type mt2 = memberType(origin.type, msym2);
   477                     if (!isSubSignature(mt1, mt2)) {
   478                         continue outer;
   479                     }
   480                 }
   481                 mostSpecific = mostSpecific.prepend(msym1);
   482             }
   483             if (mostSpecific.isEmpty()) {
   484                 return null;
   485             }
   488             //pick return types - this is done in two phases: (i) first, the most
   489             //specific return type is chosen using strict subtyping; if this fails,
   490             //a second attempt is made using return type substitutability (see JLS 8.4.5)
   491             boolean phase2 = false;
   492             Symbol bestSoFar = null;
   493             while (bestSoFar == null) {
   494                 outer: for (Symbol msym1 : mostSpecific) {
   495                     Type mt1 = memberType(origin.type, msym1);
   496                     for (Symbol msym2 : methodSyms) {
   497                         Type mt2 = memberType(origin.type, msym2);
   498                         if (phase2 ?
   499                                 !returnTypeSubstitutable(mt1, mt2) :
   500                                 !isSubtypeInternal(mt1.getReturnType(), mt2.getReturnType())) {
   501                             continue outer;
   502                         }
   503                     }
   504                     bestSoFar = msym1;
   505                 }
   506                 if (phase2) {
   507                     break;
   508                 } else {
   509                     phase2 = true;
   510                 }
   511             }
   512             if (bestSoFar == null) return null;
   514             //merge thrown types - form the intersection of all the thrown types in
   515             //all the signatures in the list
   516             List<Type> thrown = null;
   517             for (Symbol msym1 : methodSyms) {
   518                 Type mt1 = memberType(origin.type, msym1);
   519                 thrown = (thrown == null) ?
   520                     mt1.getThrownTypes() :
   521                     chk.intersect(mt1.getThrownTypes(), thrown);
   522             }
   524             final List<Type> thrown1 = thrown;
   525             return new FunctionDescriptor(bestSoFar) {
   526                 @Override
   527                 public Type getType(Type origin) {
   528                     Type mt = memberType(origin, getSymbol());
   529                     return new MethodType(mt.getParameterTypes(), mt.getReturnType(), thrown1, syms.methodClass);
   530                 }
   531             };
   532         }
   534         boolean isSubtypeInternal(Type s, Type t) {
   535             return (s.isPrimitive() && t.isPrimitive()) ?
   536                     isSameType(t, s) :
   537                     isSubtype(s, t);
   538         }
   540         FunctionDescriptorLookupError failure(String msg, Object... args) {
   541             return failure(diags.fragment(msg, args));
   542         }
   544         FunctionDescriptorLookupError failure(JCDiagnostic diag) {
   545             return functionDescriptorLookupError.setMessage(diag);
   546         }
   547     }
   549     private DescriptorCache descCache = new DescriptorCache();
   551     /**
   552      * Find the method descriptor associated to this class symbol - if the
   553      * symbol 'origin' is not a functional interface, an exception is thrown.
   554      */
   555     public Symbol findDescriptorSymbol(TypeSymbol origin) throws FunctionDescriptorLookupError {
   556         return descCache.get(origin).getSymbol();
   557     }
   559     /**
   560      * Find the type of the method descriptor associated to this class symbol -
   561      * if the symbol 'origin' is not a functional interface, an exception is thrown.
   562      */
   563     public Type findDescriptorType(Type origin) throws FunctionDescriptorLookupError {
   564         return descCache.get(origin.tsym).getType(origin);
   565     }
   567     /**
   568      * Is given type a functional interface?
   569      */
   570     public boolean isFunctionalInterface(TypeSymbol tsym) {
   571         try {
   572             findDescriptorSymbol(tsym);
   573             return true;
   574         } catch (FunctionDescriptorLookupError ex) {
   575             return false;
   576         }
   577     }
   579     public boolean isFunctionalInterface(Type site) {
   580         try {
   581             findDescriptorType(site);
   582             return true;
   583         } catch (FunctionDescriptorLookupError ex) {
   584             return false;
   585         }
   586     }
   587     // </editor-fold>
   589    /**
   590     * Scope filter used to skip methods that should be ignored (such as methods
   591     * overridden by j.l.Object) during function interface conversion/marker interface checks
   592     */
   593     class DescriptorFilter implements Filter<Symbol> {
   595        TypeSymbol origin;
   597        DescriptorFilter(TypeSymbol origin) {
   598            this.origin = origin;
   599        }
   601        @Override
   602        public boolean accepts(Symbol sym) {
   603            return sym.kind == Kinds.MTH &&
   604                    (sym.flags() & (ABSTRACT | DEFAULT)) == ABSTRACT &&
   605                    !overridesObjectMethod(origin, sym) &&
   606                    (interfaceCandidates(origin.type, (MethodSymbol)sym).head.flags() & DEFAULT) == 0;
   607        }
   608     };
   610     // <editor-fold defaultstate="collapsed" desc="isMarker">
   612     /**
   613      * A cache that keeps track of marker interfaces
   614      */
   615     class MarkerCache {
   617         private WeakHashMap<TypeSymbol, Entry> _map = new WeakHashMap<TypeSymbol, Entry>();
   619         class Entry {
   620             final boolean isMarkerIntf;
   621             final int prevMark;
   623             public Entry(boolean isMarkerIntf,
   624                     int prevMark) {
   625                 this.isMarkerIntf = isMarkerIntf;
   626                 this.prevMark = prevMark;
   627             }
   629             boolean matches(int mark) {
   630                 return  this.prevMark == mark;
   631             }
   632         }
   634         boolean get(TypeSymbol origin) throws FunctionDescriptorLookupError {
   635             Entry e = _map.get(origin);
   636             CompoundScope members = membersClosure(origin.type, false);
   637             if (e == null ||
   638                     !e.matches(members.getMark())) {
   639                 boolean isMarkerIntf = isMarkerInterfaceInternal(origin, members);
   640                 _map.put(origin, new Entry(isMarkerIntf, members.getMark()));
   641                 return isMarkerIntf;
   642             }
   643             else {
   644                 return e.isMarkerIntf;
   645             }
   646         }
   648         /**
   649          * Is given symbol a marker interface
   650          */
   651         public boolean isMarkerInterfaceInternal(TypeSymbol origin, CompoundScope membersCache) throws FunctionDescriptorLookupError {
   652             return !origin.isInterface() ?
   653                     false :
   654                     !membersCache.getElements(new DescriptorFilter(origin)).iterator().hasNext();
   655         }
   656     }
   658     private MarkerCache markerCache = new MarkerCache();
   660     /**
   661      * Is given type a marker interface?
   662      */
   663     public boolean isMarkerInterface(Type site) {
   664         return markerCache.get(site.tsym);
   665     }
   666     // </editor-fold>
   668     // <editor-fold defaultstate="collapsed" desc="isSubtype">
   669     /**
   670      * Is t an unchecked subtype of s?
   671      */
   672     public boolean isSubtypeUnchecked(Type t, Type s) {
   673         return isSubtypeUnchecked(t, s, noWarnings);
   674     }
   675     /**
   676      * Is t an unchecked subtype of s?
   677      */
   678     public boolean isSubtypeUnchecked(Type t, Type s, Warner warn) {
   679         boolean result = isSubtypeUncheckedInternal(t, s, warn);
   680         if (result) {
   681             checkUnsafeVarargsConversion(t, s, warn);
   682         }
   683         return result;
   684     }
   685     //where
   686         private boolean isSubtypeUncheckedInternal(Type t, Type s, Warner warn) {
   687             if (t.hasTag(ARRAY) && s.hasTag(ARRAY)) {
   688                 t = t.unannotatedType();
   689                 s = s.unannotatedType();
   690                 if (((ArrayType)t).elemtype.isPrimitive()) {
   691                     return isSameType(elemtype(t), elemtype(s));
   692                 } else {
   693                     return isSubtypeUnchecked(elemtype(t), elemtype(s), warn);
   694                 }
   695             } else if (isSubtype(t, s)) {
   696                 return true;
   697             }
   698             else if (t.tag == TYPEVAR) {
   699                 return isSubtypeUnchecked(t.getUpperBound(), s, warn);
   700             }
   701             else if (!s.isRaw()) {
   702                 Type t2 = asSuper(t, s.tsym);
   703                 if (t2 != null && t2.isRaw()) {
   704                     if (isReifiable(s))
   705                         warn.silentWarn(LintCategory.UNCHECKED);
   706                     else
   707                         warn.warn(LintCategory.UNCHECKED);
   708                     return true;
   709                 }
   710             }
   711             return false;
   712         }
   714         private void checkUnsafeVarargsConversion(Type t, Type s, Warner warn) {
   715             if (t.tag != ARRAY || isReifiable(t))
   716                 return;
   717             t = t.unannotatedType();
   718             s = s.unannotatedType();
   719             ArrayType from = (ArrayType)t;
   720             boolean shouldWarn = false;
   721             switch (s.tag) {
   722                 case ARRAY:
   723                     ArrayType to = (ArrayType)s;
   724                     shouldWarn = from.isVarargs() &&
   725                             !to.isVarargs() &&
   726                             !isReifiable(from);
   727                     break;
   728                 case CLASS:
   729                     shouldWarn = from.isVarargs();
   730                     break;
   731             }
   732             if (shouldWarn) {
   733                 warn.warn(LintCategory.VARARGS);
   734             }
   735         }
   737     /**
   738      * Is t a subtype of s?<br>
   739      * (not defined for Method and ForAll types)
   740      */
   741     final public boolean isSubtype(Type t, Type s) {
   742         return isSubtype(t, s, true);
   743     }
   744     final public boolean isSubtypeNoCapture(Type t, Type s) {
   745         return isSubtype(t, s, false);
   746     }
   747     public boolean isSubtype(Type t, Type s, boolean capture) {
   748         if (t == s)
   749             return true;
   751         t = t.unannotatedType();
   752         s = s.unannotatedType();
   754         if (t == s)
   755             return true;
   757         if (s.isPartial())
   758             return isSuperType(s, t);
   760         if (s.isCompound()) {
   761             for (Type s2 : interfaces(s).prepend(supertype(s))) {
   762                 if (!isSubtype(t, s2, capture))
   763                     return false;
   764             }
   765             return true;
   766         }
   768         Type lower = lowerBound(s);
   769         if (s != lower)
   770             return isSubtype(capture ? capture(t) : t, lower, false);
   772         return isSubtype.visit(capture ? capture(t) : t, s);
   773     }
   774     // where
   775         private TypeRelation isSubtype = new TypeRelation()
   776         {
   777             public Boolean visitType(Type t, Type s) {
   778                 switch (t.tag) {
   779                  case BYTE:
   780                      return (!s.hasTag(CHAR) && t.getTag().isSubRangeOf(s.getTag()));
   781                  case CHAR:
   782                      return (!s.hasTag(SHORT) && t.getTag().isSubRangeOf(s.getTag()));
   783                  case SHORT: case INT: case LONG:
   784                  case FLOAT: case DOUBLE:
   785                      return t.getTag().isSubRangeOf(s.getTag());
   786                  case BOOLEAN: case VOID:
   787                      return t.hasTag(s.getTag());
   788                  case TYPEVAR:
   789                      return isSubtypeNoCapture(t.getUpperBound(), s);
   790                  case BOT:
   791                      return
   792                          s.hasTag(BOT) || s.hasTag(CLASS) ||
   793                          s.hasTag(ARRAY) || s.hasTag(TYPEVAR);
   794                  case WILDCARD: //we shouldn't be here - avoids crash (see 7034495)
   795                  case NONE:
   796                      return false;
   797                  default:
   798                      throw new AssertionError("isSubtype " + t.tag);
   799                  }
   800             }
   802             private Set<TypePair> cache = new HashSet<TypePair>();
   804             private boolean containsTypeRecursive(Type t, Type s) {
   805                 TypePair pair = new TypePair(t, s);
   806                 if (cache.add(pair)) {
   807                     try {
   808                         return containsType(t.getTypeArguments(),
   809                                             s.getTypeArguments());
   810                     } finally {
   811                         cache.remove(pair);
   812                     }
   813                 } else {
   814                     return containsType(t.getTypeArguments(),
   815                                         rewriteSupers(s).getTypeArguments());
   816                 }
   817             }
   819             private Type rewriteSupers(Type t) {
   820                 if (!t.isParameterized())
   821                     return t;
   822                 ListBuffer<Type> from = lb();
   823                 ListBuffer<Type> to = lb();
   824                 adaptSelf(t, from, to);
   825                 if (from.isEmpty())
   826                     return t;
   827                 ListBuffer<Type> rewrite = lb();
   828                 boolean changed = false;
   829                 for (Type orig : to.toList()) {
   830                     Type s = rewriteSupers(orig);
   831                     if (s.isSuperBound() && !s.isExtendsBound()) {
   832                         s = new WildcardType(syms.objectType,
   833                                              BoundKind.UNBOUND,
   834                                              syms.boundClass);
   835                         changed = true;
   836                     } else if (s != orig) {
   837                         s = new WildcardType(upperBound(s),
   838                                              BoundKind.EXTENDS,
   839                                              syms.boundClass);
   840                         changed = true;
   841                     }
   842                     rewrite.append(s);
   843                 }
   844                 if (changed)
   845                     return subst(t.tsym.type, from.toList(), rewrite.toList());
   846                 else
   847                     return t;
   848             }
   850             @Override
   851             public Boolean visitClassType(ClassType t, Type s) {
   852                 Type sup = asSuper(t, s.tsym);
   853                 return sup != null
   854                     && sup.tsym == s.tsym
   855                     // You're not allowed to write
   856                     //     Vector<Object> vec = new Vector<String>();
   857                     // But with wildcards you can write
   858                     //     Vector<? extends Object> vec = new Vector<String>();
   859                     // which means that subtype checking must be done
   860                     // here instead of same-type checking (via containsType).
   861                     && (!s.isParameterized() || containsTypeRecursive(s, sup))
   862                     && isSubtypeNoCapture(sup.getEnclosingType(),
   863                                           s.getEnclosingType());
   864             }
   866             @Override
   867             public Boolean visitArrayType(ArrayType t, Type s) {
   868                 if (s.tag == ARRAY) {
   869                     if (t.elemtype.isPrimitive())
   870                         return isSameType(t.elemtype, elemtype(s));
   871                     else
   872                         return isSubtypeNoCapture(t.elemtype, elemtype(s));
   873                 }
   875                 if (s.tag == CLASS) {
   876                     Name sname = s.tsym.getQualifiedName();
   877                     return sname == names.java_lang_Object
   878                         || sname == names.java_lang_Cloneable
   879                         || sname == names.java_io_Serializable;
   880                 }
   882                 return false;
   883             }
   885             @Override
   886             public Boolean visitUndetVar(UndetVar t, Type s) {
   887                 //todo: test against origin needed? or replace with substitution?
   888                 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN) {
   889                     return true;
   890                 } else if (s.tag == BOT) {
   891                     //if 's' is 'null' there's no instantiated type U for which
   892                     //U <: s (but 'null' itself, which is not a valid type)
   893                     return false;
   894                 }
   896                 t.addBound(InferenceBound.UPPER, s, Types.this);
   897                 return true;
   898             }
   900             @Override
   901             public Boolean visitErrorType(ErrorType t, Type s) {
   902                 return true;
   903             }
   904         };
   906     /**
   907      * Is t a subtype of every type in given list `ts'?<br>
   908      * (not defined for Method and ForAll types)<br>
   909      * Allows unchecked conversions.
   910      */
   911     public boolean isSubtypeUnchecked(Type t, List<Type> ts, Warner warn) {
   912         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
   913             if (!isSubtypeUnchecked(t, l.head, warn))
   914                 return false;
   915         return true;
   916     }
   918     /**
   919      * Are corresponding elements of ts subtypes of ss?  If lists are
   920      * of different length, return false.
   921      */
   922     public boolean isSubtypes(List<Type> ts, List<Type> ss) {
   923         while (ts.tail != null && ss.tail != null
   924                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   925                isSubtype(ts.head, ss.head)) {
   926             ts = ts.tail;
   927             ss = ss.tail;
   928         }
   929         return ts.tail == null && ss.tail == null;
   930         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   931     }
   933     /**
   934      * Are corresponding elements of ts subtypes of ss, allowing
   935      * unchecked conversions?  If lists are of different length,
   936      * return false.
   937      **/
   938     public boolean isSubtypesUnchecked(List<Type> ts, List<Type> ss, Warner warn) {
   939         while (ts.tail != null && ss.tail != null
   940                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   941                isSubtypeUnchecked(ts.head, ss.head, warn)) {
   942             ts = ts.tail;
   943             ss = ss.tail;
   944         }
   945         return ts.tail == null && ss.tail == null;
   946         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   947     }
   948     // </editor-fold>
   950     // <editor-fold defaultstate="collapsed" desc="isSuperType">
   951     /**
   952      * Is t a supertype of s?
   953      */
   954     public boolean isSuperType(Type t, Type s) {
   955         switch (t.tag) {
   956         case ERROR:
   957             return true;
   958         case UNDETVAR: {
   959             UndetVar undet = (UndetVar)t;
   960             if (t == s ||
   961                 undet.qtype == s ||
   962                 s.tag == ERROR ||
   963                 s.tag == BOT) return true;
   964             undet.addBound(InferenceBound.LOWER, s, this);
   965             return true;
   966         }
   967         default:
   968             return isSubtype(s, t);
   969         }
   970     }
   971     // </editor-fold>
   973     // <editor-fold defaultstate="collapsed" desc="isSameType">
   974     /**
   975      * Are corresponding elements of the lists the same type?  If
   976      * lists are of different length, return false.
   977      */
   978     public boolean isSameTypes(List<Type> ts, List<Type> ss) {
   979         while (ts.tail != null && ss.tail != null
   980                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   981                isSameType(ts.head, ss.head)) {
   982             ts = ts.tail;
   983             ss = ss.tail;
   984         }
   985         return ts.tail == null && ss.tail == null;
   986         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   987     }
   989     /**
   990      * Is t the same type as s?
   991      */
   992     public boolean isSameType(Type t, Type s) {
   993         return isSameType.visit(t, s);
   994     }
   995     // where
   996         private TypeRelation isSameType = new TypeRelation() {
   998             public Boolean visitType(Type t, Type s) {
   999                 if (t == s)
  1000                     return true;
  1002                 if (s.isPartial())
  1003                     return visit(s, t);
  1005                 switch (t.tag) {
  1006                 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
  1007                 case DOUBLE: case BOOLEAN: case VOID: case BOT: case NONE:
  1008                     return t.tag == s.tag;
  1009                 case TYPEVAR: {
  1010                     if (s.tag == TYPEVAR) {
  1011                         //type-substitution does not preserve type-var types
  1012                         //check that type var symbols and bounds are indeed the same
  1013                         return t.tsym == s.tsym &&
  1014                                 visit(t.getUpperBound(), s.getUpperBound());
  1016                     else {
  1017                         //special case for s == ? super X, where upper(s) = u
  1018                         //check that u == t, where u has been set by Type.withTypeVar
  1019                         return s.isSuperBound() &&
  1020                                 !s.isExtendsBound() &&
  1021                                 visit(t, upperBound(s));
  1024                 default:
  1025                     throw new AssertionError("isSameType " + t.tag);
  1029             @Override
  1030             public Boolean visitWildcardType(WildcardType t, Type s) {
  1031                 if (s.isPartial())
  1032                     return visit(s, t);
  1033                 else
  1034                     return false;
  1037             @Override
  1038             public Boolean visitClassType(ClassType t, Type s) {
  1039                 if (t == s)
  1040                     return true;
  1042                 if (s.isPartial())
  1043                     return visit(s, t);
  1045                 if (s.isSuperBound() && !s.isExtendsBound())
  1046                     return visit(t, upperBound(s)) && visit(t, lowerBound(s));
  1048                 if (t.isCompound() && s.isCompound()) {
  1049                     if (!visit(supertype(t), supertype(s)))
  1050                         return false;
  1052                     HashSet<UniqueType> set = new HashSet<UniqueType>();
  1053                     for (Type x : interfaces(t))
  1054                         set.add(new UniqueType(x, Types.this));
  1055                     for (Type x : interfaces(s)) {
  1056                         if (!set.remove(new UniqueType(x, Types.this)))
  1057                             return false;
  1059                     return (set.isEmpty());
  1061                 return t.tsym == s.tsym
  1062                     && visit(t.getEnclosingType(), s.getEnclosingType())
  1063                     && containsTypeEquivalent(t.getTypeArguments(), s.getTypeArguments());
  1066             @Override
  1067             public Boolean visitArrayType(ArrayType t, Type s) {
  1068                 if (t == s)
  1069                     return true;
  1071                 if (s.isPartial())
  1072                     return visit(s, t);
  1074                 return s.hasTag(ARRAY)
  1075                     && containsTypeEquivalent(t.elemtype, elemtype(s));
  1078             @Override
  1079             public Boolean visitMethodType(MethodType t, Type s) {
  1080                 // isSameType for methods does not take thrown
  1081                 // exceptions into account!
  1082                 return hasSameArgs(t, s) && visit(t.getReturnType(), s.getReturnType());
  1085             @Override
  1086             public Boolean visitPackageType(PackageType t, Type s) {
  1087                 return t == s;
  1090             @Override
  1091             public Boolean visitForAll(ForAll t, Type s) {
  1092                 if (s.tag != FORALL)
  1093                     return false;
  1095                 ForAll forAll = (ForAll)s;
  1096                 return hasSameBounds(t, forAll)
  1097                     && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
  1100             @Override
  1101             public Boolean visitUndetVar(UndetVar t, Type s) {
  1102                 if (s.tag == WILDCARD)
  1103                     // FIXME, this might be leftovers from before capture conversion
  1104                     return false;
  1106                 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN)
  1107                     return true;
  1109                 t.addBound(InferenceBound.EQ, s, Types.this);
  1111                 return true;
  1114             @Override
  1115             public Boolean visitErrorType(ErrorType t, Type s) {
  1116                 return true;
  1118         };
  1119     // </editor-fold>
  1121     // <editor-fold defaultstate="collapsed" desc="Contains Type">
  1122     public boolean containedBy(Type t, Type s) {
  1123         switch (t.tag) {
  1124         case UNDETVAR:
  1125             if (s.tag == WILDCARD) {
  1126                 UndetVar undetvar = (UndetVar)t;
  1127                 WildcardType wt = (WildcardType)s;
  1128                 switch(wt.kind) {
  1129                     case UNBOUND: //similar to ? extends Object
  1130                     case EXTENDS: {
  1131                         Type bound = upperBound(s);
  1132                         undetvar.addBound(InferenceBound.UPPER, bound, this);
  1133                         break;
  1135                     case SUPER: {
  1136                         Type bound = lowerBound(s);
  1137                         undetvar.addBound(InferenceBound.LOWER, bound, this);
  1138                         break;
  1141                 return true;
  1142             } else {
  1143                 return isSameType(t, s);
  1145         case ERROR:
  1146             return true;
  1147         default:
  1148             return containsType(s, t);
  1152     boolean containsType(List<Type> ts, List<Type> ss) {
  1153         while (ts.nonEmpty() && ss.nonEmpty()
  1154                && containsType(ts.head, ss.head)) {
  1155             ts = ts.tail;
  1156             ss = ss.tail;
  1158         return ts.isEmpty() && ss.isEmpty();
  1161     /**
  1162      * Check if t contains s.
  1164      * <p>T contains S if:
  1166      * <p>{@code L(T) <: L(S) && U(S) <: U(T)}
  1168      * <p>This relation is only used by ClassType.isSubtype(), that
  1169      * is,
  1171      * <p>{@code C<S> <: C<T> if T contains S.}
  1173      * <p>Because of F-bounds, this relation can lead to infinite
  1174      * recursion.  Thus we must somehow break that recursion.  Notice
  1175      * that containsType() is only called from ClassType.isSubtype().
  1176      * Since the arguments have already been checked against their
  1177      * bounds, we know:
  1179      * <p>{@code U(S) <: U(T) if T is "super" bound (U(T) *is* the bound)}
  1181      * <p>{@code L(T) <: L(S) if T is "extends" bound (L(T) is bottom)}
  1183      * @param t a type
  1184      * @param s a type
  1185      */
  1186     public boolean containsType(Type t, Type s) {
  1187         return containsType.visit(t, s);
  1189     // where
  1190         private TypeRelation containsType = new TypeRelation() {
  1192             private Type U(Type t) {
  1193                 while (t.tag == WILDCARD) {
  1194                     WildcardType w = (WildcardType)t;
  1195                     if (w.isSuperBound())
  1196                         return w.bound == null ? syms.objectType : w.bound.bound;
  1197                     else
  1198                         t = w.type;
  1200                 return t;
  1203             private Type L(Type t) {
  1204                 while (t.tag == WILDCARD) {
  1205                     WildcardType w = (WildcardType)t;
  1206                     if (w.isExtendsBound())
  1207                         return syms.botType;
  1208                     else
  1209                         t = w.type;
  1211                 return t;
  1214             public Boolean visitType(Type t, Type s) {
  1215                 if (s.isPartial())
  1216                     return containedBy(s, t);
  1217                 else
  1218                     return isSameType(t, s);
  1221 //            void debugContainsType(WildcardType t, Type s) {
  1222 //                System.err.println();
  1223 //                System.err.format(" does %s contain %s?%n", t, s);
  1224 //                System.err.format(" %s U(%s) <: U(%s) %s = %s%n",
  1225 //                                  upperBound(s), s, t, U(t),
  1226 //                                  t.isSuperBound()
  1227 //                                  || isSubtypeNoCapture(upperBound(s), U(t)));
  1228 //                System.err.format(" %s L(%s) <: L(%s) %s = %s%n",
  1229 //                                  L(t), t, s, lowerBound(s),
  1230 //                                  t.isExtendsBound()
  1231 //                                  || isSubtypeNoCapture(L(t), lowerBound(s)));
  1232 //                System.err.println();
  1233 //            }
  1235             @Override
  1236             public Boolean visitWildcardType(WildcardType t, Type s) {
  1237                 if (s.isPartial())
  1238                     return containedBy(s, t);
  1239                 else {
  1240 //                    debugContainsType(t, s);
  1241                     return isSameWildcard(t, s)
  1242                         || isCaptureOf(s, t)
  1243                         || ((t.isExtendsBound() || isSubtypeNoCapture(L(t), lowerBound(s))) &&
  1244                             (t.isSuperBound() || isSubtypeNoCapture(upperBound(s), U(t))));
  1248             @Override
  1249             public Boolean visitUndetVar(UndetVar t, Type s) {
  1250                 if (s.tag != WILDCARD)
  1251                     return isSameType(t, s);
  1252                 else
  1253                     return false;
  1256             @Override
  1257             public Boolean visitErrorType(ErrorType t, Type s) {
  1258                 return true;
  1260         };
  1262     public boolean isCaptureOf(Type s, WildcardType t) {
  1263         if (s.tag != TYPEVAR || !((TypeVar)s).isCaptured())
  1264             return false;
  1265         return isSameWildcard(t, ((CapturedType)s).wildcard);
  1268     public boolean isSameWildcard(WildcardType t, Type s) {
  1269         if (s.tag != WILDCARD)
  1270             return false;
  1271         WildcardType w = (WildcardType)s;
  1272         return w.kind == t.kind && w.type == t.type;
  1275     public boolean containsTypeEquivalent(List<Type> ts, List<Type> ss) {
  1276         while (ts.nonEmpty() && ss.nonEmpty()
  1277                && containsTypeEquivalent(ts.head, ss.head)) {
  1278             ts = ts.tail;
  1279             ss = ss.tail;
  1281         return ts.isEmpty() && ss.isEmpty();
  1283     // </editor-fold>
  1285     // <editor-fold defaultstate="collapsed" desc="isCastable">
  1286     public boolean isCastable(Type t, Type s) {
  1287         return isCastable(t, s, noWarnings);
  1290     /**
  1291      * Is t is castable to s?<br>
  1292      * s is assumed to be an erased type.<br>
  1293      * (not defined for Method and ForAll types).
  1294      */
  1295     public boolean isCastable(Type t, Type s, Warner warn) {
  1296         if (t == s)
  1297             return true;
  1299         if (t.isPrimitive() != s.isPrimitive())
  1300             return allowBoxing && (
  1301                     isConvertible(t, s, warn)
  1302                     || (allowObjectToPrimitiveCast &&
  1303                         s.isPrimitive() &&
  1304                         isSubtype(boxedClass(s).type, t)));
  1305         if (warn != warnStack.head) {
  1306             try {
  1307                 warnStack = warnStack.prepend(warn);
  1308                 checkUnsafeVarargsConversion(t, s, warn);
  1309                 return isCastable.visit(t,s);
  1310             } finally {
  1311                 warnStack = warnStack.tail;
  1313         } else {
  1314             return isCastable.visit(t,s);
  1317     // where
  1318         private TypeRelation isCastable = new TypeRelation() {
  1320             public Boolean visitType(Type t, Type s) {
  1321                 if (s.tag == ERROR)
  1322                     return true;
  1324                 switch (t.tag) {
  1325                 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
  1326                 case DOUBLE:
  1327                     return s.isNumeric();
  1328                 case BOOLEAN:
  1329                     return s.tag == BOOLEAN;
  1330                 case VOID:
  1331                     return false;
  1332                 case BOT:
  1333                     return isSubtype(t, s);
  1334                 default:
  1335                     throw new AssertionError();
  1339             @Override
  1340             public Boolean visitWildcardType(WildcardType t, Type s) {
  1341                 return isCastable(upperBound(t), s, warnStack.head);
  1344             @Override
  1345             public Boolean visitClassType(ClassType t, Type s) {
  1346                 if (s.tag == ERROR || s.tag == BOT)
  1347                     return true;
  1349                 if (s.tag == TYPEVAR) {
  1350                     if (isCastable(t, s.getUpperBound(), noWarnings)) {
  1351                         warnStack.head.warn(LintCategory.UNCHECKED);
  1352                         return true;
  1353                     } else {
  1354                         return false;
  1358                 if (t.isCompound()) {
  1359                     Warner oldWarner = warnStack.head;
  1360                     warnStack.head = noWarnings;
  1361                     if (!visit(supertype(t), s))
  1362                         return false;
  1363                     for (Type intf : interfaces(t)) {
  1364                         if (!visit(intf, s))
  1365                             return false;
  1367                     if (warnStack.head.hasLint(LintCategory.UNCHECKED))
  1368                         oldWarner.warn(LintCategory.UNCHECKED);
  1369                     return true;
  1372                 if (s.isCompound()) {
  1373                     // call recursively to reuse the above code
  1374                     return visitClassType((ClassType)s, t);
  1377                 if (s.tag == CLASS || s.tag == ARRAY) {
  1378                     boolean upcast;
  1379                     if ((upcast = isSubtype(erasure(t), erasure(s)))
  1380                         || isSubtype(erasure(s), erasure(t))) {
  1381                         if (!upcast && s.tag == ARRAY) {
  1382                             if (!isReifiable(s))
  1383                                 warnStack.head.warn(LintCategory.UNCHECKED);
  1384                             return true;
  1385                         } else if (s.isRaw()) {
  1386                             return true;
  1387                         } else if (t.isRaw()) {
  1388                             if (!isUnbounded(s))
  1389                                 warnStack.head.warn(LintCategory.UNCHECKED);
  1390                             return true;
  1392                         // Assume |a| <: |b|
  1393                         final Type a = upcast ? t : s;
  1394                         final Type b = upcast ? s : t;
  1395                         final boolean HIGH = true;
  1396                         final boolean LOW = false;
  1397                         final boolean DONT_REWRITE_TYPEVARS = false;
  1398                         Type aHigh = rewriteQuantifiers(a, HIGH, DONT_REWRITE_TYPEVARS);
  1399                         Type aLow  = rewriteQuantifiers(a, LOW,  DONT_REWRITE_TYPEVARS);
  1400                         Type bHigh = rewriteQuantifiers(b, HIGH, DONT_REWRITE_TYPEVARS);
  1401                         Type bLow  = rewriteQuantifiers(b, LOW,  DONT_REWRITE_TYPEVARS);
  1402                         Type lowSub = asSub(bLow, aLow.tsym);
  1403                         Type highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
  1404                         if (highSub == null) {
  1405                             final boolean REWRITE_TYPEVARS = true;
  1406                             aHigh = rewriteQuantifiers(a, HIGH, REWRITE_TYPEVARS);
  1407                             aLow  = rewriteQuantifiers(a, LOW,  REWRITE_TYPEVARS);
  1408                             bHigh = rewriteQuantifiers(b, HIGH, REWRITE_TYPEVARS);
  1409                             bLow  = rewriteQuantifiers(b, LOW,  REWRITE_TYPEVARS);
  1410                             lowSub = asSub(bLow, aLow.tsym);
  1411                             highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
  1413                         if (highSub != null) {
  1414                             if (!(a.tsym == highSub.tsym && a.tsym == lowSub.tsym)) {
  1415                                 Assert.error(a.tsym + " != " + highSub.tsym + " != " + lowSub.tsym);
  1417                             if (!disjointTypes(aHigh.allparams(), highSub.allparams())
  1418                                 && !disjointTypes(aHigh.allparams(), lowSub.allparams())
  1419                                 && !disjointTypes(aLow.allparams(), highSub.allparams())
  1420                                 && !disjointTypes(aLow.allparams(), lowSub.allparams())) {
  1421                                 if (upcast ? giveWarning(a, b) :
  1422                                     giveWarning(b, a))
  1423                                     warnStack.head.warn(LintCategory.UNCHECKED);
  1424                                 return true;
  1427                         if (isReifiable(s))
  1428                             return isSubtypeUnchecked(a, b);
  1429                         else
  1430                             return isSubtypeUnchecked(a, b, warnStack.head);
  1433                     // Sidecast
  1434                     if (s.tag == CLASS) {
  1435                         if ((s.tsym.flags() & INTERFACE) != 0) {
  1436                             return ((t.tsym.flags() & FINAL) == 0)
  1437                                 ? sideCast(t, s, warnStack.head)
  1438                                 : sideCastFinal(t, s, warnStack.head);
  1439                         } else if ((t.tsym.flags() & INTERFACE) != 0) {
  1440                             return ((s.tsym.flags() & FINAL) == 0)
  1441                                 ? sideCast(t, s, warnStack.head)
  1442                                 : sideCastFinal(t, s, warnStack.head);
  1443                         } else {
  1444                             // unrelated class types
  1445                             return false;
  1449                 return false;
  1452             @Override
  1453             public Boolean visitArrayType(ArrayType t, Type s) {
  1454                 switch (s.tag) {
  1455                 case ERROR:
  1456                 case BOT:
  1457                     return true;
  1458                 case TYPEVAR:
  1459                     if (isCastable(s, t, noWarnings)) {
  1460                         warnStack.head.warn(LintCategory.UNCHECKED);
  1461                         return true;
  1462                     } else {
  1463                         return false;
  1465                 case CLASS:
  1466                     return isSubtype(t, s);
  1467                 case ARRAY:
  1468                     if (elemtype(t).isPrimitive() || elemtype(s).isPrimitive()) {
  1469                         return elemtype(t).tag == elemtype(s).tag;
  1470                     } else {
  1471                         return visit(elemtype(t), elemtype(s));
  1473                 default:
  1474                     return false;
  1478             @Override
  1479             public Boolean visitTypeVar(TypeVar t, Type s) {
  1480                 switch (s.tag) {
  1481                 case ERROR:
  1482                 case BOT:
  1483                     return true;
  1484                 case TYPEVAR:
  1485                     if (isSubtype(t, s)) {
  1486                         return true;
  1487                     } else if (isCastable(t.bound, s, noWarnings)) {
  1488                         warnStack.head.warn(LintCategory.UNCHECKED);
  1489                         return true;
  1490                     } else {
  1491                         return false;
  1493                 default:
  1494                     return isCastable(t.bound, s, warnStack.head);
  1498             @Override
  1499             public Boolean visitErrorType(ErrorType t, Type s) {
  1500                 return true;
  1502         };
  1503     // </editor-fold>
  1505     // <editor-fold defaultstate="collapsed" desc="disjointTypes">
  1506     public boolean disjointTypes(List<Type> ts, List<Type> ss) {
  1507         while (ts.tail != null && ss.tail != null) {
  1508             if (disjointType(ts.head, ss.head)) return true;
  1509             ts = ts.tail;
  1510             ss = ss.tail;
  1512         return false;
  1515     /**
  1516      * Two types or wildcards are considered disjoint if it can be
  1517      * proven that no type can be contained in both. It is
  1518      * conservative in that it is allowed to say that two types are
  1519      * not disjoint, even though they actually are.
  1521      * The type {@code C<X>} is castable to {@code C<Y>} exactly if
  1522      * {@code X} and {@code Y} are not disjoint.
  1523      */
  1524     public boolean disjointType(Type t, Type s) {
  1525         return disjointType.visit(t, s);
  1527     // where
  1528         private TypeRelation disjointType = new TypeRelation() {
  1530             private Set<TypePair> cache = new HashSet<TypePair>();
  1532             public Boolean visitType(Type t, Type s) {
  1533                 if (s.tag == WILDCARD)
  1534                     return visit(s, t);
  1535                 else
  1536                     return notSoftSubtypeRecursive(t, s) || notSoftSubtypeRecursive(s, t);
  1539             private boolean isCastableRecursive(Type t, Type s) {
  1540                 TypePair pair = new TypePair(t, s);
  1541                 if (cache.add(pair)) {
  1542                     try {
  1543                         return Types.this.isCastable(t, s);
  1544                     } finally {
  1545                         cache.remove(pair);
  1547                 } else {
  1548                     return true;
  1552             private boolean notSoftSubtypeRecursive(Type t, Type s) {
  1553                 TypePair pair = new TypePair(t, s);
  1554                 if (cache.add(pair)) {
  1555                     try {
  1556                         return Types.this.notSoftSubtype(t, s);
  1557                     } finally {
  1558                         cache.remove(pair);
  1560                 } else {
  1561                     return false;
  1565             @Override
  1566             public Boolean visitWildcardType(WildcardType t, Type s) {
  1567                 if (t.isUnbound())
  1568                     return false;
  1570                 if (s.tag != WILDCARD) {
  1571                     if (t.isExtendsBound())
  1572                         return notSoftSubtypeRecursive(s, t.type);
  1573                     else // isSuperBound()
  1574                         return notSoftSubtypeRecursive(t.type, s);
  1577                 if (s.isUnbound())
  1578                     return false;
  1580                 if (t.isExtendsBound()) {
  1581                     if (s.isExtendsBound())
  1582                         return !isCastableRecursive(t.type, upperBound(s));
  1583                     else if (s.isSuperBound())
  1584                         return notSoftSubtypeRecursive(lowerBound(s), t.type);
  1585                 } else if (t.isSuperBound()) {
  1586                     if (s.isExtendsBound())
  1587                         return notSoftSubtypeRecursive(t.type, upperBound(s));
  1589                 return false;
  1591         };
  1592     // </editor-fold>
  1594     // <editor-fold defaultstate="collapsed" desc="lowerBoundArgtypes">
  1595     /**
  1596      * Returns the lower bounds of the formals of a method.
  1597      */
  1598     public List<Type> lowerBoundArgtypes(Type t) {
  1599         return lowerBounds(t.getParameterTypes());
  1601     public List<Type> lowerBounds(List<Type> ts) {
  1602         return map(ts, lowerBoundMapping);
  1604     private final Mapping lowerBoundMapping = new Mapping("lowerBound") {
  1605             public Type apply(Type t) {
  1606                 return lowerBound(t);
  1608         };
  1609     // </editor-fold>
  1611     // <editor-fold defaultstate="collapsed" desc="notSoftSubtype">
  1612     /**
  1613      * This relation answers the question: is impossible that
  1614      * something of type `t' can be a subtype of `s'? This is
  1615      * different from the question "is `t' not a subtype of `s'?"
  1616      * when type variables are involved: Integer is not a subtype of T
  1617      * where {@code <T extends Number>} but it is not true that Integer cannot
  1618      * possibly be a subtype of T.
  1619      */
  1620     public boolean notSoftSubtype(Type t, Type s) {
  1621         if (t == s) return false;
  1622         if (t.tag == TYPEVAR) {
  1623             TypeVar tv = (TypeVar) t;
  1624             return !isCastable(tv.bound,
  1625                                relaxBound(s),
  1626                                noWarnings);
  1628         if (s.tag != WILDCARD)
  1629             s = upperBound(s);
  1631         return !isSubtype(t, relaxBound(s));
  1634     private Type relaxBound(Type t) {
  1635         if (t.tag == TYPEVAR) {
  1636             while (t.tag == TYPEVAR)
  1637                 t = t.getUpperBound();
  1638             t = rewriteQuantifiers(t, true, true);
  1640         return t;
  1642     // </editor-fold>
  1644     // <editor-fold defaultstate="collapsed" desc="isReifiable">
  1645     public boolean isReifiable(Type t) {
  1646         return isReifiable.visit(t);
  1648     // where
  1649         private UnaryVisitor<Boolean> isReifiable = new UnaryVisitor<Boolean>() {
  1651             public Boolean visitType(Type t, Void ignored) {
  1652                 return true;
  1655             @Override
  1656             public Boolean visitClassType(ClassType t, Void ignored) {
  1657                 if (t.isCompound())
  1658                     return false;
  1659                 else {
  1660                     if (!t.isParameterized())
  1661                         return true;
  1663                     for (Type param : t.allparams()) {
  1664                         if (!param.isUnbound())
  1665                             return false;
  1667                     return true;
  1671             @Override
  1672             public Boolean visitArrayType(ArrayType t, Void ignored) {
  1673                 return visit(t.elemtype);
  1676             @Override
  1677             public Boolean visitTypeVar(TypeVar t, Void ignored) {
  1678                 return false;
  1680         };
  1681     // </editor-fold>
  1683     // <editor-fold defaultstate="collapsed" desc="Array Utils">
  1684     public boolean isArray(Type t) {
  1685         while (t.tag == WILDCARD)
  1686             t = upperBound(t);
  1687         return t.tag == ARRAY;
  1690     /**
  1691      * The element type of an array.
  1692      */
  1693     public Type elemtype(Type t) {
  1694         switch (t.tag) {
  1695         case WILDCARD:
  1696             return elemtype(upperBound(t));
  1697         case ARRAY:
  1698             t = t.unannotatedType();
  1699             return ((ArrayType)t).elemtype;
  1700         case FORALL:
  1701             return elemtype(((ForAll)t).qtype);
  1702         case ERROR:
  1703             return t;
  1704         default:
  1705             return null;
  1709     public Type elemtypeOrType(Type t) {
  1710         Type elemtype = elemtype(t);
  1711         return elemtype != null ?
  1712             elemtype :
  1713             t;
  1716     /**
  1717      * Mapping to take element type of an arraytype
  1718      */
  1719     private Mapping elemTypeFun = new Mapping ("elemTypeFun") {
  1720         public Type apply(Type t) { return elemtype(t); }
  1721     };
  1723     /**
  1724      * The number of dimensions of an array type.
  1725      */
  1726     public int dimensions(Type t) {
  1727         int result = 0;
  1728         while (t.tag == ARRAY) {
  1729             result++;
  1730             t = elemtype(t);
  1732         return result;
  1735     /**
  1736      * Returns an ArrayType with the component type t
  1738      * @param t The component type of the ArrayType
  1739      * @return the ArrayType for the given component
  1740      */
  1741     public ArrayType makeArrayType(Type t) {
  1742         if (t.tag == VOID ||
  1743             t.tag == PACKAGE) {
  1744             Assert.error("Type t must not be a VOID or PACKAGE type, " + t.toString());
  1746         return new ArrayType(t, syms.arrayClass);
  1748     // </editor-fold>
  1750     // <editor-fold defaultstate="collapsed" desc="asSuper">
  1751     /**
  1752      * Return the (most specific) base type of t that starts with the
  1753      * given symbol.  If none exists, return null.
  1755      * @param t a type
  1756      * @param sym a symbol
  1757      */
  1758     public Type asSuper(Type t, Symbol sym) {
  1759         return asSuper.visit(t, sym);
  1761     // where
  1762         private SimpleVisitor<Type,Symbol> asSuper = new SimpleVisitor<Type,Symbol>() {
  1764             public Type visitType(Type t, Symbol sym) {
  1765                 return null;
  1768             @Override
  1769             public Type visitClassType(ClassType t, Symbol sym) {
  1770                 if (t.tsym == sym)
  1771                     return t;
  1773                 Type st = supertype(t);
  1774                 if (st.tag == CLASS || st.tag == TYPEVAR || st.tag == ERROR) {
  1775                     Type x = asSuper(st, sym);
  1776                     if (x != null)
  1777                         return x;
  1779                 if ((sym.flags() & INTERFACE) != 0) {
  1780                     for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
  1781                         Type x = asSuper(l.head, sym);
  1782                         if (x != null)
  1783                             return x;
  1786                 return null;
  1789             @Override
  1790             public Type visitArrayType(ArrayType t, Symbol sym) {
  1791                 return isSubtype(t, sym.type) ? sym.type : null;
  1794             @Override
  1795             public Type visitTypeVar(TypeVar t, Symbol sym) {
  1796                 if (t.tsym == sym)
  1797                     return t;
  1798                 else
  1799                     return asSuper(t.bound, sym);
  1802             @Override
  1803             public Type visitErrorType(ErrorType t, Symbol sym) {
  1804                 return t;
  1806         };
  1808     /**
  1809      * Return the base type of t or any of its outer types that starts
  1810      * with the given symbol.  If none exists, return null.
  1812      * @param t a type
  1813      * @param sym a symbol
  1814      */
  1815     public Type asOuterSuper(Type t, Symbol sym) {
  1816         switch (t.tag) {
  1817         case CLASS:
  1818             do {
  1819                 Type s = asSuper(t, sym);
  1820                 if (s != null) return s;
  1821                 t = t.getEnclosingType();
  1822             } while (t.tag == CLASS);
  1823             return null;
  1824         case ARRAY:
  1825             return isSubtype(t, sym.type) ? sym.type : null;
  1826         case TYPEVAR:
  1827             return asSuper(t, sym);
  1828         case ERROR:
  1829             return t;
  1830         default:
  1831             return null;
  1835     /**
  1836      * Return the base type of t or any of its enclosing types that
  1837      * starts with the given symbol.  If none exists, return null.
  1839      * @param t a type
  1840      * @param sym a symbol
  1841      */
  1842     public Type asEnclosingSuper(Type t, Symbol sym) {
  1843         switch (t.tag) {
  1844         case CLASS:
  1845             do {
  1846                 Type s = asSuper(t, sym);
  1847                 if (s != null) return s;
  1848                 Type outer = t.getEnclosingType();
  1849                 t = (outer.tag == CLASS) ? outer :
  1850                     (t.tsym.owner.enclClass() != null) ? t.tsym.owner.enclClass().type :
  1851                     Type.noType;
  1852             } while (t.tag == CLASS);
  1853             return null;
  1854         case ARRAY:
  1855             return isSubtype(t, sym.type) ? sym.type : null;
  1856         case TYPEVAR:
  1857             return asSuper(t, sym);
  1858         case ERROR:
  1859             return t;
  1860         default:
  1861             return null;
  1864     // </editor-fold>
  1866     // <editor-fold defaultstate="collapsed" desc="memberType">
  1867     /**
  1868      * The type of given symbol, seen as a member of t.
  1870      * @param t a type
  1871      * @param sym a symbol
  1872      */
  1873     public Type memberType(Type t, Symbol sym) {
  1874         return (sym.flags() & STATIC) != 0
  1875             ? sym.type
  1876             : memberType.visit(t, sym);
  1878     // where
  1879         private SimpleVisitor<Type,Symbol> memberType = new SimpleVisitor<Type,Symbol>() {
  1881             public Type visitType(Type t, Symbol sym) {
  1882                 return sym.type;
  1885             @Override
  1886             public Type visitWildcardType(WildcardType t, Symbol sym) {
  1887                 return memberType(upperBound(t), sym);
  1890             @Override
  1891             public Type visitClassType(ClassType t, Symbol sym) {
  1892                 Symbol owner = sym.owner;
  1893                 long flags = sym.flags();
  1894                 if (((flags & STATIC) == 0) && owner.type.isParameterized()) {
  1895                     Type base = asOuterSuper(t, owner);
  1896                     //if t is an intersection type T = CT & I1 & I2 ... & In
  1897                     //its supertypes CT, I1, ... In might contain wildcards
  1898                     //so we need to go through capture conversion
  1899                     base = t.isCompound() ? capture(base) : base;
  1900                     if (base != null) {
  1901                         List<Type> ownerParams = owner.type.allparams();
  1902                         List<Type> baseParams = base.allparams();
  1903                         if (ownerParams.nonEmpty()) {
  1904                             if (baseParams.isEmpty()) {
  1905                                 // then base is a raw type
  1906                                 return erasure(sym.type);
  1907                             } else {
  1908                                 return subst(sym.type, ownerParams, baseParams);
  1913                 return sym.type;
  1916             @Override
  1917             public Type visitTypeVar(TypeVar t, Symbol sym) {
  1918                 return memberType(t.bound, sym);
  1921             @Override
  1922             public Type visitErrorType(ErrorType t, Symbol sym) {
  1923                 return t;
  1925         };
  1926     // </editor-fold>
  1928     // <editor-fold defaultstate="collapsed" desc="isAssignable">
  1929     public boolean isAssignable(Type t, Type s) {
  1930         return isAssignable(t, s, noWarnings);
  1933     /**
  1934      * Is t assignable to s?<br>
  1935      * Equivalent to subtype except for constant values and raw
  1936      * types.<br>
  1937      * (not defined for Method and ForAll types)
  1938      */
  1939     public boolean isAssignable(Type t, Type s, Warner warn) {
  1940         if (t.tag == ERROR)
  1941             return true;
  1942         if (t.tag.isSubRangeOf(INT) && t.constValue() != null) {
  1943             int value = ((Number)t.constValue()).intValue();
  1944             switch (s.tag) {
  1945             case BYTE:
  1946                 if (Byte.MIN_VALUE <= value && value <= Byte.MAX_VALUE)
  1947                     return true;
  1948                 break;
  1949             case CHAR:
  1950                 if (Character.MIN_VALUE <= value && value <= Character.MAX_VALUE)
  1951                     return true;
  1952                 break;
  1953             case SHORT:
  1954                 if (Short.MIN_VALUE <= value && value <= Short.MAX_VALUE)
  1955                     return true;
  1956                 break;
  1957             case INT:
  1958                 return true;
  1959             case CLASS:
  1960                 switch (unboxedType(s).tag) {
  1961                 case BYTE:
  1962                 case CHAR:
  1963                 case SHORT:
  1964                     return isAssignable(t, unboxedType(s), warn);
  1966                 break;
  1969         return isConvertible(t, s, warn);
  1971     // </editor-fold>
  1973     // <editor-fold defaultstate="collapsed" desc="erasure">
  1974     /**
  1975      * The erasure of t {@code |t|} -- the type that results when all
  1976      * type parameters in t are deleted.
  1977      */
  1978     public Type erasure(Type t) {
  1979         return eraseNotNeeded(t)? t : erasure(t, false);
  1981     //where
  1982     private boolean eraseNotNeeded(Type t) {
  1983         // We don't want to erase primitive types and String type as that
  1984         // operation is idempotent. Also, erasing these could result in loss
  1985         // of information such as constant values attached to such types.
  1986         return (t.isPrimitive()) || (syms.stringType.tsym == t.tsym);
  1989     private Type erasure(Type t, boolean recurse) {
  1990         if (t.isPrimitive())
  1991             return t; /* fast special case */
  1992         else
  1993             return erasure.visit(t, recurse);
  1995     // where
  1996         private SimpleVisitor<Type, Boolean> erasure = new SimpleVisitor<Type, Boolean>() {
  1997             public Type visitType(Type t, Boolean recurse) {
  1998                 if (t.isPrimitive())
  1999                     return t; /*fast special case*/
  2000                 else
  2001                     return t.map(recurse ? erasureRecFun : erasureFun);
  2004             @Override
  2005             public Type visitWildcardType(WildcardType t, Boolean recurse) {
  2006                 return erasure(upperBound(t), recurse);
  2009             @Override
  2010             public Type visitClassType(ClassType t, Boolean recurse) {
  2011                 Type erased = t.tsym.erasure(Types.this);
  2012                 if (recurse) {
  2013                     erased = new ErasedClassType(erased.getEnclosingType(),erased.tsym);
  2015                 return erased;
  2018             @Override
  2019             public Type visitTypeVar(TypeVar t, Boolean recurse) {
  2020                 return erasure(t.bound, recurse);
  2023             @Override
  2024             public Type visitErrorType(ErrorType t, Boolean recurse) {
  2025                 return t;
  2028             @Override
  2029             public Type visitAnnotatedType(AnnotatedType t, Boolean recurse) {
  2030                 return new AnnotatedType(t.typeAnnotations, erasure(t.underlyingType, recurse));
  2032         };
  2034     private Mapping erasureFun = new Mapping ("erasure") {
  2035             public Type apply(Type t) { return erasure(t); }
  2036         };
  2038     private Mapping erasureRecFun = new Mapping ("erasureRecursive") {
  2039         public Type apply(Type t) { return erasureRecursive(t); }
  2040     };
  2042     public List<Type> erasure(List<Type> ts) {
  2043         return Type.map(ts, erasureFun);
  2046     public Type erasureRecursive(Type t) {
  2047         return erasure(t, true);
  2050     public List<Type> erasureRecursive(List<Type> ts) {
  2051         return Type.map(ts, erasureRecFun);
  2053     // </editor-fold>
  2055     // <editor-fold defaultstate="collapsed" desc="makeCompoundType">
  2056     /**
  2057      * Make a compound type from non-empty list of types
  2059      * @param bounds            the types from which the compound type is formed
  2060      * @param supertype         is objectType if all bounds are interfaces,
  2061      *                          null otherwise.
  2062      */
  2063     public Type makeCompoundType(List<Type> bounds) {
  2064         return makeCompoundType(bounds, bounds.head.tsym.isInterface());
  2066     public Type makeCompoundType(List<Type> bounds, boolean allInterfaces) {
  2067         Assert.check(bounds.nonEmpty());
  2068         Type firstExplicitBound = bounds.head;
  2069         if (allInterfaces) {
  2070             bounds = bounds.prepend(syms.objectType);
  2072         ClassSymbol bc =
  2073             new ClassSymbol(ABSTRACT|PUBLIC|SYNTHETIC|COMPOUND|ACYCLIC,
  2074                             Type.moreInfo
  2075                                 ? names.fromString(bounds.toString())
  2076                                 : names.empty,
  2077                             null,
  2078                             syms.noSymbol);
  2079         bc.type = new IntersectionClassType(bounds, bc, allInterfaces);
  2080         bc.erasure_field = (bounds.head.tag == TYPEVAR) ?
  2081                 syms.objectType : // error condition, recover
  2082                 erasure(firstExplicitBound);
  2083         bc.members_field = new Scope(bc);
  2084         return bc.type;
  2087     /**
  2088      * A convenience wrapper for {@link #makeCompoundType(List)}; the
  2089      * arguments are converted to a list and passed to the other
  2090      * method.  Note that this might cause a symbol completion.
  2091      * Hence, this version of makeCompoundType may not be called
  2092      * during a classfile read.
  2093      */
  2094     public Type makeCompoundType(Type bound1, Type bound2) {
  2095         return makeCompoundType(List.of(bound1, bound2));
  2097     // </editor-fold>
  2099     // <editor-fold defaultstate="collapsed" desc="supertype">
  2100     public Type supertype(Type t) {
  2101         return supertype.visit(t);
  2103     // where
  2104         private UnaryVisitor<Type> supertype = new UnaryVisitor<Type>() {
  2106             public Type visitType(Type t, Void ignored) {
  2107                 // A note on wildcards: there is no good way to
  2108                 // determine a supertype for a super bounded wildcard.
  2109                 return null;
  2112             @Override
  2113             public Type visitClassType(ClassType t, Void ignored) {
  2114                 if (t.supertype_field == null) {
  2115                     Type supertype = ((ClassSymbol)t.tsym).getSuperclass();
  2116                     // An interface has no superclass; its supertype is Object.
  2117                     if (t.isInterface())
  2118                         supertype = ((ClassType)t.tsym.type).supertype_field;
  2119                     if (t.supertype_field == null) {
  2120                         List<Type> actuals = classBound(t).allparams();
  2121                         List<Type> formals = t.tsym.type.allparams();
  2122                         if (t.hasErasedSupertypes()) {
  2123                             t.supertype_field = erasureRecursive(supertype);
  2124                         } else if (formals.nonEmpty()) {
  2125                             t.supertype_field = subst(supertype, formals, actuals);
  2127                         else {
  2128                             t.supertype_field = supertype;
  2132                 return t.supertype_field;
  2135             /**
  2136              * The supertype is always a class type. If the type
  2137              * variable's bounds start with a class type, this is also
  2138              * the supertype.  Otherwise, the supertype is
  2139              * java.lang.Object.
  2140              */
  2141             @Override
  2142             public Type visitTypeVar(TypeVar t, Void ignored) {
  2143                 if (t.bound.tag == TYPEVAR ||
  2144                     (!t.bound.isCompound() && !t.bound.isInterface())) {
  2145                     return t.bound;
  2146                 } else {
  2147                     return supertype(t.bound);
  2151             @Override
  2152             public Type visitArrayType(ArrayType t, Void ignored) {
  2153                 if (t.elemtype.isPrimitive() || isSameType(t.elemtype, syms.objectType))
  2154                     return arraySuperType();
  2155                 else
  2156                     return new ArrayType(supertype(t.elemtype), t.tsym);
  2159             @Override
  2160             public Type visitErrorType(ErrorType t, Void ignored) {
  2161                 return t;
  2163         };
  2164     // </editor-fold>
  2166     // <editor-fold defaultstate="collapsed" desc="interfaces">
  2167     /**
  2168      * Return the interfaces implemented by this class.
  2169      */
  2170     public List<Type> interfaces(Type t) {
  2171         return interfaces.visit(t);
  2173     // where
  2174         private UnaryVisitor<List<Type>> interfaces = new UnaryVisitor<List<Type>>() {
  2176             public List<Type> visitType(Type t, Void ignored) {
  2177                 return List.nil();
  2180             @Override
  2181             public List<Type> visitClassType(ClassType t, Void ignored) {
  2182                 if (t.interfaces_field == null) {
  2183                     List<Type> interfaces = ((ClassSymbol)t.tsym).getInterfaces();
  2184                     if (t.interfaces_field == null) {
  2185                         // If t.interfaces_field is null, then t must
  2186                         // be a parameterized type (not to be confused
  2187                         // with a generic type declaration).
  2188                         // Terminology:
  2189                         //    Parameterized type: List<String>
  2190                         //    Generic type declaration: class List<E> { ... }
  2191                         // So t corresponds to List<String> and
  2192                         // t.tsym.type corresponds to List<E>.
  2193                         // The reason t must be parameterized type is
  2194                         // that completion will happen as a side
  2195                         // effect of calling
  2196                         // ClassSymbol.getInterfaces.  Since
  2197                         // t.interfaces_field is null after
  2198                         // completion, we can assume that t is not the
  2199                         // type of a class/interface declaration.
  2200                         Assert.check(t != t.tsym.type, t);
  2201                         List<Type> actuals = t.allparams();
  2202                         List<Type> formals = t.tsym.type.allparams();
  2203                         if (t.hasErasedSupertypes()) {
  2204                             t.interfaces_field = erasureRecursive(interfaces);
  2205                         } else if (formals.nonEmpty()) {
  2206                             t.interfaces_field =
  2207                                 upperBounds(subst(interfaces, formals, actuals));
  2209                         else {
  2210                             t.interfaces_field = interfaces;
  2214                 return t.interfaces_field;
  2217             @Override
  2218             public List<Type> visitTypeVar(TypeVar t, Void ignored) {
  2219                 if (t.bound.isCompound())
  2220                     return interfaces(t.bound);
  2222                 if (t.bound.isInterface())
  2223                     return List.of(t.bound);
  2225                 return List.nil();
  2227         };
  2229     public boolean isDirectSuperInterface(TypeSymbol isym, TypeSymbol origin) {
  2230         for (Type i2 : interfaces(origin.type)) {
  2231             if (isym == i2.tsym) return true;
  2233         return false;
  2235     // </editor-fold>
  2237     // <editor-fold defaultstate="collapsed" desc="isDerivedRaw">
  2238     Map<Type,Boolean> isDerivedRawCache = new HashMap<Type,Boolean>();
  2240     public boolean isDerivedRaw(Type t) {
  2241         Boolean result = isDerivedRawCache.get(t);
  2242         if (result == null) {
  2243             result = isDerivedRawInternal(t);
  2244             isDerivedRawCache.put(t, result);
  2246         return result;
  2249     public boolean isDerivedRawInternal(Type t) {
  2250         if (t.isErroneous())
  2251             return false;
  2252         return
  2253             t.isRaw() ||
  2254             supertype(t) != null && isDerivedRaw(supertype(t)) ||
  2255             isDerivedRaw(interfaces(t));
  2258     public boolean isDerivedRaw(List<Type> ts) {
  2259         List<Type> l = ts;
  2260         while (l.nonEmpty() && !isDerivedRaw(l.head)) l = l.tail;
  2261         return l.nonEmpty();
  2263     // </editor-fold>
  2265     // <editor-fold defaultstate="collapsed" desc="setBounds">
  2266     /**
  2267      * Set the bounds field of the given type variable to reflect a
  2268      * (possibly multiple) list of bounds.
  2269      * @param t                 a type variable
  2270      * @param bounds            the bounds, must be nonempty
  2271      * @param supertype         is objectType if all bounds are interfaces,
  2272      *                          null otherwise.
  2273      */
  2274     public void setBounds(TypeVar t, List<Type> bounds) {
  2275         setBounds(t, bounds, bounds.head.tsym.isInterface());
  2278     /**
  2279      * Same as {@link #setBounds(Type.TypeVar,List,Type)}, except that
  2280      * third parameter is computed directly, as follows: if all
  2281      * all bounds are interface types, the computed supertype is Object,
  2282      * otherwise the supertype is simply left null (in this case, the supertype
  2283      * is assumed to be the head of the bound list passed as second argument).
  2284      * Note that this check might cause a symbol completion. Hence, this version of
  2285      * setBounds may not be called during a classfile read.
  2286      */
  2287     public void setBounds(TypeVar t, List<Type> bounds, boolean allInterfaces) {
  2288         t.bound = bounds.tail.isEmpty() ?
  2289                 bounds.head :
  2290                 makeCompoundType(bounds, allInterfaces);
  2291         t.rank_field = -1;
  2293     // </editor-fold>
  2295     // <editor-fold defaultstate="collapsed" desc="getBounds">
  2296     /**
  2297      * Return list of bounds of the given type variable.
  2298      */
  2299     public List<Type> getBounds(TypeVar t) {
  2300         if (t.bound.hasTag(NONE))
  2301             return List.nil();
  2302         else if (t.bound.isErroneous() || !t.bound.isCompound())
  2303             return List.of(t.bound);
  2304         else if ((erasure(t).tsym.flags() & INTERFACE) == 0)
  2305             return interfaces(t).prepend(supertype(t));
  2306         else
  2307             // No superclass was given in bounds.
  2308             // In this case, supertype is Object, erasure is first interface.
  2309             return interfaces(t);
  2311     // </editor-fold>
  2313     // <editor-fold defaultstate="collapsed" desc="classBound">
  2314     /**
  2315      * If the given type is a (possibly selected) type variable,
  2316      * return the bounding class of this type, otherwise return the
  2317      * type itself.
  2318      */
  2319     public Type classBound(Type t) {
  2320         return classBound.visit(t);
  2322     // where
  2323         private UnaryVisitor<Type> classBound = new UnaryVisitor<Type>() {
  2325             public Type visitType(Type t, Void ignored) {
  2326                 return t;
  2329             @Override
  2330             public Type visitClassType(ClassType t, Void ignored) {
  2331                 Type outer1 = classBound(t.getEnclosingType());
  2332                 if (outer1 != t.getEnclosingType())
  2333                     return new ClassType(outer1, t.getTypeArguments(), t.tsym);
  2334                 else
  2335                     return t;
  2338             @Override
  2339             public Type visitTypeVar(TypeVar t, Void ignored) {
  2340                 return classBound(supertype(t));
  2343             @Override
  2344             public Type visitErrorType(ErrorType t, Void ignored) {
  2345                 return t;
  2347         };
  2348     // </editor-fold>
  2350     // <editor-fold defaultstate="collapsed" desc="sub signature / override equivalence">
  2351     /**
  2352      * Returns true iff the first signature is a <em>sub
  2353      * signature</em> of the other.  This is <b>not</b> an equivalence
  2354      * relation.
  2356      * @jls section 8.4.2.
  2357      * @see #overrideEquivalent(Type t, Type s)
  2358      * @param t first signature (possibly raw).
  2359      * @param s second signature (could be subjected to erasure).
  2360      * @return true if t is a sub signature of s.
  2361      */
  2362     public boolean isSubSignature(Type t, Type s) {
  2363         return isSubSignature(t, s, true);
  2366     public boolean isSubSignature(Type t, Type s, boolean strict) {
  2367         return hasSameArgs(t, s, strict) || hasSameArgs(t, erasure(s), strict);
  2370     /**
  2371      * Returns true iff these signatures are related by <em>override
  2372      * equivalence</em>.  This is the natural extension of
  2373      * isSubSignature to an equivalence relation.
  2375      * @jls section 8.4.2.
  2376      * @see #isSubSignature(Type t, Type s)
  2377      * @param t a signature (possible raw, could be subjected to
  2378      * erasure).
  2379      * @param s a signature (possible raw, could be subjected to
  2380      * erasure).
  2381      * @return true if either argument is a sub signature of the other.
  2382      */
  2383     public boolean overrideEquivalent(Type t, Type s) {
  2384         return hasSameArgs(t, s) ||
  2385             hasSameArgs(t, erasure(s)) || hasSameArgs(erasure(t), s);
  2388     public boolean overridesObjectMethod(TypeSymbol origin, Symbol msym) {
  2389         for (Scope.Entry e = syms.objectType.tsym.members().lookup(msym.name) ; e.scope != null ; e = e.next()) {
  2390             if (msym.overrides(e.sym, origin, Types.this, true)) {
  2391                 return true;
  2394         return false;
  2397     // <editor-fold defaultstate="collapsed" desc="Determining method implementation in given site">
  2398     class ImplementationCache {
  2400         private WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>> _map =
  2401                 new WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>>();
  2403         class Entry {
  2404             final MethodSymbol cachedImpl;
  2405             final Filter<Symbol> implFilter;
  2406             final boolean checkResult;
  2407             final int prevMark;
  2409             public Entry(MethodSymbol cachedImpl,
  2410                     Filter<Symbol> scopeFilter,
  2411                     boolean checkResult,
  2412                     int prevMark) {
  2413                 this.cachedImpl = cachedImpl;
  2414                 this.implFilter = scopeFilter;
  2415                 this.checkResult = checkResult;
  2416                 this.prevMark = prevMark;
  2419             boolean matches(Filter<Symbol> scopeFilter, boolean checkResult, int mark) {
  2420                 return this.implFilter == scopeFilter &&
  2421                         this.checkResult == checkResult &&
  2422                         this.prevMark == mark;
  2426         MethodSymbol get(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
  2427             SoftReference<Map<TypeSymbol, Entry>> ref_cache = _map.get(ms);
  2428             Map<TypeSymbol, Entry> cache = ref_cache != null ? ref_cache.get() : null;
  2429             if (cache == null) {
  2430                 cache = new HashMap<TypeSymbol, Entry>();
  2431                 _map.put(ms, new SoftReference<Map<TypeSymbol, Entry>>(cache));
  2433             Entry e = cache.get(origin);
  2434             CompoundScope members = membersClosure(origin.type, true);
  2435             if (e == null ||
  2436                     !e.matches(implFilter, checkResult, members.getMark())) {
  2437                 MethodSymbol impl = implementationInternal(ms, origin, checkResult, implFilter);
  2438                 cache.put(origin, new Entry(impl, implFilter, checkResult, members.getMark()));
  2439                 return impl;
  2441             else {
  2442                 return e.cachedImpl;
  2446         private MethodSymbol implementationInternal(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
  2447             for (Type t = origin.type; t.tag == CLASS || t.tag == TYPEVAR; t = supertype(t)) {
  2448                 while (t.tag == TYPEVAR)
  2449                     t = t.getUpperBound();
  2450                 TypeSymbol c = t.tsym;
  2451                 for (Scope.Entry e = c.members().lookup(ms.name, implFilter);
  2452                      e.scope != null;
  2453                      e = e.next(implFilter)) {
  2454                     if (e.sym != null &&
  2455                              e.sym.overrides(ms, origin, Types.this, checkResult))
  2456                         return (MethodSymbol)e.sym;
  2459             return null;
  2463     private ImplementationCache implCache = new ImplementationCache();
  2465     public MethodSymbol implementation(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
  2466         return implCache.get(ms, origin, checkResult, implFilter);
  2468     // </editor-fold>
  2470     // <editor-fold defaultstate="collapsed" desc="compute transitive closure of all members in given site">
  2471     class MembersClosureCache extends SimpleVisitor<CompoundScope, Boolean> {
  2473         private WeakHashMap<TypeSymbol, Entry> _map =
  2474                 new WeakHashMap<TypeSymbol, Entry>();
  2476         class Entry {
  2477             final boolean skipInterfaces;
  2478             final CompoundScope compoundScope;
  2480             public Entry(boolean skipInterfaces, CompoundScope compoundScope) {
  2481                 this.skipInterfaces = skipInterfaces;
  2482                 this.compoundScope = compoundScope;
  2485             boolean matches(boolean skipInterfaces) {
  2486                 return this.skipInterfaces == skipInterfaces;
  2490         List<TypeSymbol> seenTypes = List.nil();
  2492         /** members closure visitor methods **/
  2494         public CompoundScope visitType(Type t, Boolean skipInterface) {
  2495             return null;
  2498         @Override
  2499         public CompoundScope visitClassType(ClassType t, Boolean skipInterface) {
  2500             if (seenTypes.contains(t.tsym)) {
  2501                 //this is possible when an interface is implemented in multiple
  2502                 //superclasses, or when a classs hierarchy is circular - in such
  2503                 //cases we don't need to recurse (empty scope is returned)
  2504                 return new CompoundScope(t.tsym);
  2506             try {
  2507                 seenTypes = seenTypes.prepend(t.tsym);
  2508                 ClassSymbol csym = (ClassSymbol)t.tsym;
  2509                 Entry e = _map.get(csym);
  2510                 if (e == null || !e.matches(skipInterface)) {
  2511                     CompoundScope membersClosure = new CompoundScope(csym);
  2512                     if (!skipInterface) {
  2513                         for (Type i : interfaces(t)) {
  2514                             membersClosure.addSubScope(visit(i, skipInterface));
  2517                     membersClosure.addSubScope(visit(supertype(t), skipInterface));
  2518                     membersClosure.addSubScope(csym.members());
  2519                     e = new Entry(skipInterface, membersClosure);
  2520                     _map.put(csym, e);
  2522                 return e.compoundScope;
  2524             finally {
  2525                 seenTypes = seenTypes.tail;
  2529         @Override
  2530         public CompoundScope visitTypeVar(TypeVar t, Boolean skipInterface) {
  2531             return visit(t.getUpperBound(), skipInterface);
  2535     private MembersClosureCache membersCache = new MembersClosureCache();
  2537     public CompoundScope membersClosure(Type site, boolean skipInterface) {
  2538         return membersCache.visit(site, skipInterface);
  2540     // </editor-fold>
  2543     //where
  2544     public List<MethodSymbol> interfaceCandidates(Type site, MethodSymbol ms) {
  2545         Filter<Symbol> filter = new MethodFilter(ms, site);
  2546         List<MethodSymbol> candidates = List.nil();
  2547         for (Symbol s : membersClosure(site, false).getElements(filter)) {
  2548             if (!site.tsym.isInterface() && !s.owner.isInterface()) {
  2549                 return List.of((MethodSymbol)s);
  2550             } else if (!candidates.contains(s)) {
  2551                 candidates = candidates.prepend((MethodSymbol)s);
  2554         return prune(candidates, ownerComparator);
  2557     public List<MethodSymbol> prune(List<MethodSymbol> methods, Comparator<MethodSymbol> cmp) {
  2558         ListBuffer<MethodSymbol> methodsMin = ListBuffer.lb();
  2559         for (MethodSymbol m1 : methods) {
  2560             boolean isMin_m1 = true;
  2561             for (MethodSymbol m2 : methods) {
  2562                 if (m1 == m2) continue;
  2563                 if (cmp.compare(m2, m1) < 0) {
  2564                     isMin_m1 = false;
  2565                     break;
  2568             if (isMin_m1)
  2569                 methodsMin.append(m1);
  2571         return methodsMin.toList();
  2574     Comparator<MethodSymbol> ownerComparator = new Comparator<MethodSymbol>() {
  2575         public int compare(MethodSymbol s1, MethodSymbol s2) {
  2576             return s1.owner.isSubClass(s2.owner, Types.this) ? -1 : 1;
  2578     };
  2579     // where
  2580             private class MethodFilter implements Filter<Symbol> {
  2582                 Symbol msym;
  2583                 Type site;
  2585                 MethodFilter(Symbol msym, Type site) {
  2586                     this.msym = msym;
  2587                     this.site = site;
  2590                 public boolean accepts(Symbol s) {
  2591                     return s.kind == Kinds.MTH &&
  2592                             s.name == msym.name &&
  2593                             s.isInheritedIn(site.tsym, Types.this) &&
  2594                             overrideEquivalent(memberType(site, s), memberType(site, msym));
  2596             };
  2597     // </editor-fold>
  2599     /**
  2600      * Does t have the same arguments as s?  It is assumed that both
  2601      * types are (possibly polymorphic) method types.  Monomorphic
  2602      * method types "have the same arguments", if their argument lists
  2603      * are equal.  Polymorphic method types "have the same arguments",
  2604      * if they have the same arguments after renaming all type
  2605      * variables of one to corresponding type variables in the other,
  2606      * where correspondence is by position in the type parameter list.
  2607      */
  2608     public boolean hasSameArgs(Type t, Type s) {
  2609         return hasSameArgs(t, s, true);
  2612     public boolean hasSameArgs(Type t, Type s, boolean strict) {
  2613         return hasSameArgs(t, s, strict ? hasSameArgs_strict : hasSameArgs_nonstrict);
  2616     private boolean hasSameArgs(Type t, Type s, TypeRelation hasSameArgs) {
  2617         return hasSameArgs.visit(t, s);
  2619     // where
  2620         private class HasSameArgs extends TypeRelation {
  2622             boolean strict;
  2624             public HasSameArgs(boolean strict) {
  2625                 this.strict = strict;
  2628             public Boolean visitType(Type t, Type s) {
  2629                 throw new AssertionError();
  2632             @Override
  2633             public Boolean visitMethodType(MethodType t, Type s) {
  2634                 return s.tag == METHOD
  2635                     && containsTypeEquivalent(t.argtypes, s.getParameterTypes());
  2638             @Override
  2639             public Boolean visitForAll(ForAll t, Type s) {
  2640                 if (s.tag != FORALL)
  2641                     return strict ? false : visitMethodType(t.asMethodType(), s);
  2643                 ForAll forAll = (ForAll)s;
  2644                 return hasSameBounds(t, forAll)
  2645                     && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
  2648             @Override
  2649             public Boolean visitErrorType(ErrorType t, Type s) {
  2650                 return false;
  2652         };
  2654         TypeRelation hasSameArgs_strict = new HasSameArgs(true);
  2655         TypeRelation hasSameArgs_nonstrict = new HasSameArgs(false);
  2657     // </editor-fold>
  2659     // <editor-fold defaultstate="collapsed" desc="subst">
  2660     public List<Type> subst(List<Type> ts,
  2661                             List<Type> from,
  2662                             List<Type> to) {
  2663         return new Subst(from, to).subst(ts);
  2666     /**
  2667      * Substitute all occurrences of a type in `from' with the
  2668      * corresponding type in `to' in 't'. Match lists `from' and `to'
  2669      * from the right: If lists have different length, discard leading
  2670      * elements of the longer list.
  2671      */
  2672     public Type subst(Type t, List<Type> from, List<Type> to) {
  2673         return new Subst(from, to).subst(t);
  2676     private class Subst extends UnaryVisitor<Type> {
  2677         List<Type> from;
  2678         List<Type> to;
  2680         public Subst(List<Type> from, List<Type> to) {
  2681             int fromLength = from.length();
  2682             int toLength = to.length();
  2683             while (fromLength > toLength) {
  2684                 fromLength--;
  2685                 from = from.tail;
  2687             while (fromLength < toLength) {
  2688                 toLength--;
  2689                 to = to.tail;
  2691             this.from = from;
  2692             this.to = to;
  2695         Type subst(Type t) {
  2696             if (from.tail == null)
  2697                 return t;
  2698             else
  2699                 return visit(t);
  2702         List<Type> subst(List<Type> ts) {
  2703             if (from.tail == null)
  2704                 return ts;
  2705             boolean wild = false;
  2706             if (ts.nonEmpty() && from.nonEmpty()) {
  2707                 Type head1 = subst(ts.head);
  2708                 List<Type> tail1 = subst(ts.tail);
  2709                 if (head1 != ts.head || tail1 != ts.tail)
  2710                     return tail1.prepend(head1);
  2712             return ts;
  2715         public Type visitType(Type t, Void ignored) {
  2716             return t;
  2719         @Override
  2720         public Type visitMethodType(MethodType t, Void ignored) {
  2721             List<Type> argtypes = subst(t.argtypes);
  2722             Type restype = subst(t.restype);
  2723             List<Type> thrown = subst(t.thrown);
  2724             if (argtypes == t.argtypes &&
  2725                 restype == t.restype &&
  2726                 thrown == t.thrown)
  2727                 return t;
  2728             else
  2729                 return new MethodType(argtypes, restype, thrown, t.tsym);
  2732         @Override
  2733         public Type visitTypeVar(TypeVar t, Void ignored) {
  2734             for (List<Type> from = this.from, to = this.to;
  2735                  from.nonEmpty();
  2736                  from = from.tail, to = to.tail) {
  2737                 if (t == from.head) {
  2738                     return to.head.withTypeVar(t);
  2741             return t;
  2744         @Override
  2745         public Type visitClassType(ClassType t, Void ignored) {
  2746             if (!t.isCompound()) {
  2747                 List<Type> typarams = t.getTypeArguments();
  2748                 List<Type> typarams1 = subst(typarams);
  2749                 Type outer = t.getEnclosingType();
  2750                 Type outer1 = subst(outer);
  2751                 if (typarams1 == typarams && outer1 == outer)
  2752                     return t;
  2753                 else
  2754                     return new ClassType(outer1, typarams1, t.tsym);
  2755             } else {
  2756                 Type st = subst(supertype(t));
  2757                 List<Type> is = upperBounds(subst(interfaces(t)));
  2758                 if (st == supertype(t) && is == interfaces(t))
  2759                     return t;
  2760                 else
  2761                     return makeCompoundType(is.prepend(st));
  2765         @Override
  2766         public Type visitWildcardType(WildcardType t, Void ignored) {
  2767             Type bound = t.type;
  2768             if (t.kind != BoundKind.UNBOUND)
  2769                 bound = subst(bound);
  2770             if (bound == t.type) {
  2771                 return t;
  2772             } else {
  2773                 if (t.isExtendsBound() && bound.isExtendsBound())
  2774                     bound = upperBound(bound);
  2775                 return new WildcardType(bound, t.kind, syms.boundClass, t.bound);
  2779         @Override
  2780         public Type visitArrayType(ArrayType t, Void ignored) {
  2781             Type elemtype = subst(t.elemtype);
  2782             if (elemtype == t.elemtype)
  2783                 return t;
  2784             else
  2785                 return new ArrayType(upperBound(elemtype), t.tsym);
  2788         @Override
  2789         public Type visitForAll(ForAll t, Void ignored) {
  2790             if (Type.containsAny(to, t.tvars)) {
  2791                 //perform alpha-renaming of free-variables in 't'
  2792                 //if 'to' types contain variables that are free in 't'
  2793                 List<Type> freevars = newInstances(t.tvars);
  2794                 t = new ForAll(freevars,
  2795                         Types.this.subst(t.qtype, t.tvars, freevars));
  2797             List<Type> tvars1 = substBounds(t.tvars, from, to);
  2798             Type qtype1 = subst(t.qtype);
  2799             if (tvars1 == t.tvars && qtype1 == t.qtype) {
  2800                 return t;
  2801             } else if (tvars1 == t.tvars) {
  2802                 return new ForAll(tvars1, qtype1);
  2803             } else {
  2804                 return new ForAll(tvars1, Types.this.subst(qtype1, t.tvars, tvars1));
  2808         @Override
  2809         public Type visitErrorType(ErrorType t, Void ignored) {
  2810             return t;
  2814     public List<Type> substBounds(List<Type> tvars,
  2815                                   List<Type> from,
  2816                                   List<Type> to) {
  2817         if (tvars.isEmpty())
  2818             return tvars;
  2819         ListBuffer<Type> newBoundsBuf = lb();
  2820         boolean changed = false;
  2821         // calculate new bounds
  2822         for (Type t : tvars) {
  2823             TypeVar tv = (TypeVar) t;
  2824             Type bound = subst(tv.bound, from, to);
  2825             if (bound != tv.bound)
  2826                 changed = true;
  2827             newBoundsBuf.append(bound);
  2829         if (!changed)
  2830             return tvars;
  2831         ListBuffer<Type> newTvars = lb();
  2832         // create new type variables without bounds
  2833         for (Type t : tvars) {
  2834             newTvars.append(new TypeVar(t.tsym, null, syms.botType));
  2836         // the new bounds should use the new type variables in place
  2837         // of the old
  2838         List<Type> newBounds = newBoundsBuf.toList();
  2839         from = tvars;
  2840         to = newTvars.toList();
  2841         for (; !newBounds.isEmpty(); newBounds = newBounds.tail) {
  2842             newBounds.head = subst(newBounds.head, from, to);
  2844         newBounds = newBoundsBuf.toList();
  2845         // set the bounds of new type variables to the new bounds
  2846         for (Type t : newTvars.toList()) {
  2847             TypeVar tv = (TypeVar) t;
  2848             tv.bound = newBounds.head;
  2849             newBounds = newBounds.tail;
  2851         return newTvars.toList();
  2854     public TypeVar substBound(TypeVar t, List<Type> from, List<Type> to) {
  2855         Type bound1 = subst(t.bound, from, to);
  2856         if (bound1 == t.bound)
  2857             return t;
  2858         else {
  2859             // create new type variable without bounds
  2860             TypeVar tv = new TypeVar(t.tsym, null, syms.botType);
  2861             // the new bound should use the new type variable in place
  2862             // of the old
  2863             tv.bound = subst(bound1, List.<Type>of(t), List.<Type>of(tv));
  2864             return tv;
  2867     // </editor-fold>
  2869     // <editor-fold defaultstate="collapsed" desc="hasSameBounds">
  2870     /**
  2871      * Does t have the same bounds for quantified variables as s?
  2872      */
  2873     boolean hasSameBounds(ForAll t, ForAll s) {
  2874         List<Type> l1 = t.tvars;
  2875         List<Type> l2 = s.tvars;
  2876         while (l1.nonEmpty() && l2.nonEmpty() &&
  2877                isSameType(l1.head.getUpperBound(),
  2878                           subst(l2.head.getUpperBound(),
  2879                                 s.tvars,
  2880                                 t.tvars))) {
  2881             l1 = l1.tail;
  2882             l2 = l2.tail;
  2884         return l1.isEmpty() && l2.isEmpty();
  2886     // </editor-fold>
  2888     // <editor-fold defaultstate="collapsed" desc="newInstances">
  2889     /** Create new vector of type variables from list of variables
  2890      *  changing all recursive bounds from old to new list.
  2891      */
  2892     public List<Type> newInstances(List<Type> tvars) {
  2893         List<Type> tvars1 = Type.map(tvars, newInstanceFun);
  2894         for (List<Type> l = tvars1; l.nonEmpty(); l = l.tail) {
  2895             TypeVar tv = (TypeVar) l.head;
  2896             tv.bound = subst(tv.bound, tvars, tvars1);
  2898         return tvars1;
  2900     private static final Mapping newInstanceFun = new Mapping("newInstanceFun") {
  2901             public Type apply(Type t) { return new TypeVar(t.tsym, t.getUpperBound(), t.getLowerBound()); }
  2902         };
  2903     // </editor-fold>
  2905     public Type createMethodTypeWithParameters(Type original, List<Type> newParams) {
  2906         return original.accept(methodWithParameters, newParams);
  2908     // where
  2909         private final MapVisitor<List<Type>> methodWithParameters = new MapVisitor<List<Type>>() {
  2910             public Type visitType(Type t, List<Type> newParams) {
  2911                 throw new IllegalArgumentException("Not a method type: " + t);
  2913             public Type visitMethodType(MethodType t, List<Type> newParams) {
  2914                 return new MethodType(newParams, t.restype, t.thrown, t.tsym);
  2916             public Type visitForAll(ForAll t, List<Type> newParams) {
  2917                 return new ForAll(t.tvars, t.qtype.accept(this, newParams));
  2919         };
  2921     public Type createMethodTypeWithThrown(Type original, List<Type> newThrown) {
  2922         return original.accept(methodWithThrown, newThrown);
  2924     // where
  2925         private final MapVisitor<List<Type>> methodWithThrown = new MapVisitor<List<Type>>() {
  2926             public Type visitType(Type t, List<Type> newThrown) {
  2927                 throw new IllegalArgumentException("Not a method type: " + t);
  2929             public Type visitMethodType(MethodType t, List<Type> newThrown) {
  2930                 return new MethodType(t.argtypes, t.restype, newThrown, t.tsym);
  2932             public Type visitForAll(ForAll t, List<Type> newThrown) {
  2933                 return new ForAll(t.tvars, t.qtype.accept(this, newThrown));
  2935         };
  2937     public Type createMethodTypeWithReturn(Type original, Type newReturn) {
  2938         return original.accept(methodWithReturn, newReturn);
  2940     // where
  2941         private final MapVisitor<Type> methodWithReturn = new MapVisitor<Type>() {
  2942             public Type visitType(Type t, Type newReturn) {
  2943                 throw new IllegalArgumentException("Not a method type: " + t);
  2945             public Type visitMethodType(MethodType t, Type newReturn) {
  2946                 return new MethodType(t.argtypes, newReturn, t.thrown, t.tsym);
  2948             public Type visitForAll(ForAll t, Type newReturn) {
  2949                 return new ForAll(t.tvars, t.qtype.accept(this, newReturn));
  2951         };
  2953     // <editor-fold defaultstate="collapsed" desc="createErrorType">
  2954     public Type createErrorType(Type originalType) {
  2955         return new ErrorType(originalType, syms.errSymbol);
  2958     public Type createErrorType(ClassSymbol c, Type originalType) {
  2959         return new ErrorType(c, originalType);
  2962     public Type createErrorType(Name name, TypeSymbol container, Type originalType) {
  2963         return new ErrorType(name, container, originalType);
  2965     // </editor-fold>
  2967     // <editor-fold defaultstate="collapsed" desc="rank">
  2968     /**
  2969      * The rank of a class is the length of the longest path between
  2970      * the class and java.lang.Object in the class inheritance
  2971      * graph. Undefined for all but reference types.
  2972      */
  2973     public int rank(Type t) {
  2974         t = t.unannotatedType();
  2975         switch(t.tag) {
  2976         case CLASS: {
  2977             ClassType cls = (ClassType)t;
  2978             if (cls.rank_field < 0) {
  2979                 Name fullname = cls.tsym.getQualifiedName();
  2980                 if (fullname == names.java_lang_Object)
  2981                     cls.rank_field = 0;
  2982                 else {
  2983                     int r = rank(supertype(cls));
  2984                     for (List<Type> l = interfaces(cls);
  2985                          l.nonEmpty();
  2986                          l = l.tail) {
  2987                         if (rank(l.head) > r)
  2988                             r = rank(l.head);
  2990                     cls.rank_field = r + 1;
  2993             return cls.rank_field;
  2995         case TYPEVAR: {
  2996             TypeVar tvar = (TypeVar)t;
  2997             if (tvar.rank_field < 0) {
  2998                 int r = rank(supertype(tvar));
  2999                 for (List<Type> l = interfaces(tvar);
  3000                      l.nonEmpty();
  3001                      l = l.tail) {
  3002                     if (rank(l.head) > r) r = rank(l.head);
  3004                 tvar.rank_field = r + 1;
  3006             return tvar.rank_field;
  3008         case ERROR:
  3009             return 0;
  3010         default:
  3011             throw new AssertionError();
  3014     // </editor-fold>
  3016     /**
  3017      * Helper method for generating a string representation of a given type
  3018      * accordingly to a given locale
  3019      */
  3020     public String toString(Type t, Locale locale) {
  3021         return Printer.createStandardPrinter(messages).visit(t, locale);
  3024     /**
  3025      * Helper method for generating a string representation of a given type
  3026      * accordingly to a given locale
  3027      */
  3028     public String toString(Symbol t, Locale locale) {
  3029         return Printer.createStandardPrinter(messages).visit(t, locale);
  3032     // <editor-fold defaultstate="collapsed" desc="toString">
  3033     /**
  3034      * This toString is slightly more descriptive than the one on Type.
  3036      * @deprecated Types.toString(Type t, Locale l) provides better support
  3037      * for localization
  3038      */
  3039     @Deprecated
  3040     public String toString(Type t) {
  3041         if (t.tag == FORALL) {
  3042             ForAll forAll = (ForAll)t;
  3043             return typaramsString(forAll.tvars) + forAll.qtype;
  3045         return "" + t;
  3047     // where
  3048         private String typaramsString(List<Type> tvars) {
  3049             StringBuilder s = new StringBuilder();
  3050             s.append('<');
  3051             boolean first = true;
  3052             for (Type t : tvars) {
  3053                 if (!first) s.append(", ");
  3054                 first = false;
  3055                 appendTyparamString(((TypeVar)t), s);
  3057             s.append('>');
  3058             return s.toString();
  3060         private void appendTyparamString(TypeVar t, StringBuilder buf) {
  3061             buf.append(t);
  3062             if (t.bound == null ||
  3063                 t.bound.tsym.getQualifiedName() == names.java_lang_Object)
  3064                 return;
  3065             buf.append(" extends "); // Java syntax; no need for i18n
  3066             Type bound = t.bound;
  3067             if (!bound.isCompound()) {
  3068                 buf.append(bound);
  3069             } else if ((erasure(t).tsym.flags() & INTERFACE) == 0) {
  3070                 buf.append(supertype(t));
  3071                 for (Type intf : interfaces(t)) {
  3072                     buf.append('&');
  3073                     buf.append(intf);
  3075             } else {
  3076                 // No superclass was given in bounds.
  3077                 // In this case, supertype is Object, erasure is first interface.
  3078                 boolean first = true;
  3079                 for (Type intf : interfaces(t)) {
  3080                     if (!first) buf.append('&');
  3081                     first = false;
  3082                     buf.append(intf);
  3086     // </editor-fold>
  3088     // <editor-fold defaultstate="collapsed" desc="Determining least upper bounds of types">
  3089     /**
  3090      * A cache for closures.
  3092      * <p>A closure is a list of all the supertypes and interfaces of
  3093      * a class or interface type, ordered by ClassSymbol.precedes
  3094      * (that is, subclasses come first, arbitrary but fixed
  3095      * otherwise).
  3096      */
  3097     private Map<Type,List<Type>> closureCache = new HashMap<Type,List<Type>>();
  3099     /**
  3100      * Returns the closure of a class or interface type.
  3101      */
  3102     public List<Type> closure(Type t) {
  3103         List<Type> cl = closureCache.get(t);
  3104         if (cl == null) {
  3105             Type st = supertype(t);
  3106             if (!t.isCompound()) {
  3107                 if (st.tag == CLASS) {
  3108                     cl = insert(closure(st), t);
  3109                 } else if (st.tag == TYPEVAR) {
  3110                     cl = closure(st).prepend(t);
  3111                 } else {
  3112                     cl = List.of(t);
  3114             } else {
  3115                 cl = closure(supertype(t));
  3117             for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail)
  3118                 cl = union(cl, closure(l.head));
  3119             closureCache.put(t, cl);
  3121         return cl;
  3124     /**
  3125      * Insert a type in a closure
  3126      */
  3127     public List<Type> insert(List<Type> cl, Type t) {
  3128         if (cl.isEmpty() || t.tsym.precedes(cl.head.tsym, this)) {
  3129             return cl.prepend(t);
  3130         } else if (cl.head.tsym.precedes(t.tsym, this)) {
  3131             return insert(cl.tail, t).prepend(cl.head);
  3132         } else {
  3133             return cl;
  3137     /**
  3138      * Form the union of two closures
  3139      */
  3140     public List<Type> union(List<Type> cl1, List<Type> cl2) {
  3141         if (cl1.isEmpty()) {
  3142             return cl2;
  3143         } else if (cl2.isEmpty()) {
  3144             return cl1;
  3145         } else if (cl1.head.tsym.precedes(cl2.head.tsym, this)) {
  3146             return union(cl1.tail, cl2).prepend(cl1.head);
  3147         } else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) {
  3148             return union(cl1, cl2.tail).prepend(cl2.head);
  3149         } else {
  3150             return union(cl1.tail, cl2.tail).prepend(cl1.head);
  3154     /**
  3155      * Intersect two closures
  3156      */
  3157     public List<Type> intersect(List<Type> cl1, List<Type> cl2) {
  3158         if (cl1 == cl2)
  3159             return cl1;
  3160         if (cl1.isEmpty() || cl2.isEmpty())
  3161             return List.nil();
  3162         if (cl1.head.tsym.precedes(cl2.head.tsym, this))
  3163             return intersect(cl1.tail, cl2);
  3164         if (cl2.head.tsym.precedes(cl1.head.tsym, this))
  3165             return intersect(cl1, cl2.tail);
  3166         if (isSameType(cl1.head, cl2.head))
  3167             return intersect(cl1.tail, cl2.tail).prepend(cl1.head);
  3168         if (cl1.head.tsym == cl2.head.tsym &&
  3169             cl1.head.tag == CLASS && cl2.head.tag == CLASS) {
  3170             if (cl1.head.isParameterized() && cl2.head.isParameterized()) {
  3171                 Type merge = merge(cl1.head,cl2.head);
  3172                 return intersect(cl1.tail, cl2.tail).prepend(merge);
  3174             if (cl1.head.isRaw() || cl2.head.isRaw())
  3175                 return intersect(cl1.tail, cl2.tail).prepend(erasure(cl1.head));
  3177         return intersect(cl1.tail, cl2.tail);
  3179     // where
  3180         class TypePair {
  3181             final Type t1;
  3182             final Type t2;
  3183             TypePair(Type t1, Type t2) {
  3184                 this.t1 = t1;
  3185                 this.t2 = t2;
  3187             @Override
  3188             public int hashCode() {
  3189                 return 127 * Types.this.hashCode(t1) + Types.this.hashCode(t2);
  3191             @Override
  3192             public boolean equals(Object obj) {
  3193                 if (!(obj instanceof TypePair))
  3194                     return false;
  3195                 TypePair typePair = (TypePair)obj;
  3196                 return isSameType(t1, typePair.t1)
  3197                     && isSameType(t2, typePair.t2);
  3200         Set<TypePair> mergeCache = new HashSet<TypePair>();
  3201         private Type merge(Type c1, Type c2) {
  3202             ClassType class1 = (ClassType) c1;
  3203             List<Type> act1 = class1.getTypeArguments();
  3204             ClassType class2 = (ClassType) c2;
  3205             List<Type> act2 = class2.getTypeArguments();
  3206             ListBuffer<Type> merged = new ListBuffer<Type>();
  3207             List<Type> typarams = class1.tsym.type.getTypeArguments();
  3209             while (act1.nonEmpty() && act2.nonEmpty() && typarams.nonEmpty()) {
  3210                 if (containsType(act1.head, act2.head)) {
  3211                     merged.append(act1.head);
  3212                 } else if (containsType(act2.head, act1.head)) {
  3213                     merged.append(act2.head);
  3214                 } else {
  3215                     TypePair pair = new TypePair(c1, c2);
  3216                     Type m;
  3217                     if (mergeCache.add(pair)) {
  3218                         m = new WildcardType(lub(upperBound(act1.head),
  3219                                                  upperBound(act2.head)),
  3220                                              BoundKind.EXTENDS,
  3221                                              syms.boundClass);
  3222                         mergeCache.remove(pair);
  3223                     } else {
  3224                         m = new WildcardType(syms.objectType,
  3225                                              BoundKind.UNBOUND,
  3226                                              syms.boundClass);
  3228                     merged.append(m.withTypeVar(typarams.head));
  3230                 act1 = act1.tail;
  3231                 act2 = act2.tail;
  3232                 typarams = typarams.tail;
  3234             Assert.check(act1.isEmpty() && act2.isEmpty() && typarams.isEmpty());
  3235             return new ClassType(class1.getEnclosingType(), merged.toList(), class1.tsym);
  3238     /**
  3239      * Return the minimum type of a closure, a compound type if no
  3240      * unique minimum exists.
  3241      */
  3242     private Type compoundMin(List<Type> cl) {
  3243         if (cl.isEmpty()) return syms.objectType;
  3244         List<Type> compound = closureMin(cl);
  3245         if (compound.isEmpty())
  3246             return null;
  3247         else if (compound.tail.isEmpty())
  3248             return compound.head;
  3249         else
  3250             return makeCompoundType(compound);
  3253     /**
  3254      * Return the minimum types of a closure, suitable for computing
  3255      * compoundMin or glb.
  3256      */
  3257     private List<Type> closureMin(List<Type> cl) {
  3258         ListBuffer<Type> classes = lb();
  3259         ListBuffer<Type> interfaces = lb();
  3260         while (!cl.isEmpty()) {
  3261             Type current = cl.head;
  3262             if (current.isInterface())
  3263                 interfaces.append(current);
  3264             else
  3265                 classes.append(current);
  3266             ListBuffer<Type> candidates = lb();
  3267             for (Type t : cl.tail) {
  3268                 if (!isSubtypeNoCapture(current, t))
  3269                     candidates.append(t);
  3271             cl = candidates.toList();
  3273         return classes.appendList(interfaces).toList();
  3276     /**
  3277      * Return the least upper bound of pair of types.  if the lub does
  3278      * not exist return null.
  3279      */
  3280     public Type lub(Type t1, Type t2) {
  3281         return lub(List.of(t1, t2));
  3284     /**
  3285      * Return the least upper bound (lub) of set of types.  If the lub
  3286      * does not exist return the type of null (bottom).
  3287      */
  3288     public Type lub(List<Type> ts) {
  3289         final int ARRAY_BOUND = 1;
  3290         final int CLASS_BOUND = 2;
  3291         int boundkind = 0;
  3292         for (Type t : ts) {
  3293             switch (t.tag) {
  3294             case CLASS:
  3295                 boundkind |= CLASS_BOUND;
  3296                 break;
  3297             case ARRAY:
  3298                 boundkind |= ARRAY_BOUND;
  3299                 break;
  3300             case  TYPEVAR:
  3301                 do {
  3302                     t = t.getUpperBound();
  3303                 } while (t.tag == TYPEVAR);
  3304                 if (t.tag == ARRAY) {
  3305                     boundkind |= ARRAY_BOUND;
  3306                 } else {
  3307                     boundkind |= CLASS_BOUND;
  3309                 break;
  3310             default:
  3311                 if (t.isPrimitive())
  3312                     return syms.errType;
  3315         switch (boundkind) {
  3316         case 0:
  3317             return syms.botType;
  3319         case ARRAY_BOUND:
  3320             // calculate lub(A[], B[])
  3321             List<Type> elements = Type.map(ts, elemTypeFun);
  3322             for (Type t : elements) {
  3323                 if (t.isPrimitive()) {
  3324                     // if a primitive type is found, then return
  3325                     // arraySuperType unless all the types are the
  3326                     // same
  3327                     Type first = ts.head;
  3328                     for (Type s : ts.tail) {
  3329                         if (!isSameType(first, s)) {
  3330                              // lub(int[], B[]) is Cloneable & Serializable
  3331                             return arraySuperType();
  3334                     // all the array types are the same, return one
  3335                     // lub(int[], int[]) is int[]
  3336                     return first;
  3339             // lub(A[], B[]) is lub(A, B)[]
  3340             return new ArrayType(lub(elements), syms.arrayClass);
  3342         case CLASS_BOUND:
  3343             // calculate lub(A, B)
  3344             while (ts.head.tag != CLASS && ts.head.tag != TYPEVAR)
  3345                 ts = ts.tail;
  3346             Assert.check(!ts.isEmpty());
  3347             //step 1 - compute erased candidate set (EC)
  3348             List<Type> cl = erasedSupertypes(ts.head);
  3349             for (Type t : ts.tail) {
  3350                 if (t.tag == CLASS || t.tag == TYPEVAR)
  3351                     cl = intersect(cl, erasedSupertypes(t));
  3353             //step 2 - compute minimal erased candidate set (MEC)
  3354             List<Type> mec = closureMin(cl);
  3355             //step 3 - for each element G in MEC, compute lci(Inv(G))
  3356             List<Type> candidates = List.nil();
  3357             for (Type erasedSupertype : mec) {
  3358                 List<Type> lci = List.of(asSuper(ts.head, erasedSupertype.tsym));
  3359                 for (Type t : ts) {
  3360                     lci = intersect(lci, List.of(asSuper(t, erasedSupertype.tsym)));
  3362                 candidates = candidates.appendList(lci);
  3364             //step 4 - let MEC be { G1, G2 ... Gn }, then we have that
  3365             //lub = lci(Inv(G1)) & lci(Inv(G2)) & ... & lci(Inv(Gn))
  3366             return compoundMin(candidates);
  3368         default:
  3369             // calculate lub(A, B[])
  3370             List<Type> classes = List.of(arraySuperType());
  3371             for (Type t : ts) {
  3372                 if (t.tag != ARRAY) // Filter out any arrays
  3373                     classes = classes.prepend(t);
  3375             // lub(A, B[]) is lub(A, arraySuperType)
  3376             return lub(classes);
  3379     // where
  3380         List<Type> erasedSupertypes(Type t) {
  3381             ListBuffer<Type> buf = lb();
  3382             for (Type sup : closure(t)) {
  3383                 if (sup.tag == TYPEVAR) {
  3384                     buf.append(sup);
  3385                 } else {
  3386                     buf.append(erasure(sup));
  3389             return buf.toList();
  3392         private Type arraySuperType = null;
  3393         private Type arraySuperType() {
  3394             // initialized lazily to avoid problems during compiler startup
  3395             if (arraySuperType == null) {
  3396                 synchronized (this) {
  3397                     if (arraySuperType == null) {
  3398                         // JLS 10.8: all arrays implement Cloneable and Serializable.
  3399                         arraySuperType = makeCompoundType(List.of(syms.serializableType,
  3400                                                                   syms.cloneableType), true);
  3404             return arraySuperType;
  3406     // </editor-fold>
  3408     // <editor-fold defaultstate="collapsed" desc="Greatest lower bound">
  3409     public Type glb(List<Type> ts) {
  3410         Type t1 = ts.head;
  3411         for (Type t2 : ts.tail) {
  3412             if (t1.isErroneous())
  3413                 return t1;
  3414             t1 = glb(t1, t2);
  3416         return t1;
  3418     //where
  3419     public Type glb(Type t, Type s) {
  3420         if (s == null)
  3421             return t;
  3422         else if (t.isPrimitive() || s.isPrimitive())
  3423             return syms.errType;
  3424         else if (isSubtypeNoCapture(t, s))
  3425             return t;
  3426         else if (isSubtypeNoCapture(s, t))
  3427             return s;
  3429         List<Type> closure = union(closure(t), closure(s));
  3430         List<Type> bounds = closureMin(closure);
  3432         if (bounds.isEmpty()) {             // length == 0
  3433             return syms.objectType;
  3434         } else if (bounds.tail.isEmpty()) { // length == 1
  3435             return bounds.head;
  3436         } else {                            // length > 1
  3437             int classCount = 0;
  3438             for (Type bound : bounds)
  3439                 if (!bound.isInterface())
  3440                     classCount++;
  3441             if (classCount > 1)
  3442                 return createErrorType(t);
  3444         return makeCompoundType(bounds);
  3446     // </editor-fold>
  3448     // <editor-fold defaultstate="collapsed" desc="hashCode">
  3449     /**
  3450      * Compute a hash code on a type.
  3451      */
  3452     public int hashCode(Type t) {
  3453         return hashCode.visit(t);
  3455     // where
  3456         private static final UnaryVisitor<Integer> hashCode = new UnaryVisitor<Integer>() {
  3458             public Integer visitType(Type t, Void ignored) {
  3459                 return t.tag.ordinal();
  3462             @Override
  3463             public Integer visitClassType(ClassType t, Void ignored) {
  3464                 int result = visit(t.getEnclosingType());
  3465                 result *= 127;
  3466                 result += t.tsym.flatName().hashCode();
  3467                 for (Type s : t.getTypeArguments()) {
  3468                     result *= 127;
  3469                     result += visit(s);
  3471                 return result;
  3474             @Override
  3475             public Integer visitMethodType(MethodType t, Void ignored) {
  3476                 int h = METHOD.ordinal();
  3477                 for (List<Type> thisargs = t.argtypes;
  3478                      thisargs.tail != null;
  3479                      thisargs = thisargs.tail)
  3480                     h = (h << 5) + visit(thisargs.head);
  3481                 return (h << 5) + visit(t.restype);
  3484             @Override
  3485             public Integer visitWildcardType(WildcardType t, Void ignored) {
  3486                 int result = t.kind.hashCode();
  3487                 if (t.type != null) {
  3488                     result *= 127;
  3489                     result += visit(t.type);
  3491                 return result;
  3494             @Override
  3495             public Integer visitArrayType(ArrayType t, Void ignored) {
  3496                 return visit(t.elemtype) + 12;
  3499             @Override
  3500             public Integer visitTypeVar(TypeVar t, Void ignored) {
  3501                 return System.identityHashCode(t.tsym);
  3504             @Override
  3505             public Integer visitUndetVar(UndetVar t, Void ignored) {
  3506                 return System.identityHashCode(t);
  3509             @Override
  3510             public Integer visitErrorType(ErrorType t, Void ignored) {
  3511                 return 0;
  3513         };
  3514     // </editor-fold>
  3516     // <editor-fold defaultstate="collapsed" desc="Return-Type-Substitutable">
  3517     /**
  3518      * Does t have a result that is a subtype of the result type of s,
  3519      * suitable for covariant returns?  It is assumed that both types
  3520      * are (possibly polymorphic) method types.  Monomorphic method
  3521      * types are handled in the obvious way.  Polymorphic method types
  3522      * require renaming all type variables of one to corresponding
  3523      * type variables in the other, where correspondence is by
  3524      * position in the type parameter list. */
  3525     public boolean resultSubtype(Type t, Type s, Warner warner) {
  3526         List<Type> tvars = t.getTypeArguments();
  3527         List<Type> svars = s.getTypeArguments();
  3528         Type tres = t.getReturnType();
  3529         Type sres = subst(s.getReturnType(), svars, tvars);
  3530         return covariantReturnType(tres, sres, warner);
  3533     /**
  3534      * Return-Type-Substitutable.
  3535      * @jls section 8.4.5
  3536      */
  3537     public boolean returnTypeSubstitutable(Type r1, Type r2) {
  3538         if (hasSameArgs(r1, r2))
  3539             return resultSubtype(r1, r2, noWarnings);
  3540         else
  3541             return covariantReturnType(r1.getReturnType(),
  3542                                        erasure(r2.getReturnType()),
  3543                                        noWarnings);
  3546     public boolean returnTypeSubstitutable(Type r1,
  3547                                            Type r2, Type r2res,
  3548                                            Warner warner) {
  3549         if (isSameType(r1.getReturnType(), r2res))
  3550             return true;
  3551         if (r1.getReturnType().isPrimitive() || r2res.isPrimitive())
  3552             return false;
  3554         if (hasSameArgs(r1, r2))
  3555             return covariantReturnType(r1.getReturnType(), r2res, warner);
  3556         if (!allowCovariantReturns)
  3557             return false;
  3558         if (isSubtypeUnchecked(r1.getReturnType(), r2res, warner))
  3559             return true;
  3560         if (!isSubtype(r1.getReturnType(), erasure(r2res)))
  3561             return false;
  3562         warner.warn(LintCategory.UNCHECKED);
  3563         return true;
  3566     /**
  3567      * Is t an appropriate return type in an overrider for a
  3568      * method that returns s?
  3569      */
  3570     public boolean covariantReturnType(Type t, Type s, Warner warner) {
  3571         return
  3572             isSameType(t, s) ||
  3573             allowCovariantReturns &&
  3574             !t.isPrimitive() &&
  3575             !s.isPrimitive() &&
  3576             isAssignable(t, s, warner);
  3578     // </editor-fold>
  3580     // <editor-fold defaultstate="collapsed" desc="Box/unbox support">
  3581     /**
  3582      * Return the class that boxes the given primitive.
  3583      */
  3584     public ClassSymbol boxedClass(Type t) {
  3585         return reader.enterClass(syms.boxedName[t.tag.ordinal()]);
  3588     /**
  3589      * Return the boxed type if 't' is primitive, otherwise return 't' itself.
  3590      */
  3591     public Type boxedTypeOrType(Type t) {
  3592         return t.isPrimitive() ?
  3593             boxedClass(t).type :
  3594             t;
  3597     /**
  3598      * Return the primitive type corresponding to a boxed type.
  3599      */
  3600     public Type unboxedType(Type t) {
  3601         if (allowBoxing) {
  3602             for (int i=0; i<syms.boxedName.length; i++) {
  3603                 Name box = syms.boxedName[i];
  3604                 if (box != null &&
  3605                     asSuper(t, reader.enterClass(box)) != null)
  3606                     return syms.typeOfTag[i];
  3609         return Type.noType;
  3612     /**
  3613      * Return the unboxed type if 't' is a boxed class, otherwise return 't' itself.
  3614      */
  3615     public Type unboxedTypeOrType(Type t) {
  3616         Type unboxedType = unboxedType(t);
  3617         return unboxedType.tag == NONE ? t : unboxedType;
  3619     // </editor-fold>
  3621     // <editor-fold defaultstate="collapsed" desc="Capture conversion">
  3622     /*
  3623      * JLS 5.1.10 Capture Conversion:
  3625      * Let G name a generic type declaration with n formal type
  3626      * parameters A1 ... An with corresponding bounds U1 ... Un. There
  3627      * exists a capture conversion from G<T1 ... Tn> to G<S1 ... Sn>,
  3628      * where, for 1 <= i <= n:
  3630      * + If Ti is a wildcard type argument (4.5.1) of the form ? then
  3631      *   Si is a fresh type variable whose upper bound is
  3632      *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is the null
  3633      *   type.
  3635      * + If Ti is a wildcard type argument of the form ? extends Bi,
  3636      *   then Si is a fresh type variable whose upper bound is
  3637      *   glb(Bi, Ui[A1 := S1, ..., An := Sn]) and whose lower bound is
  3638      *   the null type, where glb(V1,... ,Vm) is V1 & ... & Vm. It is
  3639      *   a compile-time error if for any two classes (not interfaces)
  3640      *   Vi and Vj,Vi is not a subclass of Vj or vice versa.
  3642      * + If Ti is a wildcard type argument of the form ? super Bi,
  3643      *   then Si is a fresh type variable whose upper bound is
  3644      *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is Bi.
  3646      * + Otherwise, Si = Ti.
  3648      * Capture conversion on any type other than a parameterized type
  3649      * (4.5) acts as an identity conversion (5.1.1). Capture
  3650      * conversions never require a special action at run time and
  3651      * therefore never throw an exception at run time.
  3653      * Capture conversion is not applied recursively.
  3654      */
  3655     /**
  3656      * Capture conversion as specified by the JLS.
  3657      */
  3659     public List<Type> capture(List<Type> ts) {
  3660         List<Type> buf = List.nil();
  3661         for (Type t : ts) {
  3662             buf = buf.prepend(capture(t));
  3664         return buf.reverse();
  3666     public Type capture(Type t) {
  3667         if (t.tag != CLASS)
  3668             return t;
  3669         if (t.getEnclosingType() != Type.noType) {
  3670             Type capturedEncl = capture(t.getEnclosingType());
  3671             if (capturedEncl != t.getEnclosingType()) {
  3672                 Type type1 = memberType(capturedEncl, t.tsym);
  3673                 t = subst(type1, t.tsym.type.getTypeArguments(), t.getTypeArguments());
  3676         t = t.unannotatedType();
  3677         ClassType cls = (ClassType)t;
  3678         if (cls.isRaw() || !cls.isParameterized())
  3679             return cls;
  3681         ClassType G = (ClassType)cls.asElement().asType();
  3682         List<Type> A = G.getTypeArguments();
  3683         List<Type> T = cls.getTypeArguments();
  3684         List<Type> S = freshTypeVariables(T);
  3686         List<Type> currentA = A;
  3687         List<Type> currentT = T;
  3688         List<Type> currentS = S;
  3689         boolean captured = false;
  3690         while (!currentA.isEmpty() &&
  3691                !currentT.isEmpty() &&
  3692                !currentS.isEmpty()) {
  3693             if (currentS.head != currentT.head) {
  3694                 captured = true;
  3695                 WildcardType Ti = (WildcardType)currentT.head;
  3696                 Type Ui = currentA.head.getUpperBound();
  3697                 CapturedType Si = (CapturedType)currentS.head;
  3698                 if (Ui == null)
  3699                     Ui = syms.objectType;
  3700                 switch (Ti.kind) {
  3701                 case UNBOUND:
  3702                     Si.bound = subst(Ui, A, S);
  3703                     Si.lower = syms.botType;
  3704                     break;
  3705                 case EXTENDS:
  3706                     Si.bound = glb(Ti.getExtendsBound(), subst(Ui, A, S));
  3707                     Si.lower = syms.botType;
  3708                     break;
  3709                 case SUPER:
  3710                     Si.bound = subst(Ui, A, S);
  3711                     Si.lower = Ti.getSuperBound();
  3712                     break;
  3714                 if (Si.bound == Si.lower)
  3715                     currentS.head = Si.bound;
  3717             currentA = currentA.tail;
  3718             currentT = currentT.tail;
  3719             currentS = currentS.tail;
  3721         if (!currentA.isEmpty() || !currentT.isEmpty() || !currentS.isEmpty())
  3722             return erasure(t); // some "rare" type involved
  3724         if (captured)
  3725             return new ClassType(cls.getEnclosingType(), S, cls.tsym);
  3726         else
  3727             return t;
  3729     // where
  3730         public List<Type> freshTypeVariables(List<Type> types) {
  3731             ListBuffer<Type> result = lb();
  3732             for (Type t : types) {
  3733                 if (t.tag == WILDCARD) {
  3734                     Type bound = ((WildcardType)t).getExtendsBound();
  3735                     if (bound == null)
  3736                         bound = syms.objectType;
  3737                     result.append(new CapturedType(capturedName,
  3738                                                    syms.noSymbol,
  3739                                                    bound,
  3740                                                    syms.botType,
  3741                                                    (WildcardType)t));
  3742                 } else {
  3743                     result.append(t);
  3746             return result.toList();
  3748     // </editor-fold>
  3750     // <editor-fold defaultstate="collapsed" desc="Internal utility methods">
  3751     private List<Type> upperBounds(List<Type> ss) {
  3752         if (ss.isEmpty()) return ss;
  3753         Type head = upperBound(ss.head);
  3754         List<Type> tail = upperBounds(ss.tail);
  3755         if (head != ss.head || tail != ss.tail)
  3756             return tail.prepend(head);
  3757         else
  3758             return ss;
  3761     private boolean sideCast(Type from, Type to, Warner warn) {
  3762         // We are casting from type $from$ to type $to$, which are
  3763         // non-final unrelated types.  This method
  3764         // tries to reject a cast by transferring type parameters
  3765         // from $to$ to $from$ by common superinterfaces.
  3766         boolean reverse = false;
  3767         Type target = to;
  3768         if ((to.tsym.flags() & INTERFACE) == 0) {
  3769             Assert.check((from.tsym.flags() & INTERFACE) != 0);
  3770             reverse = true;
  3771             to = from;
  3772             from = target;
  3774         List<Type> commonSupers = superClosure(to, erasure(from));
  3775         boolean giveWarning = commonSupers.isEmpty();
  3776         // The arguments to the supers could be unified here to
  3777         // get a more accurate analysis
  3778         while (commonSupers.nonEmpty()) {
  3779             Type t1 = asSuper(from, commonSupers.head.tsym);
  3780             Type t2 = commonSupers.head; // same as asSuper(to, commonSupers.head.tsym);
  3781             if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
  3782                 return false;
  3783             giveWarning = giveWarning || (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2));
  3784             commonSupers = commonSupers.tail;
  3786         if (giveWarning && !isReifiable(reverse ? from : to))
  3787             warn.warn(LintCategory.UNCHECKED);
  3788         if (!allowCovariantReturns)
  3789             // reject if there is a common method signature with
  3790             // incompatible return types.
  3791             chk.checkCompatibleAbstracts(warn.pos(), from, to);
  3792         return true;
  3795     private boolean sideCastFinal(Type from, Type to, Warner warn) {
  3796         // We are casting from type $from$ to type $to$, which are
  3797         // unrelated types one of which is final and the other of
  3798         // which is an interface.  This method
  3799         // tries to reject a cast by transferring type parameters
  3800         // from the final class to the interface.
  3801         boolean reverse = false;
  3802         Type target = to;
  3803         if ((to.tsym.flags() & INTERFACE) == 0) {
  3804             Assert.check((from.tsym.flags() & INTERFACE) != 0);
  3805             reverse = true;
  3806             to = from;
  3807             from = target;
  3809         Assert.check((from.tsym.flags() & FINAL) != 0);
  3810         Type t1 = asSuper(from, to.tsym);
  3811         if (t1 == null) return false;
  3812         Type t2 = to;
  3813         if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
  3814             return false;
  3815         if (!allowCovariantReturns)
  3816             // reject if there is a common method signature with
  3817             // incompatible return types.
  3818             chk.checkCompatibleAbstracts(warn.pos(), from, to);
  3819         if (!isReifiable(target) &&
  3820             (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2)))
  3821             warn.warn(LintCategory.UNCHECKED);
  3822         return true;
  3825     private boolean giveWarning(Type from, Type to) {
  3826         Type subFrom = asSub(from, to.tsym);
  3827         return to.isParameterized() &&
  3828                 (!(isUnbounded(to) ||
  3829                 isSubtype(from, to) ||
  3830                 ((subFrom != null) && containsType(to.allparams(), subFrom.allparams()))));
  3833     private List<Type> superClosure(Type t, Type s) {
  3834         List<Type> cl = List.nil();
  3835         for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
  3836             if (isSubtype(s, erasure(l.head))) {
  3837                 cl = insert(cl, l.head);
  3838             } else {
  3839                 cl = union(cl, superClosure(l.head, s));
  3842         return cl;
  3845     private boolean containsTypeEquivalent(Type t, Type s) {
  3846         return
  3847             isSameType(t, s) || // shortcut
  3848             containsType(t, s) && containsType(s, t);
  3851     // <editor-fold defaultstate="collapsed" desc="adapt">
  3852     /**
  3853      * Adapt a type by computing a substitution which maps a source
  3854      * type to a target type.
  3856      * @param source    the source type
  3857      * @param target    the target type
  3858      * @param from      the type variables of the computed substitution
  3859      * @param to        the types of the computed substitution.
  3860      */
  3861     public void adapt(Type source,
  3862                        Type target,
  3863                        ListBuffer<Type> from,
  3864                        ListBuffer<Type> to) throws AdaptFailure {
  3865         new Adapter(from, to).adapt(source, target);
  3868     class Adapter extends SimpleVisitor<Void, Type> {
  3870         ListBuffer<Type> from;
  3871         ListBuffer<Type> to;
  3872         Map<Symbol,Type> mapping;
  3874         Adapter(ListBuffer<Type> from, ListBuffer<Type> to) {
  3875             this.from = from;
  3876             this.to = to;
  3877             mapping = new HashMap<Symbol,Type>();
  3880         public void adapt(Type source, Type target) throws AdaptFailure {
  3881             visit(source, target);
  3882             List<Type> fromList = from.toList();
  3883             List<Type> toList = to.toList();
  3884             while (!fromList.isEmpty()) {
  3885                 Type val = mapping.get(fromList.head.tsym);
  3886                 if (toList.head != val)
  3887                     toList.head = val;
  3888                 fromList = fromList.tail;
  3889                 toList = toList.tail;
  3893         @Override
  3894         public Void visitClassType(ClassType source, Type target) throws AdaptFailure {
  3895             if (target.tag == CLASS)
  3896                 adaptRecursive(source.allparams(), target.allparams());
  3897             return null;
  3900         @Override
  3901         public Void visitArrayType(ArrayType source, Type target) throws AdaptFailure {
  3902             if (target.tag == ARRAY)
  3903                 adaptRecursive(elemtype(source), elemtype(target));
  3904             return null;
  3907         @Override
  3908         public Void visitWildcardType(WildcardType source, Type target) throws AdaptFailure {
  3909             if (source.isExtendsBound())
  3910                 adaptRecursive(upperBound(source), upperBound(target));
  3911             else if (source.isSuperBound())
  3912                 adaptRecursive(lowerBound(source), lowerBound(target));
  3913             return null;
  3916         @Override
  3917         public Void visitTypeVar(TypeVar source, Type target) throws AdaptFailure {
  3918             // Check to see if there is
  3919             // already a mapping for $source$, in which case
  3920             // the old mapping will be merged with the new
  3921             Type val = mapping.get(source.tsym);
  3922             if (val != null) {
  3923                 if (val.isSuperBound() && target.isSuperBound()) {
  3924                     val = isSubtype(lowerBound(val), lowerBound(target))
  3925                         ? target : val;
  3926                 } else if (val.isExtendsBound() && target.isExtendsBound()) {
  3927                     val = isSubtype(upperBound(val), upperBound(target))
  3928                         ? val : target;
  3929                 } else if (!isSameType(val, target)) {
  3930                     throw new AdaptFailure();
  3932             } else {
  3933                 val = target;
  3934                 from.append(source);
  3935                 to.append(target);
  3937             mapping.put(source.tsym, val);
  3938             return null;
  3941         @Override
  3942         public Void visitType(Type source, Type target) {
  3943             return null;
  3946         private Set<TypePair> cache = new HashSet<TypePair>();
  3948         private void adaptRecursive(Type source, Type target) {
  3949             TypePair pair = new TypePair(source, target);
  3950             if (cache.add(pair)) {
  3951                 try {
  3952                     visit(source, target);
  3953                 } finally {
  3954                     cache.remove(pair);
  3959         private void adaptRecursive(List<Type> source, List<Type> target) {
  3960             if (source.length() == target.length()) {
  3961                 while (source.nonEmpty()) {
  3962                     adaptRecursive(source.head, target.head);
  3963                     source = source.tail;
  3964                     target = target.tail;
  3970     public static class AdaptFailure extends RuntimeException {
  3971         static final long serialVersionUID = -7490231548272701566L;
  3974     private void adaptSelf(Type t,
  3975                            ListBuffer<Type> from,
  3976                            ListBuffer<Type> to) {
  3977         try {
  3978             //if (t.tsym.type != t)
  3979                 adapt(t.tsym.type, t, from, to);
  3980         } catch (AdaptFailure ex) {
  3981             // Adapt should never fail calculating a mapping from
  3982             // t.tsym.type to t as there can be no merge problem.
  3983             throw new AssertionError(ex);
  3986     // </editor-fold>
  3988     /**
  3989      * Rewrite all type variables (universal quantifiers) in the given
  3990      * type to wildcards (existential quantifiers).  This is used to
  3991      * determine if a cast is allowed.  For example, if high is true
  3992      * and {@code T <: Number}, then {@code List<T>} is rewritten to
  3993      * {@code List<?  extends Number>}.  Since {@code List<Integer> <:
  3994      * List<? extends Number>} a {@code List<T>} can be cast to {@code
  3995      * List<Integer>} with a warning.
  3996      * @param t a type
  3997      * @param high if true return an upper bound; otherwise a lower
  3998      * bound
  3999      * @param rewriteTypeVars only rewrite captured wildcards if false;
  4000      * otherwise rewrite all type variables
  4001      * @return the type rewritten with wildcards (existential
  4002      * quantifiers) only
  4003      */
  4004     private Type rewriteQuantifiers(Type t, boolean high, boolean rewriteTypeVars) {
  4005         return new Rewriter(high, rewriteTypeVars).visit(t);
  4008     class Rewriter extends UnaryVisitor<Type> {
  4010         boolean high;
  4011         boolean rewriteTypeVars;
  4013         Rewriter(boolean high, boolean rewriteTypeVars) {
  4014             this.high = high;
  4015             this.rewriteTypeVars = rewriteTypeVars;
  4018         @Override
  4019         public Type visitClassType(ClassType t, Void s) {
  4020             ListBuffer<Type> rewritten = new ListBuffer<Type>();
  4021             boolean changed = false;
  4022             for (Type arg : t.allparams()) {
  4023                 Type bound = visit(arg);
  4024                 if (arg != bound) {
  4025                     changed = true;
  4027                 rewritten.append(bound);
  4029             if (changed)
  4030                 return subst(t.tsym.type,
  4031                         t.tsym.type.allparams(),
  4032                         rewritten.toList());
  4033             else
  4034                 return t;
  4037         public Type visitType(Type t, Void s) {
  4038             return high ? upperBound(t) : lowerBound(t);
  4041         @Override
  4042         public Type visitCapturedType(CapturedType t, Void s) {
  4043             Type w_bound = t.wildcard.type;
  4044             Type bound = w_bound.contains(t) ?
  4045                         erasure(w_bound) :
  4046                         visit(w_bound);
  4047             return rewriteAsWildcardType(visit(bound), t.wildcard.bound, t.wildcard.kind);
  4050         @Override
  4051         public Type visitTypeVar(TypeVar t, Void s) {
  4052             if (rewriteTypeVars) {
  4053                 Type bound = t.bound.contains(t) ?
  4054                         erasure(t.bound) :
  4055                         visit(t.bound);
  4056                 return rewriteAsWildcardType(bound, t, EXTENDS);
  4057             } else {
  4058                 return t;
  4062         @Override
  4063         public Type visitWildcardType(WildcardType t, Void s) {
  4064             Type bound2 = visit(t.type);
  4065             return t.type == bound2 ? t : rewriteAsWildcardType(bound2, t.bound, t.kind);
  4068         private Type rewriteAsWildcardType(Type bound, TypeVar formal, BoundKind bk) {
  4069             switch (bk) {
  4070                case EXTENDS: return high ?
  4071                        makeExtendsWildcard(B(bound), formal) :
  4072                        makeExtendsWildcard(syms.objectType, formal);
  4073                case SUPER: return high ?
  4074                        makeSuperWildcard(syms.botType, formal) :
  4075                        makeSuperWildcard(B(bound), formal);
  4076                case UNBOUND: return makeExtendsWildcard(syms.objectType, formal);
  4077                default:
  4078                    Assert.error("Invalid bound kind " + bk);
  4079                    return null;
  4083         Type B(Type t) {
  4084             while (t.tag == WILDCARD) {
  4085                 WildcardType w = (WildcardType)t;
  4086                 t = high ?
  4087                     w.getExtendsBound() :
  4088                     w.getSuperBound();
  4089                 if (t == null) {
  4090                     t = high ? syms.objectType : syms.botType;
  4093             return t;
  4098     /**
  4099      * Create a wildcard with the given upper (extends) bound; create
  4100      * an unbounded wildcard if bound is Object.
  4102      * @param bound the upper bound
  4103      * @param formal the formal type parameter that will be
  4104      * substituted by the wildcard
  4105      */
  4106     private WildcardType makeExtendsWildcard(Type bound, TypeVar formal) {
  4107         if (bound == syms.objectType) {
  4108             return new WildcardType(syms.objectType,
  4109                                     BoundKind.UNBOUND,
  4110                                     syms.boundClass,
  4111                                     formal);
  4112         } else {
  4113             return new WildcardType(bound,
  4114                                     BoundKind.EXTENDS,
  4115                                     syms.boundClass,
  4116                                     formal);
  4120     /**
  4121      * Create a wildcard with the given lower (super) bound; create an
  4122      * unbounded wildcard if bound is bottom (type of {@code null}).
  4124      * @param bound the lower bound
  4125      * @param formal the formal type parameter that will be
  4126      * substituted by the wildcard
  4127      */
  4128     private WildcardType makeSuperWildcard(Type bound, TypeVar formal) {
  4129         if (bound.tag == BOT) {
  4130             return new WildcardType(syms.objectType,
  4131                                     BoundKind.UNBOUND,
  4132                                     syms.boundClass,
  4133                                     formal);
  4134         } else {
  4135             return new WildcardType(bound,
  4136                                     BoundKind.SUPER,
  4137                                     syms.boundClass,
  4138                                     formal);
  4142     /**
  4143      * A wrapper for a type that allows use in sets.
  4144      */
  4145     public static class UniqueType {
  4146         public final Type type;
  4147         final Types types;
  4149         public UniqueType(Type type, Types types) {
  4150             this.type = type;
  4151             this.types = types;
  4154         public int hashCode() {
  4155             return types.hashCode(type);
  4158         public boolean equals(Object obj) {
  4159             return (obj instanceof UniqueType) &&
  4160                 types.isSameType(type, ((UniqueType)obj).type);
  4163         public String toString() {
  4164             return type.toString();
  4168     // </editor-fold>
  4170     // <editor-fold defaultstate="collapsed" desc="Visitors">
  4171     /**
  4172      * A default visitor for types.  All visitor methods except
  4173      * visitType are implemented by delegating to visitType.  Concrete
  4174      * subclasses must provide an implementation of visitType and can
  4175      * override other methods as needed.
  4177      * @param <R> the return type of the operation implemented by this
  4178      * visitor; use Void if no return type is needed.
  4179      * @param <S> the type of the second argument (the first being the
  4180      * type itself) of the operation implemented by this visitor; use
  4181      * Void if a second argument is not needed.
  4182      */
  4183     public static abstract class DefaultTypeVisitor<R,S> implements Type.Visitor<R,S> {
  4184         final public R visit(Type t, S s)               { return t.accept(this, s); }
  4185         public R visitClassType(ClassType t, S s)       { return visitType(t, s); }
  4186         public R visitWildcardType(WildcardType t, S s) { return visitType(t, s); }
  4187         public R visitArrayType(ArrayType t, S s)       { return visitType(t, s); }
  4188         public R visitMethodType(MethodType t, S s)     { return visitType(t, s); }
  4189         public R visitPackageType(PackageType t, S s)   { return visitType(t, s); }
  4190         public R visitTypeVar(TypeVar t, S s)           { return visitType(t, s); }
  4191         public R visitCapturedType(CapturedType t, S s) { return visitType(t, s); }
  4192         public R visitForAll(ForAll t, S s)             { return visitType(t, s); }
  4193         public R visitUndetVar(UndetVar t, S s)         { return visitType(t, s); }
  4194         public R visitErrorType(ErrorType t, S s)       { return visitType(t, s); }
  4195         // Pretend annotations don't exist
  4196         public R visitAnnotatedType(AnnotatedType t, S s) { return visit(t.underlyingType, s); }
  4199     /**
  4200      * A default visitor for symbols.  All visitor methods except
  4201      * visitSymbol are implemented by delegating to visitSymbol.  Concrete
  4202      * subclasses must provide an implementation of visitSymbol and can
  4203      * override other methods as needed.
  4205      * @param <R> the return type of the operation implemented by this
  4206      * visitor; use Void if no return type is needed.
  4207      * @param <S> the type of the second argument (the first being the
  4208      * symbol itself) of the operation implemented by this visitor; use
  4209      * Void if a second argument is not needed.
  4210      */
  4211     public static abstract class DefaultSymbolVisitor<R,S> implements Symbol.Visitor<R,S> {
  4212         final public R visit(Symbol s, S arg)                   { return s.accept(this, arg); }
  4213         public R visitClassSymbol(ClassSymbol s, S arg)         { return visitSymbol(s, arg); }
  4214         public R visitMethodSymbol(MethodSymbol s, S arg)       { return visitSymbol(s, arg); }
  4215         public R visitOperatorSymbol(OperatorSymbol s, S arg)   { return visitSymbol(s, arg); }
  4216         public R visitPackageSymbol(PackageSymbol s, S arg)     { return visitSymbol(s, arg); }
  4217         public R visitTypeSymbol(TypeSymbol s, S arg)           { return visitSymbol(s, arg); }
  4218         public R visitVarSymbol(VarSymbol s, S arg)             { return visitSymbol(s, arg); }
  4221     /**
  4222      * A <em>simple</em> visitor for types.  This visitor is simple as
  4223      * captured wildcards, for-all types (generic methods), and
  4224      * undetermined type variables (part of inference) are hidden.
  4225      * Captured wildcards are hidden by treating them as type
  4226      * variables and the rest are hidden by visiting their qtypes.
  4228      * @param <R> the return type of the operation implemented by this
  4229      * visitor; use Void if no return type is needed.
  4230      * @param <S> the type of the second argument (the first being the
  4231      * type itself) of the operation implemented by this visitor; use
  4232      * Void if a second argument is not needed.
  4233      */
  4234     public static abstract class SimpleVisitor<R,S> extends DefaultTypeVisitor<R,S> {
  4235         @Override
  4236         public R visitCapturedType(CapturedType t, S s) {
  4237             return visitTypeVar(t, s);
  4239         @Override
  4240         public R visitForAll(ForAll t, S s) {
  4241             return visit(t.qtype, s);
  4243         @Override
  4244         public R visitUndetVar(UndetVar t, S s) {
  4245             return visit(t.qtype, s);
  4249     /**
  4250      * A plain relation on types.  That is a 2-ary function on the
  4251      * form Type&nbsp;&times;&nbsp;Type&nbsp;&rarr;&nbsp;Boolean.
  4252      * <!-- In plain text: Type x Type -> Boolean -->
  4253      */
  4254     public static abstract class TypeRelation extends SimpleVisitor<Boolean,Type> {}
  4256     /**
  4257      * A convenience visitor for implementing operations that only
  4258      * require one argument (the type itself), that is, unary
  4259      * operations.
  4261      * @param <R> the return type of the operation implemented by this
  4262      * visitor; use Void if no return type is needed.
  4263      */
  4264     public static abstract class UnaryVisitor<R> extends SimpleVisitor<R,Void> {
  4265         final public R visit(Type t) { return t.accept(this, null); }
  4268     /**
  4269      * A visitor for implementing a mapping from types to types.  The
  4270      * default behavior of this class is to implement the identity
  4271      * mapping (mapping a type to itself).  This can be overridden in
  4272      * subclasses.
  4274      * @param <S> the type of the second argument (the first being the
  4275      * type itself) of this mapping; use Void if a second argument is
  4276      * not needed.
  4277      */
  4278     public static class MapVisitor<S> extends DefaultTypeVisitor<Type,S> {
  4279         final public Type visit(Type t) { return t.accept(this, null); }
  4280         public Type visitType(Type t, S s) { return t; }
  4282     // </editor-fold>
  4285     // <editor-fold defaultstate="collapsed" desc="Annotation support">
  4287     public RetentionPolicy getRetention(Attribute.Compound a) {
  4288         return getRetention(a.type.tsym);
  4291     public RetentionPolicy getRetention(Symbol sym) {
  4292         RetentionPolicy vis = RetentionPolicy.CLASS; // the default
  4293         Attribute.Compound c = sym.attribute(syms.retentionType.tsym);
  4294         if (c != null) {
  4295             Attribute value = c.member(names.value);
  4296             if (value != null && value instanceof Attribute.Enum) {
  4297                 Name levelName = ((Attribute.Enum)value).value.name;
  4298                 if (levelName == names.SOURCE) vis = RetentionPolicy.SOURCE;
  4299                 else if (levelName == names.CLASS) vis = RetentionPolicy.CLASS;
  4300                 else if (levelName == names.RUNTIME) vis = RetentionPolicy.RUNTIME;
  4301                 else ;// /* fail soft */ throw new AssertionError(levelName);
  4304         return vis;
  4306     // </editor-fold>

mercurial