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

Wed, 06 Feb 2013 14:03:39 +0000

author
mcimadamore
date
Wed, 06 Feb 2013 14:03:39 +0000
changeset 1550
1df20330f6bd
parent 1521
71f35e4b93a5
child 1563
bc456436c613
permissions
-rw-r--r--

8007463: Cleanup inference related classes
Summary: Make Infer.InferenceContext an inner class; adjust bound replacement logic in Type.UndetVar
Reviewed-by: jjg

     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         return isSameTypes(ts, ss, false);
   980     }
   981     public boolean isSameTypes(List<Type> ts, List<Type> ss, boolean strict) {
   982         while (ts.tail != null && ss.tail != null
   983                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   984                isSameType(ts.head, ss.head, strict)) {
   985             ts = ts.tail;
   986             ss = ss.tail;
   987         }
   988         return ts.tail == null && ss.tail == null;
   989         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   990     }
   992     /**
   993      * Is t the same type as s?
   994      */
   995     public boolean isSameType(Type t, Type s) {
   996         return isSameType(t, s, false);
   997     }
   998     public boolean isSameType(Type t, Type s, boolean strict) {
   999         return strict ?
  1000                 isSameTypeStrict.visit(t, s) :
  1001                 isSameTypeLoose.visit(t, s);
  1003     // where
  1004         abstract class SameTypeVisitor extends TypeRelation {
  1006             public Boolean visitType(Type t, Type s) {
  1007                 if (t == s)
  1008                     return true;
  1010                 if (s.isPartial())
  1011                     return visit(s, t);
  1013                 switch (t.tag) {
  1014                 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
  1015                 case DOUBLE: case BOOLEAN: case VOID: case BOT: case NONE:
  1016                     return t.tag == s.tag;
  1017                 case TYPEVAR: {
  1018                     if (s.tag == TYPEVAR) {
  1019                         //type-substitution does not preserve type-var types
  1020                         //check that type var symbols and bounds are indeed the same
  1021                         return sameTypeVars((TypeVar)t, (TypeVar)s);
  1023                     else {
  1024                         //special case for s == ? super X, where upper(s) = u
  1025                         //check that u == t, where u has been set by Type.withTypeVar
  1026                         return s.isSuperBound() &&
  1027                                 !s.isExtendsBound() &&
  1028                                 visit(t, upperBound(s));
  1031                 default:
  1032                     throw new AssertionError("isSameType " + t.tag);
  1036             abstract boolean sameTypeVars(TypeVar tv1, TypeVar tv2);
  1038             @Override
  1039             public Boolean visitWildcardType(WildcardType t, Type s) {
  1040                 if (s.isPartial())
  1041                     return visit(s, t);
  1042                 else
  1043                     return false;
  1046             @Override
  1047             public Boolean visitClassType(ClassType t, Type s) {
  1048                 if (t == s)
  1049                     return true;
  1051                 if (s.isPartial())
  1052                     return visit(s, t);
  1054                 if (s.isSuperBound() && !s.isExtendsBound())
  1055                     return visit(t, upperBound(s)) && visit(t, lowerBound(s));
  1057                 if (t.isCompound() && s.isCompound()) {
  1058                     if (!visit(supertype(t), supertype(s)))
  1059                         return false;
  1061                     HashSet<UniqueType> set = new HashSet<UniqueType>();
  1062                     for (Type x : interfaces(t))
  1063                         set.add(new UniqueType(x, Types.this));
  1064                     for (Type x : interfaces(s)) {
  1065                         if (!set.remove(new UniqueType(x, Types.this)))
  1066                             return false;
  1068                     return (set.isEmpty());
  1070                 return t.tsym == s.tsym
  1071                     && visit(t.getEnclosingType(), s.getEnclosingType())
  1072                     && containsTypes(t.getTypeArguments(), s.getTypeArguments());
  1075             abstract protected boolean containsTypes(List<Type> ts1, List<Type> ts2);
  1077             @Override
  1078             public Boolean visitArrayType(ArrayType t, Type s) {
  1079                 if (t == s)
  1080                     return true;
  1082                 if (s.isPartial())
  1083                     return visit(s, t);
  1085                 return s.hasTag(ARRAY)
  1086                     && containsTypeEquivalent(t.elemtype, elemtype(s));
  1089             @Override
  1090             public Boolean visitMethodType(MethodType t, Type s) {
  1091                 // isSameType for methods does not take thrown
  1092                 // exceptions into account!
  1093                 return hasSameArgs(t, s) && visit(t.getReturnType(), s.getReturnType());
  1096             @Override
  1097             public Boolean visitPackageType(PackageType t, Type s) {
  1098                 return t == s;
  1101             @Override
  1102             public Boolean visitForAll(ForAll t, Type s) {
  1103                 if (s.tag != FORALL)
  1104                     return false;
  1106                 ForAll forAll = (ForAll)s;
  1107                 return hasSameBounds(t, forAll)
  1108                     && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
  1111             @Override
  1112             public Boolean visitUndetVar(UndetVar t, Type s) {
  1113                 if (s.tag == WILDCARD)
  1114                     // FIXME, this might be leftovers from before capture conversion
  1115                     return false;
  1117                 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN)
  1118                     return true;
  1120                 t.addBound(InferenceBound.EQ, s, Types.this);
  1122                 return true;
  1125             @Override
  1126             public Boolean visitErrorType(ErrorType t, Type s) {
  1127                 return true;
  1131         /**
  1132          * Standard type-equality relation - type variables are considered
  1133          * equals if they share the same type symbol.
  1134          */
  1135         TypeRelation isSameTypeLoose = new SameTypeVisitor() {
  1136             @Override
  1137             boolean sameTypeVars(TypeVar tv1, TypeVar tv2) {
  1138                 return tv1.tsym == tv2.tsym && visit(tv1.getUpperBound(), tv2.getUpperBound());
  1140             @Override
  1141             protected boolean containsTypes(List<Type> ts1, List<Type> ts2) {
  1142                 return containsTypeEquivalent(ts1, ts2);
  1144         };
  1146         /**
  1147          * Strict type-equality relation - type variables are considered
  1148          * equals if they share the same object identity.
  1149          */
  1150         TypeRelation isSameTypeStrict = new SameTypeVisitor() {
  1151             @Override
  1152             boolean sameTypeVars(TypeVar tv1, TypeVar tv2) {
  1153                 return tv1 == tv2;
  1155             @Override
  1156             protected boolean containsTypes(List<Type> ts1, List<Type> ts2) {
  1157                 return isSameTypes(ts1, ts2, true);
  1159         };
  1160     // </editor-fold>
  1162     // <editor-fold defaultstate="collapsed" desc="Contains Type">
  1163     public boolean containedBy(Type t, Type s) {
  1164         switch (t.tag) {
  1165         case UNDETVAR:
  1166             if (s.tag == WILDCARD) {
  1167                 UndetVar undetvar = (UndetVar)t;
  1168                 WildcardType wt = (WildcardType)s;
  1169                 switch(wt.kind) {
  1170                     case UNBOUND: //similar to ? extends Object
  1171                     case EXTENDS: {
  1172                         Type bound = upperBound(s);
  1173                         undetvar.addBound(InferenceBound.UPPER, bound, this);
  1174                         break;
  1176                     case SUPER: {
  1177                         Type bound = lowerBound(s);
  1178                         undetvar.addBound(InferenceBound.LOWER, bound, this);
  1179                         break;
  1182                 return true;
  1183             } else {
  1184                 return isSameType(t, s);
  1186         case ERROR:
  1187             return true;
  1188         default:
  1189             return containsType(s, t);
  1193     boolean containsType(List<Type> ts, List<Type> ss) {
  1194         while (ts.nonEmpty() && ss.nonEmpty()
  1195                && containsType(ts.head, ss.head)) {
  1196             ts = ts.tail;
  1197             ss = ss.tail;
  1199         return ts.isEmpty() && ss.isEmpty();
  1202     /**
  1203      * Check if t contains s.
  1205      * <p>T contains S if:
  1207      * <p>{@code L(T) <: L(S) && U(S) <: U(T)}
  1209      * <p>This relation is only used by ClassType.isSubtype(), that
  1210      * is,
  1212      * <p>{@code C<S> <: C<T> if T contains S.}
  1214      * <p>Because of F-bounds, this relation can lead to infinite
  1215      * recursion.  Thus we must somehow break that recursion.  Notice
  1216      * that containsType() is only called from ClassType.isSubtype().
  1217      * Since the arguments have already been checked against their
  1218      * bounds, we know:
  1220      * <p>{@code U(S) <: U(T) if T is "super" bound (U(T) *is* the bound)}
  1222      * <p>{@code L(T) <: L(S) if T is "extends" bound (L(T) is bottom)}
  1224      * @param t a type
  1225      * @param s a type
  1226      */
  1227     public boolean containsType(Type t, Type s) {
  1228         return containsType.visit(t, s);
  1230     // where
  1231         private TypeRelation containsType = new TypeRelation() {
  1233             private Type U(Type t) {
  1234                 while (t.tag == WILDCARD) {
  1235                     WildcardType w = (WildcardType)t;
  1236                     if (w.isSuperBound())
  1237                         return w.bound == null ? syms.objectType : w.bound.bound;
  1238                     else
  1239                         t = w.type;
  1241                 return t;
  1244             private Type L(Type t) {
  1245                 while (t.tag == WILDCARD) {
  1246                     WildcardType w = (WildcardType)t;
  1247                     if (w.isExtendsBound())
  1248                         return syms.botType;
  1249                     else
  1250                         t = w.type;
  1252                 return t;
  1255             public Boolean visitType(Type t, Type s) {
  1256                 if (s.isPartial())
  1257                     return containedBy(s, t);
  1258                 else
  1259                     return isSameType(t, s);
  1262 //            void debugContainsType(WildcardType t, Type s) {
  1263 //                System.err.println();
  1264 //                System.err.format(" does %s contain %s?%n", t, s);
  1265 //                System.err.format(" %s U(%s) <: U(%s) %s = %s%n",
  1266 //                                  upperBound(s), s, t, U(t),
  1267 //                                  t.isSuperBound()
  1268 //                                  || isSubtypeNoCapture(upperBound(s), U(t)));
  1269 //                System.err.format(" %s L(%s) <: L(%s) %s = %s%n",
  1270 //                                  L(t), t, s, lowerBound(s),
  1271 //                                  t.isExtendsBound()
  1272 //                                  || isSubtypeNoCapture(L(t), lowerBound(s)));
  1273 //                System.err.println();
  1274 //            }
  1276             @Override
  1277             public Boolean visitWildcardType(WildcardType t, Type s) {
  1278                 if (s.isPartial())
  1279                     return containedBy(s, t);
  1280                 else {
  1281 //                    debugContainsType(t, s);
  1282                     return isSameWildcard(t, s)
  1283                         || isCaptureOf(s, t)
  1284                         || ((t.isExtendsBound() || isSubtypeNoCapture(L(t), lowerBound(s))) &&
  1285                             (t.isSuperBound() || isSubtypeNoCapture(upperBound(s), U(t))));
  1289             @Override
  1290             public Boolean visitUndetVar(UndetVar t, Type s) {
  1291                 if (s.tag != WILDCARD)
  1292                     return isSameType(t, s);
  1293                 else
  1294                     return false;
  1297             @Override
  1298             public Boolean visitErrorType(ErrorType t, Type s) {
  1299                 return true;
  1301         };
  1303     public boolean isCaptureOf(Type s, WildcardType t) {
  1304         if (s.tag != TYPEVAR || !((TypeVar)s).isCaptured())
  1305             return false;
  1306         return isSameWildcard(t, ((CapturedType)s).wildcard);
  1309     public boolean isSameWildcard(WildcardType t, Type s) {
  1310         if (s.tag != WILDCARD)
  1311             return false;
  1312         WildcardType w = (WildcardType)s;
  1313         return w.kind == t.kind && w.type == t.type;
  1316     public boolean containsTypeEquivalent(List<Type> ts, List<Type> ss) {
  1317         while (ts.nonEmpty() && ss.nonEmpty()
  1318                && containsTypeEquivalent(ts.head, ss.head)) {
  1319             ts = ts.tail;
  1320             ss = ss.tail;
  1322         return ts.isEmpty() && ss.isEmpty();
  1324     // </editor-fold>
  1326     // <editor-fold defaultstate="collapsed" desc="isCastable">
  1327     public boolean isCastable(Type t, Type s) {
  1328         return isCastable(t, s, noWarnings);
  1331     /**
  1332      * Is t is castable to s?<br>
  1333      * s is assumed to be an erased type.<br>
  1334      * (not defined for Method and ForAll types).
  1335      */
  1336     public boolean isCastable(Type t, Type s, Warner warn) {
  1337         if (t == s)
  1338             return true;
  1340         if (t.isPrimitive() != s.isPrimitive())
  1341             return allowBoxing && (
  1342                     isConvertible(t, s, warn)
  1343                     || (allowObjectToPrimitiveCast &&
  1344                         s.isPrimitive() &&
  1345                         isSubtype(boxedClass(s).type, t)));
  1346         if (warn != warnStack.head) {
  1347             try {
  1348                 warnStack = warnStack.prepend(warn);
  1349                 checkUnsafeVarargsConversion(t, s, warn);
  1350                 return isCastable.visit(t,s);
  1351             } finally {
  1352                 warnStack = warnStack.tail;
  1354         } else {
  1355             return isCastable.visit(t,s);
  1358     // where
  1359         private TypeRelation isCastable = new TypeRelation() {
  1361             public Boolean visitType(Type t, Type s) {
  1362                 if (s.tag == ERROR)
  1363                     return true;
  1365                 switch (t.tag) {
  1366                 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
  1367                 case DOUBLE:
  1368                     return s.isNumeric();
  1369                 case BOOLEAN:
  1370                     return s.tag == BOOLEAN;
  1371                 case VOID:
  1372                     return false;
  1373                 case BOT:
  1374                     return isSubtype(t, s);
  1375                 default:
  1376                     throw new AssertionError();
  1380             @Override
  1381             public Boolean visitWildcardType(WildcardType t, Type s) {
  1382                 return isCastable(upperBound(t), s, warnStack.head);
  1385             @Override
  1386             public Boolean visitClassType(ClassType t, Type s) {
  1387                 if (s.tag == ERROR || s.tag == BOT)
  1388                     return true;
  1390                 if (s.tag == TYPEVAR) {
  1391                     if (isCastable(t, s.getUpperBound(), noWarnings)) {
  1392                         warnStack.head.warn(LintCategory.UNCHECKED);
  1393                         return true;
  1394                     } else {
  1395                         return false;
  1399                 if (t.isCompound()) {
  1400                     Warner oldWarner = warnStack.head;
  1401                     warnStack.head = noWarnings;
  1402                     if (!visit(supertype(t), s))
  1403                         return false;
  1404                     for (Type intf : interfaces(t)) {
  1405                         if (!visit(intf, s))
  1406                             return false;
  1408                     if (warnStack.head.hasLint(LintCategory.UNCHECKED))
  1409                         oldWarner.warn(LintCategory.UNCHECKED);
  1410                     return true;
  1413                 if (s.isCompound()) {
  1414                     // call recursively to reuse the above code
  1415                     return visitClassType((ClassType)s, t);
  1418                 if (s.tag == CLASS || s.tag == ARRAY) {
  1419                     boolean upcast;
  1420                     if ((upcast = isSubtype(erasure(t), erasure(s)))
  1421                         || isSubtype(erasure(s), erasure(t))) {
  1422                         if (!upcast && s.tag == ARRAY) {
  1423                             if (!isReifiable(s))
  1424                                 warnStack.head.warn(LintCategory.UNCHECKED);
  1425                             return true;
  1426                         } else if (s.isRaw()) {
  1427                             return true;
  1428                         } else if (t.isRaw()) {
  1429                             if (!isUnbounded(s))
  1430                                 warnStack.head.warn(LintCategory.UNCHECKED);
  1431                             return true;
  1433                         // Assume |a| <: |b|
  1434                         final Type a = upcast ? t : s;
  1435                         final Type b = upcast ? s : t;
  1436                         final boolean HIGH = true;
  1437                         final boolean LOW = false;
  1438                         final boolean DONT_REWRITE_TYPEVARS = false;
  1439                         Type aHigh = rewriteQuantifiers(a, HIGH, DONT_REWRITE_TYPEVARS);
  1440                         Type aLow  = rewriteQuantifiers(a, LOW,  DONT_REWRITE_TYPEVARS);
  1441                         Type bHigh = rewriteQuantifiers(b, HIGH, DONT_REWRITE_TYPEVARS);
  1442                         Type bLow  = rewriteQuantifiers(b, LOW,  DONT_REWRITE_TYPEVARS);
  1443                         Type lowSub = asSub(bLow, aLow.tsym);
  1444                         Type highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
  1445                         if (highSub == null) {
  1446                             final boolean REWRITE_TYPEVARS = true;
  1447                             aHigh = rewriteQuantifiers(a, HIGH, REWRITE_TYPEVARS);
  1448                             aLow  = rewriteQuantifiers(a, LOW,  REWRITE_TYPEVARS);
  1449                             bHigh = rewriteQuantifiers(b, HIGH, REWRITE_TYPEVARS);
  1450                             bLow  = rewriteQuantifiers(b, LOW,  REWRITE_TYPEVARS);
  1451                             lowSub = asSub(bLow, aLow.tsym);
  1452                             highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
  1454                         if (highSub != null) {
  1455                             if (!(a.tsym == highSub.tsym && a.tsym == lowSub.tsym)) {
  1456                                 Assert.error(a.tsym + " != " + highSub.tsym + " != " + lowSub.tsym);
  1458                             if (!disjointTypes(aHigh.allparams(), highSub.allparams())
  1459                                 && !disjointTypes(aHigh.allparams(), lowSub.allparams())
  1460                                 && !disjointTypes(aLow.allparams(), highSub.allparams())
  1461                                 && !disjointTypes(aLow.allparams(), lowSub.allparams())) {
  1462                                 if (upcast ? giveWarning(a, b) :
  1463                                     giveWarning(b, a))
  1464                                     warnStack.head.warn(LintCategory.UNCHECKED);
  1465                                 return true;
  1468                         if (isReifiable(s))
  1469                             return isSubtypeUnchecked(a, b);
  1470                         else
  1471                             return isSubtypeUnchecked(a, b, warnStack.head);
  1474                     // Sidecast
  1475                     if (s.tag == CLASS) {
  1476                         if ((s.tsym.flags() & INTERFACE) != 0) {
  1477                             return ((t.tsym.flags() & FINAL) == 0)
  1478                                 ? sideCast(t, s, warnStack.head)
  1479                                 : sideCastFinal(t, s, warnStack.head);
  1480                         } else if ((t.tsym.flags() & INTERFACE) != 0) {
  1481                             return ((s.tsym.flags() & FINAL) == 0)
  1482                                 ? sideCast(t, s, warnStack.head)
  1483                                 : sideCastFinal(t, s, warnStack.head);
  1484                         } else {
  1485                             // unrelated class types
  1486                             return false;
  1490                 return false;
  1493             @Override
  1494             public Boolean visitArrayType(ArrayType t, Type s) {
  1495                 switch (s.tag) {
  1496                 case ERROR:
  1497                 case BOT:
  1498                     return true;
  1499                 case TYPEVAR:
  1500                     if (isCastable(s, t, noWarnings)) {
  1501                         warnStack.head.warn(LintCategory.UNCHECKED);
  1502                         return true;
  1503                     } else {
  1504                         return false;
  1506                 case CLASS:
  1507                     return isSubtype(t, s);
  1508                 case ARRAY:
  1509                     if (elemtype(t).isPrimitive() || elemtype(s).isPrimitive()) {
  1510                         return elemtype(t).tag == elemtype(s).tag;
  1511                     } else {
  1512                         return visit(elemtype(t), elemtype(s));
  1514                 default:
  1515                     return false;
  1519             @Override
  1520             public Boolean visitTypeVar(TypeVar t, Type s) {
  1521                 switch (s.tag) {
  1522                 case ERROR:
  1523                 case BOT:
  1524                     return true;
  1525                 case TYPEVAR:
  1526                     if (isSubtype(t, s)) {
  1527                         return true;
  1528                     } else if (isCastable(t.bound, s, noWarnings)) {
  1529                         warnStack.head.warn(LintCategory.UNCHECKED);
  1530                         return true;
  1531                     } else {
  1532                         return false;
  1534                 default:
  1535                     return isCastable(t.bound, s, warnStack.head);
  1539             @Override
  1540             public Boolean visitErrorType(ErrorType t, Type s) {
  1541                 return true;
  1543         };
  1544     // </editor-fold>
  1546     // <editor-fold defaultstate="collapsed" desc="disjointTypes">
  1547     public boolean disjointTypes(List<Type> ts, List<Type> ss) {
  1548         while (ts.tail != null && ss.tail != null) {
  1549             if (disjointType(ts.head, ss.head)) return true;
  1550             ts = ts.tail;
  1551             ss = ss.tail;
  1553         return false;
  1556     /**
  1557      * Two types or wildcards are considered disjoint if it can be
  1558      * proven that no type can be contained in both. It is
  1559      * conservative in that it is allowed to say that two types are
  1560      * not disjoint, even though they actually are.
  1562      * The type {@code C<X>} is castable to {@code C<Y>} exactly if
  1563      * {@code X} and {@code Y} are not disjoint.
  1564      */
  1565     public boolean disjointType(Type t, Type s) {
  1566         return disjointType.visit(t, s);
  1568     // where
  1569         private TypeRelation disjointType = new TypeRelation() {
  1571             private Set<TypePair> cache = new HashSet<TypePair>();
  1573             public Boolean visitType(Type t, Type s) {
  1574                 if (s.tag == WILDCARD)
  1575                     return visit(s, t);
  1576                 else
  1577                     return notSoftSubtypeRecursive(t, s) || notSoftSubtypeRecursive(s, t);
  1580             private boolean isCastableRecursive(Type t, Type s) {
  1581                 TypePair pair = new TypePair(t, s);
  1582                 if (cache.add(pair)) {
  1583                     try {
  1584                         return Types.this.isCastable(t, s);
  1585                     } finally {
  1586                         cache.remove(pair);
  1588                 } else {
  1589                     return true;
  1593             private boolean notSoftSubtypeRecursive(Type t, Type s) {
  1594                 TypePair pair = new TypePair(t, s);
  1595                 if (cache.add(pair)) {
  1596                     try {
  1597                         return Types.this.notSoftSubtype(t, s);
  1598                     } finally {
  1599                         cache.remove(pair);
  1601                 } else {
  1602                     return false;
  1606             @Override
  1607             public Boolean visitWildcardType(WildcardType t, Type s) {
  1608                 if (t.isUnbound())
  1609                     return false;
  1611                 if (s.tag != WILDCARD) {
  1612                     if (t.isExtendsBound())
  1613                         return notSoftSubtypeRecursive(s, t.type);
  1614                     else // isSuperBound()
  1615                         return notSoftSubtypeRecursive(t.type, s);
  1618                 if (s.isUnbound())
  1619                     return false;
  1621                 if (t.isExtendsBound()) {
  1622                     if (s.isExtendsBound())
  1623                         return !isCastableRecursive(t.type, upperBound(s));
  1624                     else if (s.isSuperBound())
  1625                         return notSoftSubtypeRecursive(lowerBound(s), t.type);
  1626                 } else if (t.isSuperBound()) {
  1627                     if (s.isExtendsBound())
  1628                         return notSoftSubtypeRecursive(t.type, upperBound(s));
  1630                 return false;
  1632         };
  1633     // </editor-fold>
  1635     // <editor-fold defaultstate="collapsed" desc="lowerBoundArgtypes">
  1636     /**
  1637      * Returns the lower bounds of the formals of a method.
  1638      */
  1639     public List<Type> lowerBoundArgtypes(Type t) {
  1640         return lowerBounds(t.getParameterTypes());
  1642     public List<Type> lowerBounds(List<Type> ts) {
  1643         return map(ts, lowerBoundMapping);
  1645     private final Mapping lowerBoundMapping = new Mapping("lowerBound") {
  1646             public Type apply(Type t) {
  1647                 return lowerBound(t);
  1649         };
  1650     // </editor-fold>
  1652     // <editor-fold defaultstate="collapsed" desc="notSoftSubtype">
  1653     /**
  1654      * This relation answers the question: is impossible that
  1655      * something of type `t' can be a subtype of `s'? This is
  1656      * different from the question "is `t' not a subtype of `s'?"
  1657      * when type variables are involved: Integer is not a subtype of T
  1658      * where {@code <T extends Number>} but it is not true that Integer cannot
  1659      * possibly be a subtype of T.
  1660      */
  1661     public boolean notSoftSubtype(Type t, Type s) {
  1662         if (t == s) return false;
  1663         if (t.tag == TYPEVAR) {
  1664             TypeVar tv = (TypeVar) t;
  1665             return !isCastable(tv.bound,
  1666                                relaxBound(s),
  1667                                noWarnings);
  1669         if (s.tag != WILDCARD)
  1670             s = upperBound(s);
  1672         return !isSubtype(t, relaxBound(s));
  1675     private Type relaxBound(Type t) {
  1676         if (t.tag == TYPEVAR) {
  1677             while (t.tag == TYPEVAR)
  1678                 t = t.getUpperBound();
  1679             t = rewriteQuantifiers(t, true, true);
  1681         return t;
  1683     // </editor-fold>
  1685     // <editor-fold defaultstate="collapsed" desc="isReifiable">
  1686     public boolean isReifiable(Type t) {
  1687         return isReifiable.visit(t);
  1689     // where
  1690         private UnaryVisitor<Boolean> isReifiable = new UnaryVisitor<Boolean>() {
  1692             public Boolean visitType(Type t, Void ignored) {
  1693                 return true;
  1696             @Override
  1697             public Boolean visitClassType(ClassType t, Void ignored) {
  1698                 if (t.isCompound())
  1699                     return false;
  1700                 else {
  1701                     if (!t.isParameterized())
  1702                         return true;
  1704                     for (Type param : t.allparams()) {
  1705                         if (!param.isUnbound())
  1706                             return false;
  1708                     return true;
  1712             @Override
  1713             public Boolean visitArrayType(ArrayType t, Void ignored) {
  1714                 return visit(t.elemtype);
  1717             @Override
  1718             public Boolean visitTypeVar(TypeVar t, Void ignored) {
  1719                 return false;
  1721         };
  1722     // </editor-fold>
  1724     // <editor-fold defaultstate="collapsed" desc="Array Utils">
  1725     public boolean isArray(Type t) {
  1726         while (t.tag == WILDCARD)
  1727             t = upperBound(t);
  1728         return t.tag == ARRAY;
  1731     /**
  1732      * The element type of an array.
  1733      */
  1734     public Type elemtype(Type t) {
  1735         switch (t.tag) {
  1736         case WILDCARD:
  1737             return elemtype(upperBound(t));
  1738         case ARRAY:
  1739             t = t.unannotatedType();
  1740             return ((ArrayType)t).elemtype;
  1741         case FORALL:
  1742             return elemtype(((ForAll)t).qtype);
  1743         case ERROR:
  1744             return t;
  1745         default:
  1746             return null;
  1750     public Type elemtypeOrType(Type t) {
  1751         Type elemtype = elemtype(t);
  1752         return elemtype != null ?
  1753             elemtype :
  1754             t;
  1757     /**
  1758      * Mapping to take element type of an arraytype
  1759      */
  1760     private Mapping elemTypeFun = new Mapping ("elemTypeFun") {
  1761         public Type apply(Type t) { return elemtype(t); }
  1762     };
  1764     /**
  1765      * The number of dimensions of an array type.
  1766      */
  1767     public int dimensions(Type t) {
  1768         int result = 0;
  1769         while (t.tag == ARRAY) {
  1770             result++;
  1771             t = elemtype(t);
  1773         return result;
  1776     /**
  1777      * Returns an ArrayType with the component type t
  1779      * @param t The component type of the ArrayType
  1780      * @return the ArrayType for the given component
  1781      */
  1782     public ArrayType makeArrayType(Type t) {
  1783         if (t.tag == VOID ||
  1784             t.tag == PACKAGE) {
  1785             Assert.error("Type t must not be a VOID or PACKAGE type, " + t.toString());
  1787         return new ArrayType(t, syms.arrayClass);
  1789     // </editor-fold>
  1791     // <editor-fold defaultstate="collapsed" desc="asSuper">
  1792     /**
  1793      * Return the (most specific) base type of t that starts with the
  1794      * given symbol.  If none exists, return null.
  1796      * @param t a type
  1797      * @param sym a symbol
  1798      */
  1799     public Type asSuper(Type t, Symbol sym) {
  1800         return asSuper.visit(t, sym);
  1802     // where
  1803         private SimpleVisitor<Type,Symbol> asSuper = new SimpleVisitor<Type,Symbol>() {
  1805             public Type visitType(Type t, Symbol sym) {
  1806                 return null;
  1809             @Override
  1810             public Type visitClassType(ClassType t, Symbol sym) {
  1811                 if (t.tsym == sym)
  1812                     return t;
  1814                 Type st = supertype(t);
  1815                 if (st.tag == CLASS || st.tag == TYPEVAR || st.tag == ERROR) {
  1816                     Type x = asSuper(st, sym);
  1817                     if (x != null)
  1818                         return x;
  1820                 if ((sym.flags() & INTERFACE) != 0) {
  1821                     for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
  1822                         Type x = asSuper(l.head, sym);
  1823                         if (x != null)
  1824                             return x;
  1827                 return null;
  1830             @Override
  1831             public Type visitArrayType(ArrayType t, Symbol sym) {
  1832                 return isSubtype(t, sym.type) ? sym.type : null;
  1835             @Override
  1836             public Type visitTypeVar(TypeVar t, Symbol sym) {
  1837                 if (t.tsym == sym)
  1838                     return t;
  1839                 else
  1840                     return asSuper(t.bound, sym);
  1843             @Override
  1844             public Type visitErrorType(ErrorType t, Symbol sym) {
  1845                 return t;
  1847         };
  1849     /**
  1850      * Return the base type of t or any of its outer types that starts
  1851      * with the given symbol.  If none exists, return null.
  1853      * @param t a type
  1854      * @param sym a symbol
  1855      */
  1856     public Type asOuterSuper(Type t, Symbol sym) {
  1857         switch (t.tag) {
  1858         case CLASS:
  1859             do {
  1860                 Type s = asSuper(t, sym);
  1861                 if (s != null) return s;
  1862                 t = t.getEnclosingType();
  1863             } while (t.tag == CLASS);
  1864             return null;
  1865         case ARRAY:
  1866             return isSubtype(t, sym.type) ? sym.type : null;
  1867         case TYPEVAR:
  1868             return asSuper(t, sym);
  1869         case ERROR:
  1870             return t;
  1871         default:
  1872             return null;
  1876     /**
  1877      * Return the base type of t or any of its enclosing types that
  1878      * starts with the given symbol.  If none exists, return null.
  1880      * @param t a type
  1881      * @param sym a symbol
  1882      */
  1883     public Type asEnclosingSuper(Type t, Symbol sym) {
  1884         switch (t.tag) {
  1885         case CLASS:
  1886             do {
  1887                 Type s = asSuper(t, sym);
  1888                 if (s != null) return s;
  1889                 Type outer = t.getEnclosingType();
  1890                 t = (outer.tag == CLASS) ? outer :
  1891                     (t.tsym.owner.enclClass() != null) ? t.tsym.owner.enclClass().type :
  1892                     Type.noType;
  1893             } while (t.tag == CLASS);
  1894             return null;
  1895         case ARRAY:
  1896             return isSubtype(t, sym.type) ? sym.type : null;
  1897         case TYPEVAR:
  1898             return asSuper(t, sym);
  1899         case ERROR:
  1900             return t;
  1901         default:
  1902             return null;
  1905     // </editor-fold>
  1907     // <editor-fold defaultstate="collapsed" desc="memberType">
  1908     /**
  1909      * The type of given symbol, seen as a member of t.
  1911      * @param t a type
  1912      * @param sym a symbol
  1913      */
  1914     public Type memberType(Type t, Symbol sym) {
  1915         return (sym.flags() & STATIC) != 0
  1916             ? sym.type
  1917             : memberType.visit(t, sym);
  1919     // where
  1920         private SimpleVisitor<Type,Symbol> memberType = new SimpleVisitor<Type,Symbol>() {
  1922             public Type visitType(Type t, Symbol sym) {
  1923                 return sym.type;
  1926             @Override
  1927             public Type visitWildcardType(WildcardType t, Symbol sym) {
  1928                 return memberType(upperBound(t), sym);
  1931             @Override
  1932             public Type visitClassType(ClassType t, Symbol sym) {
  1933                 Symbol owner = sym.owner;
  1934                 long flags = sym.flags();
  1935                 if (((flags & STATIC) == 0) && owner.type.isParameterized()) {
  1936                     Type base = asOuterSuper(t, owner);
  1937                     //if t is an intersection type T = CT & I1 & I2 ... & In
  1938                     //its supertypes CT, I1, ... In might contain wildcards
  1939                     //so we need to go through capture conversion
  1940                     base = t.isCompound() ? capture(base) : base;
  1941                     if (base != null) {
  1942                         List<Type> ownerParams = owner.type.allparams();
  1943                         List<Type> baseParams = base.allparams();
  1944                         if (ownerParams.nonEmpty()) {
  1945                             if (baseParams.isEmpty()) {
  1946                                 // then base is a raw type
  1947                                 return erasure(sym.type);
  1948                             } else {
  1949                                 return subst(sym.type, ownerParams, baseParams);
  1954                 return sym.type;
  1957             @Override
  1958             public Type visitTypeVar(TypeVar t, Symbol sym) {
  1959                 return memberType(t.bound, sym);
  1962             @Override
  1963             public Type visitErrorType(ErrorType t, Symbol sym) {
  1964                 return t;
  1966         };
  1967     // </editor-fold>
  1969     // <editor-fold defaultstate="collapsed" desc="isAssignable">
  1970     public boolean isAssignable(Type t, Type s) {
  1971         return isAssignable(t, s, noWarnings);
  1974     /**
  1975      * Is t assignable to s?<br>
  1976      * Equivalent to subtype except for constant values and raw
  1977      * types.<br>
  1978      * (not defined for Method and ForAll types)
  1979      */
  1980     public boolean isAssignable(Type t, Type s, Warner warn) {
  1981         if (t.tag == ERROR)
  1982             return true;
  1983         if (t.tag.isSubRangeOf(INT) && t.constValue() != null) {
  1984             int value = ((Number)t.constValue()).intValue();
  1985             switch (s.tag) {
  1986             case BYTE:
  1987                 if (Byte.MIN_VALUE <= value && value <= Byte.MAX_VALUE)
  1988                     return true;
  1989                 break;
  1990             case CHAR:
  1991                 if (Character.MIN_VALUE <= value && value <= Character.MAX_VALUE)
  1992                     return true;
  1993                 break;
  1994             case SHORT:
  1995                 if (Short.MIN_VALUE <= value && value <= Short.MAX_VALUE)
  1996                     return true;
  1997                 break;
  1998             case INT:
  1999                 return true;
  2000             case CLASS:
  2001                 switch (unboxedType(s).tag) {
  2002                 case BYTE:
  2003                 case CHAR:
  2004                 case SHORT:
  2005                     return isAssignable(t, unboxedType(s), warn);
  2007                 break;
  2010         return isConvertible(t, s, warn);
  2012     // </editor-fold>
  2014     // <editor-fold defaultstate="collapsed" desc="erasure">
  2015     /**
  2016      * The erasure of t {@code |t|} -- the type that results when all
  2017      * type parameters in t are deleted.
  2018      */
  2019     public Type erasure(Type t) {
  2020         return eraseNotNeeded(t)? t : erasure(t, false);
  2022     //where
  2023     private boolean eraseNotNeeded(Type t) {
  2024         // We don't want to erase primitive types and String type as that
  2025         // operation is idempotent. Also, erasing these could result in loss
  2026         // of information such as constant values attached to such types.
  2027         return (t.isPrimitive()) || (syms.stringType.tsym == t.tsym);
  2030     private Type erasure(Type t, boolean recurse) {
  2031         if (t.isPrimitive())
  2032             return t; /* fast special case */
  2033         else
  2034             return erasure.visit(t, recurse);
  2036     // where
  2037         private SimpleVisitor<Type, Boolean> erasure = new SimpleVisitor<Type, Boolean>() {
  2038             public Type visitType(Type t, Boolean recurse) {
  2039                 if (t.isPrimitive())
  2040                     return t; /*fast special case*/
  2041                 else
  2042                     return t.map(recurse ? erasureRecFun : erasureFun);
  2045             @Override
  2046             public Type visitWildcardType(WildcardType t, Boolean recurse) {
  2047                 return erasure(upperBound(t), recurse);
  2050             @Override
  2051             public Type visitClassType(ClassType t, Boolean recurse) {
  2052                 Type erased = t.tsym.erasure(Types.this);
  2053                 if (recurse) {
  2054                     erased = new ErasedClassType(erased.getEnclosingType(),erased.tsym);
  2056                 return erased;
  2059             @Override
  2060             public Type visitTypeVar(TypeVar t, Boolean recurse) {
  2061                 return erasure(t.bound, recurse);
  2064             @Override
  2065             public Type visitErrorType(ErrorType t, Boolean recurse) {
  2066                 return t;
  2069             @Override
  2070             public Type visitAnnotatedType(AnnotatedType t, Boolean recurse) {
  2071                 return new AnnotatedType(t.typeAnnotations, erasure(t.underlyingType, recurse));
  2073         };
  2075     private Mapping erasureFun = new Mapping ("erasure") {
  2076             public Type apply(Type t) { return erasure(t); }
  2077         };
  2079     private Mapping erasureRecFun = new Mapping ("erasureRecursive") {
  2080         public Type apply(Type t) { return erasureRecursive(t); }
  2081     };
  2083     public List<Type> erasure(List<Type> ts) {
  2084         return Type.map(ts, erasureFun);
  2087     public Type erasureRecursive(Type t) {
  2088         return erasure(t, true);
  2091     public List<Type> erasureRecursive(List<Type> ts) {
  2092         return Type.map(ts, erasureRecFun);
  2094     // </editor-fold>
  2096     // <editor-fold defaultstate="collapsed" desc="makeCompoundType">
  2097     /**
  2098      * Make a compound type from non-empty list of types
  2100      * @param bounds            the types from which the compound type is formed
  2101      * @param supertype         is objectType if all bounds are interfaces,
  2102      *                          null otherwise.
  2103      */
  2104     public Type makeCompoundType(List<Type> bounds) {
  2105         return makeCompoundType(bounds, bounds.head.tsym.isInterface());
  2107     public Type makeCompoundType(List<Type> bounds, boolean allInterfaces) {
  2108         Assert.check(bounds.nonEmpty());
  2109         Type firstExplicitBound = bounds.head;
  2110         if (allInterfaces) {
  2111             bounds = bounds.prepend(syms.objectType);
  2113         ClassSymbol bc =
  2114             new ClassSymbol(ABSTRACT|PUBLIC|SYNTHETIC|COMPOUND|ACYCLIC,
  2115                             Type.moreInfo
  2116                                 ? names.fromString(bounds.toString())
  2117                                 : names.empty,
  2118                             null,
  2119                             syms.noSymbol);
  2120         bc.type = new IntersectionClassType(bounds, bc, allInterfaces);
  2121         bc.erasure_field = (bounds.head.tag == TYPEVAR) ?
  2122                 syms.objectType : // error condition, recover
  2123                 erasure(firstExplicitBound);
  2124         bc.members_field = new Scope(bc);
  2125         return bc.type;
  2128     /**
  2129      * A convenience wrapper for {@link #makeCompoundType(List)}; the
  2130      * arguments are converted to a list and passed to the other
  2131      * method.  Note that this might cause a symbol completion.
  2132      * Hence, this version of makeCompoundType may not be called
  2133      * during a classfile read.
  2134      */
  2135     public Type makeCompoundType(Type bound1, Type bound2) {
  2136         return makeCompoundType(List.of(bound1, bound2));
  2138     // </editor-fold>
  2140     // <editor-fold defaultstate="collapsed" desc="supertype">
  2141     public Type supertype(Type t) {
  2142         return supertype.visit(t);
  2144     // where
  2145         private UnaryVisitor<Type> supertype = new UnaryVisitor<Type>() {
  2147             public Type visitType(Type t, Void ignored) {
  2148                 // A note on wildcards: there is no good way to
  2149                 // determine a supertype for a super bounded wildcard.
  2150                 return null;
  2153             @Override
  2154             public Type visitClassType(ClassType t, Void ignored) {
  2155                 if (t.supertype_field == null) {
  2156                     Type supertype = ((ClassSymbol)t.tsym).getSuperclass();
  2157                     // An interface has no superclass; its supertype is Object.
  2158                     if (t.isInterface())
  2159                         supertype = ((ClassType)t.tsym.type).supertype_field;
  2160                     if (t.supertype_field == null) {
  2161                         List<Type> actuals = classBound(t).allparams();
  2162                         List<Type> formals = t.tsym.type.allparams();
  2163                         if (t.hasErasedSupertypes()) {
  2164                             t.supertype_field = erasureRecursive(supertype);
  2165                         } else if (formals.nonEmpty()) {
  2166                             t.supertype_field = subst(supertype, formals, actuals);
  2168                         else {
  2169                             t.supertype_field = supertype;
  2173                 return t.supertype_field;
  2176             /**
  2177              * The supertype is always a class type. If the type
  2178              * variable's bounds start with a class type, this is also
  2179              * the supertype.  Otherwise, the supertype is
  2180              * java.lang.Object.
  2181              */
  2182             @Override
  2183             public Type visitTypeVar(TypeVar t, Void ignored) {
  2184                 if (t.bound.tag == TYPEVAR ||
  2185                     (!t.bound.isCompound() && !t.bound.isInterface())) {
  2186                     return t.bound;
  2187                 } else {
  2188                     return supertype(t.bound);
  2192             @Override
  2193             public Type visitArrayType(ArrayType t, Void ignored) {
  2194                 if (t.elemtype.isPrimitive() || isSameType(t.elemtype, syms.objectType))
  2195                     return arraySuperType();
  2196                 else
  2197                     return new ArrayType(supertype(t.elemtype), t.tsym);
  2200             @Override
  2201             public Type visitErrorType(ErrorType t, Void ignored) {
  2202                 return t;
  2204         };
  2205     // </editor-fold>
  2207     // <editor-fold defaultstate="collapsed" desc="interfaces">
  2208     /**
  2209      * Return the interfaces implemented by this class.
  2210      */
  2211     public List<Type> interfaces(Type t) {
  2212         return interfaces.visit(t);
  2214     // where
  2215         private UnaryVisitor<List<Type>> interfaces = new UnaryVisitor<List<Type>>() {
  2217             public List<Type> visitType(Type t, Void ignored) {
  2218                 return List.nil();
  2221             @Override
  2222             public List<Type> visitClassType(ClassType t, Void ignored) {
  2223                 if (t.interfaces_field == null) {
  2224                     List<Type> interfaces = ((ClassSymbol)t.tsym).getInterfaces();
  2225                     if (t.interfaces_field == null) {
  2226                         // If t.interfaces_field is null, then t must
  2227                         // be a parameterized type (not to be confused
  2228                         // with a generic type declaration).
  2229                         // Terminology:
  2230                         //    Parameterized type: List<String>
  2231                         //    Generic type declaration: class List<E> { ... }
  2232                         // So t corresponds to List<String> and
  2233                         // t.tsym.type corresponds to List<E>.
  2234                         // The reason t must be parameterized type is
  2235                         // that completion will happen as a side
  2236                         // effect of calling
  2237                         // ClassSymbol.getInterfaces.  Since
  2238                         // t.interfaces_field is null after
  2239                         // completion, we can assume that t is not the
  2240                         // type of a class/interface declaration.
  2241                         Assert.check(t != t.tsym.type, t);
  2242                         List<Type> actuals = t.allparams();
  2243                         List<Type> formals = t.tsym.type.allparams();
  2244                         if (t.hasErasedSupertypes()) {
  2245                             t.interfaces_field = erasureRecursive(interfaces);
  2246                         } else if (formals.nonEmpty()) {
  2247                             t.interfaces_field =
  2248                                 upperBounds(subst(interfaces, formals, actuals));
  2250                         else {
  2251                             t.interfaces_field = interfaces;
  2255                 return t.interfaces_field;
  2258             @Override
  2259             public List<Type> visitTypeVar(TypeVar t, Void ignored) {
  2260                 if (t.bound.isCompound())
  2261                     return interfaces(t.bound);
  2263                 if (t.bound.isInterface())
  2264                     return List.of(t.bound);
  2266                 return List.nil();
  2268         };
  2270     public boolean isDirectSuperInterface(TypeSymbol isym, TypeSymbol origin) {
  2271         for (Type i2 : interfaces(origin.type)) {
  2272             if (isym == i2.tsym) return true;
  2274         return false;
  2276     // </editor-fold>
  2278     // <editor-fold defaultstate="collapsed" desc="isDerivedRaw">
  2279     Map<Type,Boolean> isDerivedRawCache = new HashMap<Type,Boolean>();
  2281     public boolean isDerivedRaw(Type t) {
  2282         Boolean result = isDerivedRawCache.get(t);
  2283         if (result == null) {
  2284             result = isDerivedRawInternal(t);
  2285             isDerivedRawCache.put(t, result);
  2287         return result;
  2290     public boolean isDerivedRawInternal(Type t) {
  2291         if (t.isErroneous())
  2292             return false;
  2293         return
  2294             t.isRaw() ||
  2295             supertype(t) != null && isDerivedRaw(supertype(t)) ||
  2296             isDerivedRaw(interfaces(t));
  2299     public boolean isDerivedRaw(List<Type> ts) {
  2300         List<Type> l = ts;
  2301         while (l.nonEmpty() && !isDerivedRaw(l.head)) l = l.tail;
  2302         return l.nonEmpty();
  2304     // </editor-fold>
  2306     // <editor-fold defaultstate="collapsed" desc="setBounds">
  2307     /**
  2308      * Set the bounds field of the given type variable to reflect a
  2309      * (possibly multiple) list of bounds.
  2310      * @param t                 a type variable
  2311      * @param bounds            the bounds, must be nonempty
  2312      * @param supertype         is objectType if all bounds are interfaces,
  2313      *                          null otherwise.
  2314      */
  2315     public void setBounds(TypeVar t, List<Type> bounds) {
  2316         setBounds(t, bounds, bounds.head.tsym.isInterface());
  2319     /**
  2320      * Same as {@link #setBounds(Type.TypeVar,List,Type)}, except that
  2321      * third parameter is computed directly, as follows: if all
  2322      * all bounds are interface types, the computed supertype is Object,
  2323      * otherwise the supertype is simply left null (in this case, the supertype
  2324      * is assumed to be the head of the bound list passed as second argument).
  2325      * Note that this check might cause a symbol completion. Hence, this version of
  2326      * setBounds may not be called during a classfile read.
  2327      */
  2328     public void setBounds(TypeVar t, List<Type> bounds, boolean allInterfaces) {
  2329         t.bound = bounds.tail.isEmpty() ?
  2330                 bounds.head :
  2331                 makeCompoundType(bounds, allInterfaces);
  2332         t.rank_field = -1;
  2334     // </editor-fold>
  2336     // <editor-fold defaultstate="collapsed" desc="getBounds">
  2337     /**
  2338      * Return list of bounds of the given type variable.
  2339      */
  2340     public List<Type> getBounds(TypeVar t) {
  2341         if (t.bound.hasTag(NONE))
  2342             return List.nil();
  2343         else if (t.bound.isErroneous() || !t.bound.isCompound())
  2344             return List.of(t.bound);
  2345         else if ((erasure(t).tsym.flags() & INTERFACE) == 0)
  2346             return interfaces(t).prepend(supertype(t));
  2347         else
  2348             // No superclass was given in bounds.
  2349             // In this case, supertype is Object, erasure is first interface.
  2350             return interfaces(t);
  2352     // </editor-fold>
  2354     // <editor-fold defaultstate="collapsed" desc="classBound">
  2355     /**
  2356      * If the given type is a (possibly selected) type variable,
  2357      * return the bounding class of this type, otherwise return the
  2358      * type itself.
  2359      */
  2360     public Type classBound(Type t) {
  2361         return classBound.visit(t);
  2363     // where
  2364         private UnaryVisitor<Type> classBound = new UnaryVisitor<Type>() {
  2366             public Type visitType(Type t, Void ignored) {
  2367                 return t;
  2370             @Override
  2371             public Type visitClassType(ClassType t, Void ignored) {
  2372                 Type outer1 = classBound(t.getEnclosingType());
  2373                 if (outer1 != t.getEnclosingType())
  2374                     return new ClassType(outer1, t.getTypeArguments(), t.tsym);
  2375                 else
  2376                     return t;
  2379             @Override
  2380             public Type visitTypeVar(TypeVar t, Void ignored) {
  2381                 return classBound(supertype(t));
  2384             @Override
  2385             public Type visitErrorType(ErrorType t, Void ignored) {
  2386                 return t;
  2388         };
  2389     // </editor-fold>
  2391     // <editor-fold defaultstate="collapsed" desc="sub signature / override equivalence">
  2392     /**
  2393      * Returns true iff the first signature is a <em>sub
  2394      * signature</em> of the other.  This is <b>not</b> an equivalence
  2395      * relation.
  2397      * @jls section 8.4.2.
  2398      * @see #overrideEquivalent(Type t, Type s)
  2399      * @param t first signature (possibly raw).
  2400      * @param s second signature (could be subjected to erasure).
  2401      * @return true if t is a sub signature of s.
  2402      */
  2403     public boolean isSubSignature(Type t, Type s) {
  2404         return isSubSignature(t, s, true);
  2407     public boolean isSubSignature(Type t, Type s, boolean strict) {
  2408         return hasSameArgs(t, s, strict) || hasSameArgs(t, erasure(s), strict);
  2411     /**
  2412      * Returns true iff these signatures are related by <em>override
  2413      * equivalence</em>.  This is the natural extension of
  2414      * isSubSignature to an equivalence relation.
  2416      * @jls section 8.4.2.
  2417      * @see #isSubSignature(Type t, Type s)
  2418      * @param t a signature (possible raw, could be subjected to
  2419      * erasure).
  2420      * @param s a signature (possible raw, could be subjected to
  2421      * erasure).
  2422      * @return true if either argument is a sub signature of the other.
  2423      */
  2424     public boolean overrideEquivalent(Type t, Type s) {
  2425         return hasSameArgs(t, s) ||
  2426             hasSameArgs(t, erasure(s)) || hasSameArgs(erasure(t), s);
  2429     public boolean overridesObjectMethod(TypeSymbol origin, Symbol msym) {
  2430         for (Scope.Entry e = syms.objectType.tsym.members().lookup(msym.name) ; e.scope != null ; e = e.next()) {
  2431             if (msym.overrides(e.sym, origin, Types.this, true)) {
  2432                 return true;
  2435         return false;
  2438     // <editor-fold defaultstate="collapsed" desc="Determining method implementation in given site">
  2439     class ImplementationCache {
  2441         private WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>> _map =
  2442                 new WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>>();
  2444         class Entry {
  2445             final MethodSymbol cachedImpl;
  2446             final Filter<Symbol> implFilter;
  2447             final boolean checkResult;
  2448             final int prevMark;
  2450             public Entry(MethodSymbol cachedImpl,
  2451                     Filter<Symbol> scopeFilter,
  2452                     boolean checkResult,
  2453                     int prevMark) {
  2454                 this.cachedImpl = cachedImpl;
  2455                 this.implFilter = scopeFilter;
  2456                 this.checkResult = checkResult;
  2457                 this.prevMark = prevMark;
  2460             boolean matches(Filter<Symbol> scopeFilter, boolean checkResult, int mark) {
  2461                 return this.implFilter == scopeFilter &&
  2462                         this.checkResult == checkResult &&
  2463                         this.prevMark == mark;
  2467         MethodSymbol get(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
  2468             SoftReference<Map<TypeSymbol, Entry>> ref_cache = _map.get(ms);
  2469             Map<TypeSymbol, Entry> cache = ref_cache != null ? ref_cache.get() : null;
  2470             if (cache == null) {
  2471                 cache = new HashMap<TypeSymbol, Entry>();
  2472                 _map.put(ms, new SoftReference<Map<TypeSymbol, Entry>>(cache));
  2474             Entry e = cache.get(origin);
  2475             CompoundScope members = membersClosure(origin.type, true);
  2476             if (e == null ||
  2477                     !e.matches(implFilter, checkResult, members.getMark())) {
  2478                 MethodSymbol impl = implementationInternal(ms, origin, checkResult, implFilter);
  2479                 cache.put(origin, new Entry(impl, implFilter, checkResult, members.getMark()));
  2480                 return impl;
  2482             else {
  2483                 return e.cachedImpl;
  2487         private MethodSymbol implementationInternal(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
  2488             for (Type t = origin.type; t.tag == CLASS || t.tag == TYPEVAR; t = supertype(t)) {
  2489                 while (t.tag == TYPEVAR)
  2490                     t = t.getUpperBound();
  2491                 TypeSymbol c = t.tsym;
  2492                 for (Scope.Entry e = c.members().lookup(ms.name, implFilter);
  2493                      e.scope != null;
  2494                      e = e.next(implFilter)) {
  2495                     if (e.sym != null &&
  2496                              e.sym.overrides(ms, origin, Types.this, checkResult))
  2497                         return (MethodSymbol)e.sym;
  2500             return null;
  2504     private ImplementationCache implCache = new ImplementationCache();
  2506     public MethodSymbol implementation(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
  2507         return implCache.get(ms, origin, checkResult, implFilter);
  2509     // </editor-fold>
  2511     // <editor-fold defaultstate="collapsed" desc="compute transitive closure of all members in given site">
  2512     class MembersClosureCache extends SimpleVisitor<CompoundScope, Boolean> {
  2514         private WeakHashMap<TypeSymbol, Entry> _map =
  2515                 new WeakHashMap<TypeSymbol, Entry>();
  2517         class Entry {
  2518             final boolean skipInterfaces;
  2519             final CompoundScope compoundScope;
  2521             public Entry(boolean skipInterfaces, CompoundScope compoundScope) {
  2522                 this.skipInterfaces = skipInterfaces;
  2523                 this.compoundScope = compoundScope;
  2526             boolean matches(boolean skipInterfaces) {
  2527                 return this.skipInterfaces == skipInterfaces;
  2531         List<TypeSymbol> seenTypes = List.nil();
  2533         /** members closure visitor methods **/
  2535         public CompoundScope visitType(Type t, Boolean skipInterface) {
  2536             return null;
  2539         @Override
  2540         public CompoundScope visitClassType(ClassType t, Boolean skipInterface) {
  2541             if (seenTypes.contains(t.tsym)) {
  2542                 //this is possible when an interface is implemented in multiple
  2543                 //superclasses, or when a classs hierarchy is circular - in such
  2544                 //cases we don't need to recurse (empty scope is returned)
  2545                 return new CompoundScope(t.tsym);
  2547             try {
  2548                 seenTypes = seenTypes.prepend(t.tsym);
  2549                 ClassSymbol csym = (ClassSymbol)t.tsym;
  2550                 Entry e = _map.get(csym);
  2551                 if (e == null || !e.matches(skipInterface)) {
  2552                     CompoundScope membersClosure = new CompoundScope(csym);
  2553                     if (!skipInterface) {
  2554                         for (Type i : interfaces(t)) {
  2555                             membersClosure.addSubScope(visit(i, skipInterface));
  2558                     membersClosure.addSubScope(visit(supertype(t), skipInterface));
  2559                     membersClosure.addSubScope(csym.members());
  2560                     e = new Entry(skipInterface, membersClosure);
  2561                     _map.put(csym, e);
  2563                 return e.compoundScope;
  2565             finally {
  2566                 seenTypes = seenTypes.tail;
  2570         @Override
  2571         public CompoundScope visitTypeVar(TypeVar t, Boolean skipInterface) {
  2572             return visit(t.getUpperBound(), skipInterface);
  2576     private MembersClosureCache membersCache = new MembersClosureCache();
  2578     public CompoundScope membersClosure(Type site, boolean skipInterface) {
  2579         return membersCache.visit(site, skipInterface);
  2581     // </editor-fold>
  2584     //where
  2585     public List<MethodSymbol> interfaceCandidates(Type site, MethodSymbol ms) {
  2586         Filter<Symbol> filter = new MethodFilter(ms, site);
  2587         List<MethodSymbol> candidates = List.nil();
  2588         for (Symbol s : membersClosure(site, false).getElements(filter)) {
  2589             if (!site.tsym.isInterface() && !s.owner.isInterface()) {
  2590                 return List.of((MethodSymbol)s);
  2591             } else if (!candidates.contains(s)) {
  2592                 candidates = candidates.prepend((MethodSymbol)s);
  2595         return prune(candidates, ownerComparator);
  2598     public List<MethodSymbol> prune(List<MethodSymbol> methods, Comparator<MethodSymbol> cmp) {
  2599         ListBuffer<MethodSymbol> methodsMin = ListBuffer.lb();
  2600         for (MethodSymbol m1 : methods) {
  2601             boolean isMin_m1 = true;
  2602             for (MethodSymbol m2 : methods) {
  2603                 if (m1 == m2) continue;
  2604                 if (cmp.compare(m2, m1) < 0) {
  2605                     isMin_m1 = false;
  2606                     break;
  2609             if (isMin_m1)
  2610                 methodsMin.append(m1);
  2612         return methodsMin.toList();
  2615     Comparator<MethodSymbol> ownerComparator = new Comparator<MethodSymbol>() {
  2616         public int compare(MethodSymbol s1, MethodSymbol s2) {
  2617             return s1.owner.isSubClass(s2.owner, Types.this) ? -1 : 1;
  2619     };
  2620     // where
  2621             private class MethodFilter implements Filter<Symbol> {
  2623                 Symbol msym;
  2624                 Type site;
  2626                 MethodFilter(Symbol msym, Type site) {
  2627                     this.msym = msym;
  2628                     this.site = site;
  2631                 public boolean accepts(Symbol s) {
  2632                     return s.kind == Kinds.MTH &&
  2633                             s.name == msym.name &&
  2634                             s.isInheritedIn(site.tsym, Types.this) &&
  2635                             overrideEquivalent(memberType(site, s), memberType(site, msym));
  2637             };
  2638     // </editor-fold>
  2640     /**
  2641      * Does t have the same arguments as s?  It is assumed that both
  2642      * types are (possibly polymorphic) method types.  Monomorphic
  2643      * method types "have the same arguments", if their argument lists
  2644      * are equal.  Polymorphic method types "have the same arguments",
  2645      * if they have the same arguments after renaming all type
  2646      * variables of one to corresponding type variables in the other,
  2647      * where correspondence is by position in the type parameter list.
  2648      */
  2649     public boolean hasSameArgs(Type t, Type s) {
  2650         return hasSameArgs(t, s, true);
  2653     public boolean hasSameArgs(Type t, Type s, boolean strict) {
  2654         return hasSameArgs(t, s, strict ? hasSameArgs_strict : hasSameArgs_nonstrict);
  2657     private boolean hasSameArgs(Type t, Type s, TypeRelation hasSameArgs) {
  2658         return hasSameArgs.visit(t, s);
  2660     // where
  2661         private class HasSameArgs extends TypeRelation {
  2663             boolean strict;
  2665             public HasSameArgs(boolean strict) {
  2666                 this.strict = strict;
  2669             public Boolean visitType(Type t, Type s) {
  2670                 throw new AssertionError();
  2673             @Override
  2674             public Boolean visitMethodType(MethodType t, Type s) {
  2675                 return s.tag == METHOD
  2676                     && containsTypeEquivalent(t.argtypes, s.getParameterTypes());
  2679             @Override
  2680             public Boolean visitForAll(ForAll t, Type s) {
  2681                 if (s.tag != FORALL)
  2682                     return strict ? false : visitMethodType(t.asMethodType(), s);
  2684                 ForAll forAll = (ForAll)s;
  2685                 return hasSameBounds(t, forAll)
  2686                     && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
  2689             @Override
  2690             public Boolean visitErrorType(ErrorType t, Type s) {
  2691                 return false;
  2693         };
  2695         TypeRelation hasSameArgs_strict = new HasSameArgs(true);
  2696         TypeRelation hasSameArgs_nonstrict = new HasSameArgs(false);
  2698     // </editor-fold>
  2700     // <editor-fold defaultstate="collapsed" desc="subst">
  2701     public List<Type> subst(List<Type> ts,
  2702                             List<Type> from,
  2703                             List<Type> to) {
  2704         return new Subst(from, to).subst(ts);
  2707     /**
  2708      * Substitute all occurrences of a type in `from' with the
  2709      * corresponding type in `to' in 't'. Match lists `from' and `to'
  2710      * from the right: If lists have different length, discard leading
  2711      * elements of the longer list.
  2712      */
  2713     public Type subst(Type t, List<Type> from, List<Type> to) {
  2714         return new Subst(from, to).subst(t);
  2717     private class Subst extends UnaryVisitor<Type> {
  2718         List<Type> from;
  2719         List<Type> to;
  2721         public Subst(List<Type> from, List<Type> to) {
  2722             int fromLength = from.length();
  2723             int toLength = to.length();
  2724             while (fromLength > toLength) {
  2725                 fromLength--;
  2726                 from = from.tail;
  2728             while (fromLength < toLength) {
  2729                 toLength--;
  2730                 to = to.tail;
  2732             this.from = from;
  2733             this.to = to;
  2736         Type subst(Type t) {
  2737             if (from.tail == null)
  2738                 return t;
  2739             else
  2740                 return visit(t);
  2743         List<Type> subst(List<Type> ts) {
  2744             if (from.tail == null)
  2745                 return ts;
  2746             boolean wild = false;
  2747             if (ts.nonEmpty() && from.nonEmpty()) {
  2748                 Type head1 = subst(ts.head);
  2749                 List<Type> tail1 = subst(ts.tail);
  2750                 if (head1 != ts.head || tail1 != ts.tail)
  2751                     return tail1.prepend(head1);
  2753             return ts;
  2756         public Type visitType(Type t, Void ignored) {
  2757             return t;
  2760         @Override
  2761         public Type visitMethodType(MethodType t, Void ignored) {
  2762             List<Type> argtypes = subst(t.argtypes);
  2763             Type restype = subst(t.restype);
  2764             List<Type> thrown = subst(t.thrown);
  2765             if (argtypes == t.argtypes &&
  2766                 restype == t.restype &&
  2767                 thrown == t.thrown)
  2768                 return t;
  2769             else
  2770                 return new MethodType(argtypes, restype, thrown, t.tsym);
  2773         @Override
  2774         public Type visitTypeVar(TypeVar t, Void ignored) {
  2775             for (List<Type> from = this.from, to = this.to;
  2776                  from.nonEmpty();
  2777                  from = from.tail, to = to.tail) {
  2778                 if (t == from.head) {
  2779                     return to.head.withTypeVar(t);
  2782             return t;
  2785         @Override
  2786         public Type visitClassType(ClassType t, Void ignored) {
  2787             if (!t.isCompound()) {
  2788                 List<Type> typarams = t.getTypeArguments();
  2789                 List<Type> typarams1 = subst(typarams);
  2790                 Type outer = t.getEnclosingType();
  2791                 Type outer1 = subst(outer);
  2792                 if (typarams1 == typarams && outer1 == outer)
  2793                     return t;
  2794                 else
  2795                     return new ClassType(outer1, typarams1, t.tsym);
  2796             } else {
  2797                 Type st = subst(supertype(t));
  2798                 List<Type> is = upperBounds(subst(interfaces(t)));
  2799                 if (st == supertype(t) && is == interfaces(t))
  2800                     return t;
  2801                 else
  2802                     return makeCompoundType(is.prepend(st));
  2806         @Override
  2807         public Type visitWildcardType(WildcardType t, Void ignored) {
  2808             Type bound = t.type;
  2809             if (t.kind != BoundKind.UNBOUND)
  2810                 bound = subst(bound);
  2811             if (bound == t.type) {
  2812                 return t;
  2813             } else {
  2814                 if (t.isExtendsBound() && bound.isExtendsBound())
  2815                     bound = upperBound(bound);
  2816                 return new WildcardType(bound, t.kind, syms.boundClass, t.bound);
  2820         @Override
  2821         public Type visitArrayType(ArrayType t, Void ignored) {
  2822             Type elemtype = subst(t.elemtype);
  2823             if (elemtype == t.elemtype)
  2824                 return t;
  2825             else
  2826                 return new ArrayType(upperBound(elemtype), t.tsym);
  2829         @Override
  2830         public Type visitForAll(ForAll t, Void ignored) {
  2831             if (Type.containsAny(to, t.tvars)) {
  2832                 //perform alpha-renaming of free-variables in 't'
  2833                 //if 'to' types contain variables that are free in 't'
  2834                 List<Type> freevars = newInstances(t.tvars);
  2835                 t = new ForAll(freevars,
  2836                         Types.this.subst(t.qtype, t.tvars, freevars));
  2838             List<Type> tvars1 = substBounds(t.tvars, from, to);
  2839             Type qtype1 = subst(t.qtype);
  2840             if (tvars1 == t.tvars && qtype1 == t.qtype) {
  2841                 return t;
  2842             } else if (tvars1 == t.tvars) {
  2843                 return new ForAll(tvars1, qtype1);
  2844             } else {
  2845                 return new ForAll(tvars1, Types.this.subst(qtype1, t.tvars, tvars1));
  2849         @Override
  2850         public Type visitErrorType(ErrorType t, Void ignored) {
  2851             return t;
  2855     public List<Type> substBounds(List<Type> tvars,
  2856                                   List<Type> from,
  2857                                   List<Type> to) {
  2858         if (tvars.isEmpty())
  2859             return tvars;
  2860         ListBuffer<Type> newBoundsBuf = lb();
  2861         boolean changed = false;
  2862         // calculate new bounds
  2863         for (Type t : tvars) {
  2864             TypeVar tv = (TypeVar) t;
  2865             Type bound = subst(tv.bound, from, to);
  2866             if (bound != tv.bound)
  2867                 changed = true;
  2868             newBoundsBuf.append(bound);
  2870         if (!changed)
  2871             return tvars;
  2872         ListBuffer<Type> newTvars = lb();
  2873         // create new type variables without bounds
  2874         for (Type t : tvars) {
  2875             newTvars.append(new TypeVar(t.tsym, null, syms.botType));
  2877         // the new bounds should use the new type variables in place
  2878         // of the old
  2879         List<Type> newBounds = newBoundsBuf.toList();
  2880         from = tvars;
  2881         to = newTvars.toList();
  2882         for (; !newBounds.isEmpty(); newBounds = newBounds.tail) {
  2883             newBounds.head = subst(newBounds.head, from, to);
  2885         newBounds = newBoundsBuf.toList();
  2886         // set the bounds of new type variables to the new bounds
  2887         for (Type t : newTvars.toList()) {
  2888             TypeVar tv = (TypeVar) t;
  2889             tv.bound = newBounds.head;
  2890             newBounds = newBounds.tail;
  2892         return newTvars.toList();
  2895     public TypeVar substBound(TypeVar t, List<Type> from, List<Type> to) {
  2896         Type bound1 = subst(t.bound, from, to);
  2897         if (bound1 == t.bound)
  2898             return t;
  2899         else {
  2900             // create new type variable without bounds
  2901             TypeVar tv = new TypeVar(t.tsym, null, syms.botType);
  2902             // the new bound should use the new type variable in place
  2903             // of the old
  2904             tv.bound = subst(bound1, List.<Type>of(t), List.<Type>of(tv));
  2905             return tv;
  2908     // </editor-fold>
  2910     // <editor-fold defaultstate="collapsed" desc="hasSameBounds">
  2911     /**
  2912      * Does t have the same bounds for quantified variables as s?
  2913      */
  2914     boolean hasSameBounds(ForAll t, ForAll s) {
  2915         List<Type> l1 = t.tvars;
  2916         List<Type> l2 = s.tvars;
  2917         while (l1.nonEmpty() && l2.nonEmpty() &&
  2918                isSameType(l1.head.getUpperBound(),
  2919                           subst(l2.head.getUpperBound(),
  2920                                 s.tvars,
  2921                                 t.tvars))) {
  2922             l1 = l1.tail;
  2923             l2 = l2.tail;
  2925         return l1.isEmpty() && l2.isEmpty();
  2927     // </editor-fold>
  2929     // <editor-fold defaultstate="collapsed" desc="newInstances">
  2930     /** Create new vector of type variables from list of variables
  2931      *  changing all recursive bounds from old to new list.
  2932      */
  2933     public List<Type> newInstances(List<Type> tvars) {
  2934         List<Type> tvars1 = Type.map(tvars, newInstanceFun);
  2935         for (List<Type> l = tvars1; l.nonEmpty(); l = l.tail) {
  2936             TypeVar tv = (TypeVar) l.head;
  2937             tv.bound = subst(tv.bound, tvars, tvars1);
  2939         return tvars1;
  2941     private static final Mapping newInstanceFun = new Mapping("newInstanceFun") {
  2942             public Type apply(Type t) { return new TypeVar(t.tsym, t.getUpperBound(), t.getLowerBound()); }
  2943         };
  2944     // </editor-fold>
  2946     public Type createMethodTypeWithParameters(Type original, List<Type> newParams) {
  2947         return original.accept(methodWithParameters, newParams);
  2949     // where
  2950         private final MapVisitor<List<Type>> methodWithParameters = new MapVisitor<List<Type>>() {
  2951             public Type visitType(Type t, List<Type> newParams) {
  2952                 throw new IllegalArgumentException("Not a method type: " + t);
  2954             public Type visitMethodType(MethodType t, List<Type> newParams) {
  2955                 return new MethodType(newParams, t.restype, t.thrown, t.tsym);
  2957             public Type visitForAll(ForAll t, List<Type> newParams) {
  2958                 return new ForAll(t.tvars, t.qtype.accept(this, newParams));
  2960         };
  2962     public Type createMethodTypeWithThrown(Type original, List<Type> newThrown) {
  2963         return original.accept(methodWithThrown, newThrown);
  2965     // where
  2966         private final MapVisitor<List<Type>> methodWithThrown = new MapVisitor<List<Type>>() {
  2967             public Type visitType(Type t, List<Type> newThrown) {
  2968                 throw new IllegalArgumentException("Not a method type: " + t);
  2970             public Type visitMethodType(MethodType t, List<Type> newThrown) {
  2971                 return new MethodType(t.argtypes, t.restype, newThrown, t.tsym);
  2973             public Type visitForAll(ForAll t, List<Type> newThrown) {
  2974                 return new ForAll(t.tvars, t.qtype.accept(this, newThrown));
  2976         };
  2978     public Type createMethodTypeWithReturn(Type original, Type newReturn) {
  2979         return original.accept(methodWithReturn, newReturn);
  2981     // where
  2982         private final MapVisitor<Type> methodWithReturn = new MapVisitor<Type>() {
  2983             public Type visitType(Type t, Type newReturn) {
  2984                 throw new IllegalArgumentException("Not a method type: " + t);
  2986             public Type visitMethodType(MethodType t, Type newReturn) {
  2987                 return new MethodType(t.argtypes, newReturn, t.thrown, t.tsym);
  2989             public Type visitForAll(ForAll t, Type newReturn) {
  2990                 return new ForAll(t.tvars, t.qtype.accept(this, newReturn));
  2992         };
  2994     // <editor-fold defaultstate="collapsed" desc="createErrorType">
  2995     public Type createErrorType(Type originalType) {
  2996         return new ErrorType(originalType, syms.errSymbol);
  2999     public Type createErrorType(ClassSymbol c, Type originalType) {
  3000         return new ErrorType(c, originalType);
  3003     public Type createErrorType(Name name, TypeSymbol container, Type originalType) {
  3004         return new ErrorType(name, container, originalType);
  3006     // </editor-fold>
  3008     // <editor-fold defaultstate="collapsed" desc="rank">
  3009     /**
  3010      * The rank of a class is the length of the longest path between
  3011      * the class and java.lang.Object in the class inheritance
  3012      * graph. Undefined for all but reference types.
  3013      */
  3014     public int rank(Type t) {
  3015         t = t.unannotatedType();
  3016         switch(t.tag) {
  3017         case CLASS: {
  3018             ClassType cls = (ClassType)t;
  3019             if (cls.rank_field < 0) {
  3020                 Name fullname = cls.tsym.getQualifiedName();
  3021                 if (fullname == names.java_lang_Object)
  3022                     cls.rank_field = 0;
  3023                 else {
  3024                     int r = rank(supertype(cls));
  3025                     for (List<Type> l = interfaces(cls);
  3026                          l.nonEmpty();
  3027                          l = l.tail) {
  3028                         if (rank(l.head) > r)
  3029                             r = rank(l.head);
  3031                     cls.rank_field = r + 1;
  3034             return cls.rank_field;
  3036         case TYPEVAR: {
  3037             TypeVar tvar = (TypeVar)t;
  3038             if (tvar.rank_field < 0) {
  3039                 int r = rank(supertype(tvar));
  3040                 for (List<Type> l = interfaces(tvar);
  3041                      l.nonEmpty();
  3042                      l = l.tail) {
  3043                     if (rank(l.head) > r) r = rank(l.head);
  3045                 tvar.rank_field = r + 1;
  3047             return tvar.rank_field;
  3049         case ERROR:
  3050             return 0;
  3051         default:
  3052             throw new AssertionError();
  3055     // </editor-fold>
  3057     /**
  3058      * Helper method for generating a string representation of a given type
  3059      * accordingly to a given locale
  3060      */
  3061     public String toString(Type t, Locale locale) {
  3062         return Printer.createStandardPrinter(messages).visit(t, locale);
  3065     /**
  3066      * Helper method for generating a string representation of a given type
  3067      * accordingly to a given locale
  3068      */
  3069     public String toString(Symbol t, Locale locale) {
  3070         return Printer.createStandardPrinter(messages).visit(t, locale);
  3073     // <editor-fold defaultstate="collapsed" desc="toString">
  3074     /**
  3075      * This toString is slightly more descriptive than the one on Type.
  3077      * @deprecated Types.toString(Type t, Locale l) provides better support
  3078      * for localization
  3079      */
  3080     @Deprecated
  3081     public String toString(Type t) {
  3082         if (t.tag == FORALL) {
  3083             ForAll forAll = (ForAll)t;
  3084             return typaramsString(forAll.tvars) + forAll.qtype;
  3086         return "" + t;
  3088     // where
  3089         private String typaramsString(List<Type> tvars) {
  3090             StringBuilder s = new StringBuilder();
  3091             s.append('<');
  3092             boolean first = true;
  3093             for (Type t : tvars) {
  3094                 if (!first) s.append(", ");
  3095                 first = false;
  3096                 appendTyparamString(((TypeVar)t), s);
  3098             s.append('>');
  3099             return s.toString();
  3101         private void appendTyparamString(TypeVar t, StringBuilder buf) {
  3102             buf.append(t);
  3103             if (t.bound == null ||
  3104                 t.bound.tsym.getQualifiedName() == names.java_lang_Object)
  3105                 return;
  3106             buf.append(" extends "); // Java syntax; no need for i18n
  3107             Type bound = t.bound;
  3108             if (!bound.isCompound()) {
  3109                 buf.append(bound);
  3110             } else if ((erasure(t).tsym.flags() & INTERFACE) == 0) {
  3111                 buf.append(supertype(t));
  3112                 for (Type intf : interfaces(t)) {
  3113                     buf.append('&');
  3114                     buf.append(intf);
  3116             } else {
  3117                 // No superclass was given in bounds.
  3118                 // In this case, supertype is Object, erasure is first interface.
  3119                 boolean first = true;
  3120                 for (Type intf : interfaces(t)) {
  3121                     if (!first) buf.append('&');
  3122                     first = false;
  3123                     buf.append(intf);
  3127     // </editor-fold>
  3129     // <editor-fold defaultstate="collapsed" desc="Determining least upper bounds of types">
  3130     /**
  3131      * A cache for closures.
  3133      * <p>A closure is a list of all the supertypes and interfaces of
  3134      * a class or interface type, ordered by ClassSymbol.precedes
  3135      * (that is, subclasses come first, arbitrary but fixed
  3136      * otherwise).
  3137      */
  3138     private Map<Type,List<Type>> closureCache = new HashMap<Type,List<Type>>();
  3140     /**
  3141      * Returns the closure of a class or interface type.
  3142      */
  3143     public List<Type> closure(Type t) {
  3144         List<Type> cl = closureCache.get(t);
  3145         if (cl == null) {
  3146             Type st = supertype(t);
  3147             if (!t.isCompound()) {
  3148                 if (st.tag == CLASS) {
  3149                     cl = insert(closure(st), t);
  3150                 } else if (st.tag == TYPEVAR) {
  3151                     cl = closure(st).prepend(t);
  3152                 } else {
  3153                     cl = List.of(t);
  3155             } else {
  3156                 cl = closure(supertype(t));
  3158             for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail)
  3159                 cl = union(cl, closure(l.head));
  3160             closureCache.put(t, cl);
  3162         return cl;
  3165     /**
  3166      * Insert a type in a closure
  3167      */
  3168     public List<Type> insert(List<Type> cl, Type t) {
  3169         if (cl.isEmpty() || t.tsym.precedes(cl.head.tsym, this)) {
  3170             return cl.prepend(t);
  3171         } else if (cl.head.tsym.precedes(t.tsym, this)) {
  3172             return insert(cl.tail, t).prepend(cl.head);
  3173         } else {
  3174             return cl;
  3178     /**
  3179      * Form the union of two closures
  3180      */
  3181     public List<Type> union(List<Type> cl1, List<Type> cl2) {
  3182         if (cl1.isEmpty()) {
  3183             return cl2;
  3184         } else if (cl2.isEmpty()) {
  3185             return cl1;
  3186         } else if (cl1.head.tsym.precedes(cl2.head.tsym, this)) {
  3187             return union(cl1.tail, cl2).prepend(cl1.head);
  3188         } else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) {
  3189             return union(cl1, cl2.tail).prepend(cl2.head);
  3190         } else {
  3191             return union(cl1.tail, cl2.tail).prepend(cl1.head);
  3195     /**
  3196      * Intersect two closures
  3197      */
  3198     public List<Type> intersect(List<Type> cl1, List<Type> cl2) {
  3199         if (cl1 == cl2)
  3200             return cl1;
  3201         if (cl1.isEmpty() || cl2.isEmpty())
  3202             return List.nil();
  3203         if (cl1.head.tsym.precedes(cl2.head.tsym, this))
  3204             return intersect(cl1.tail, cl2);
  3205         if (cl2.head.tsym.precedes(cl1.head.tsym, this))
  3206             return intersect(cl1, cl2.tail);
  3207         if (isSameType(cl1.head, cl2.head))
  3208             return intersect(cl1.tail, cl2.tail).prepend(cl1.head);
  3209         if (cl1.head.tsym == cl2.head.tsym &&
  3210             cl1.head.tag == CLASS && cl2.head.tag == CLASS) {
  3211             if (cl1.head.isParameterized() && cl2.head.isParameterized()) {
  3212                 Type merge = merge(cl1.head,cl2.head);
  3213                 return intersect(cl1.tail, cl2.tail).prepend(merge);
  3215             if (cl1.head.isRaw() || cl2.head.isRaw())
  3216                 return intersect(cl1.tail, cl2.tail).prepend(erasure(cl1.head));
  3218         return intersect(cl1.tail, cl2.tail);
  3220     // where
  3221         class TypePair {
  3222             final Type t1;
  3223             final Type t2;
  3224             TypePair(Type t1, Type t2) {
  3225                 this.t1 = t1;
  3226                 this.t2 = t2;
  3228             @Override
  3229             public int hashCode() {
  3230                 return 127 * Types.this.hashCode(t1) + Types.this.hashCode(t2);
  3232             @Override
  3233             public boolean equals(Object obj) {
  3234                 if (!(obj instanceof TypePair))
  3235                     return false;
  3236                 TypePair typePair = (TypePair)obj;
  3237                 return isSameType(t1, typePair.t1)
  3238                     && isSameType(t2, typePair.t2);
  3241         Set<TypePair> mergeCache = new HashSet<TypePair>();
  3242         private Type merge(Type c1, Type c2) {
  3243             ClassType class1 = (ClassType) c1;
  3244             List<Type> act1 = class1.getTypeArguments();
  3245             ClassType class2 = (ClassType) c2;
  3246             List<Type> act2 = class2.getTypeArguments();
  3247             ListBuffer<Type> merged = new ListBuffer<Type>();
  3248             List<Type> typarams = class1.tsym.type.getTypeArguments();
  3250             while (act1.nonEmpty() && act2.nonEmpty() && typarams.nonEmpty()) {
  3251                 if (containsType(act1.head, act2.head)) {
  3252                     merged.append(act1.head);
  3253                 } else if (containsType(act2.head, act1.head)) {
  3254                     merged.append(act2.head);
  3255                 } else {
  3256                     TypePair pair = new TypePair(c1, c2);
  3257                     Type m;
  3258                     if (mergeCache.add(pair)) {
  3259                         m = new WildcardType(lub(upperBound(act1.head),
  3260                                                  upperBound(act2.head)),
  3261                                              BoundKind.EXTENDS,
  3262                                              syms.boundClass);
  3263                         mergeCache.remove(pair);
  3264                     } else {
  3265                         m = new WildcardType(syms.objectType,
  3266                                              BoundKind.UNBOUND,
  3267                                              syms.boundClass);
  3269                     merged.append(m.withTypeVar(typarams.head));
  3271                 act1 = act1.tail;
  3272                 act2 = act2.tail;
  3273                 typarams = typarams.tail;
  3275             Assert.check(act1.isEmpty() && act2.isEmpty() && typarams.isEmpty());
  3276             return new ClassType(class1.getEnclosingType(), merged.toList(), class1.tsym);
  3279     /**
  3280      * Return the minimum type of a closure, a compound type if no
  3281      * unique minimum exists.
  3282      */
  3283     private Type compoundMin(List<Type> cl) {
  3284         if (cl.isEmpty()) return syms.objectType;
  3285         List<Type> compound = closureMin(cl);
  3286         if (compound.isEmpty())
  3287             return null;
  3288         else if (compound.tail.isEmpty())
  3289             return compound.head;
  3290         else
  3291             return makeCompoundType(compound);
  3294     /**
  3295      * Return the minimum types of a closure, suitable for computing
  3296      * compoundMin or glb.
  3297      */
  3298     private List<Type> closureMin(List<Type> cl) {
  3299         ListBuffer<Type> classes = lb();
  3300         ListBuffer<Type> interfaces = lb();
  3301         while (!cl.isEmpty()) {
  3302             Type current = cl.head;
  3303             if (current.isInterface())
  3304                 interfaces.append(current);
  3305             else
  3306                 classes.append(current);
  3307             ListBuffer<Type> candidates = lb();
  3308             for (Type t : cl.tail) {
  3309                 if (!isSubtypeNoCapture(current, t))
  3310                     candidates.append(t);
  3312             cl = candidates.toList();
  3314         return classes.appendList(interfaces).toList();
  3317     /**
  3318      * Return the least upper bound of pair of types.  if the lub does
  3319      * not exist return null.
  3320      */
  3321     public Type lub(Type t1, Type t2) {
  3322         return lub(List.of(t1, t2));
  3325     /**
  3326      * Return the least upper bound (lub) of set of types.  If the lub
  3327      * does not exist return the type of null (bottom).
  3328      */
  3329     public Type lub(List<Type> ts) {
  3330         final int ARRAY_BOUND = 1;
  3331         final int CLASS_BOUND = 2;
  3332         int boundkind = 0;
  3333         for (Type t : ts) {
  3334             switch (t.tag) {
  3335             case CLASS:
  3336                 boundkind |= CLASS_BOUND;
  3337                 break;
  3338             case ARRAY:
  3339                 boundkind |= ARRAY_BOUND;
  3340                 break;
  3341             case  TYPEVAR:
  3342                 do {
  3343                     t = t.getUpperBound();
  3344                 } while (t.tag == TYPEVAR);
  3345                 if (t.tag == ARRAY) {
  3346                     boundkind |= ARRAY_BOUND;
  3347                 } else {
  3348                     boundkind |= CLASS_BOUND;
  3350                 break;
  3351             default:
  3352                 if (t.isPrimitive())
  3353                     return syms.errType;
  3356         switch (boundkind) {
  3357         case 0:
  3358             return syms.botType;
  3360         case ARRAY_BOUND:
  3361             // calculate lub(A[], B[])
  3362             List<Type> elements = Type.map(ts, elemTypeFun);
  3363             for (Type t : elements) {
  3364                 if (t.isPrimitive()) {
  3365                     // if a primitive type is found, then return
  3366                     // arraySuperType unless all the types are the
  3367                     // same
  3368                     Type first = ts.head;
  3369                     for (Type s : ts.tail) {
  3370                         if (!isSameType(first, s)) {
  3371                              // lub(int[], B[]) is Cloneable & Serializable
  3372                             return arraySuperType();
  3375                     // all the array types are the same, return one
  3376                     // lub(int[], int[]) is int[]
  3377                     return first;
  3380             // lub(A[], B[]) is lub(A, B)[]
  3381             return new ArrayType(lub(elements), syms.arrayClass);
  3383         case CLASS_BOUND:
  3384             // calculate lub(A, B)
  3385             while (ts.head.tag != CLASS && ts.head.tag != TYPEVAR)
  3386                 ts = ts.tail;
  3387             Assert.check(!ts.isEmpty());
  3388             //step 1 - compute erased candidate set (EC)
  3389             List<Type> cl = erasedSupertypes(ts.head);
  3390             for (Type t : ts.tail) {
  3391                 if (t.tag == CLASS || t.tag == TYPEVAR)
  3392                     cl = intersect(cl, erasedSupertypes(t));
  3394             //step 2 - compute minimal erased candidate set (MEC)
  3395             List<Type> mec = closureMin(cl);
  3396             //step 3 - for each element G in MEC, compute lci(Inv(G))
  3397             List<Type> candidates = List.nil();
  3398             for (Type erasedSupertype : mec) {
  3399                 List<Type> lci = List.of(asSuper(ts.head, erasedSupertype.tsym));
  3400                 for (Type t : ts) {
  3401                     lci = intersect(lci, List.of(asSuper(t, erasedSupertype.tsym)));
  3403                 candidates = candidates.appendList(lci);
  3405             //step 4 - let MEC be { G1, G2 ... Gn }, then we have that
  3406             //lub = lci(Inv(G1)) & lci(Inv(G2)) & ... & lci(Inv(Gn))
  3407             return compoundMin(candidates);
  3409         default:
  3410             // calculate lub(A, B[])
  3411             List<Type> classes = List.of(arraySuperType());
  3412             for (Type t : ts) {
  3413                 if (t.tag != ARRAY) // Filter out any arrays
  3414                     classes = classes.prepend(t);
  3416             // lub(A, B[]) is lub(A, arraySuperType)
  3417             return lub(classes);
  3420     // where
  3421         List<Type> erasedSupertypes(Type t) {
  3422             ListBuffer<Type> buf = lb();
  3423             for (Type sup : closure(t)) {
  3424                 if (sup.tag == TYPEVAR) {
  3425                     buf.append(sup);
  3426                 } else {
  3427                     buf.append(erasure(sup));
  3430             return buf.toList();
  3433         private Type arraySuperType = null;
  3434         private Type arraySuperType() {
  3435             // initialized lazily to avoid problems during compiler startup
  3436             if (arraySuperType == null) {
  3437                 synchronized (this) {
  3438                     if (arraySuperType == null) {
  3439                         // JLS 10.8: all arrays implement Cloneable and Serializable.
  3440                         arraySuperType = makeCompoundType(List.of(syms.serializableType,
  3441                                                                   syms.cloneableType), true);
  3445             return arraySuperType;
  3447     // </editor-fold>
  3449     // <editor-fold defaultstate="collapsed" desc="Greatest lower bound">
  3450     public Type glb(List<Type> ts) {
  3451         Type t1 = ts.head;
  3452         for (Type t2 : ts.tail) {
  3453             if (t1.isErroneous())
  3454                 return t1;
  3455             t1 = glb(t1, t2);
  3457         return t1;
  3459     //where
  3460     public Type glb(Type t, Type s) {
  3461         if (s == null)
  3462             return t;
  3463         else if (t.isPrimitive() || s.isPrimitive())
  3464             return syms.errType;
  3465         else if (isSubtypeNoCapture(t, s))
  3466             return t;
  3467         else if (isSubtypeNoCapture(s, t))
  3468             return s;
  3470         List<Type> closure = union(closure(t), closure(s));
  3471         List<Type> bounds = closureMin(closure);
  3473         if (bounds.isEmpty()) {             // length == 0
  3474             return syms.objectType;
  3475         } else if (bounds.tail.isEmpty()) { // length == 1
  3476             return bounds.head;
  3477         } else {                            // length > 1
  3478             int classCount = 0;
  3479             for (Type bound : bounds)
  3480                 if (!bound.isInterface())
  3481                     classCount++;
  3482             if (classCount > 1)
  3483                 return createErrorType(t);
  3485         return makeCompoundType(bounds);
  3487     // </editor-fold>
  3489     // <editor-fold defaultstate="collapsed" desc="hashCode">
  3490     /**
  3491      * Compute a hash code on a type.
  3492      */
  3493     public int hashCode(Type t) {
  3494         return hashCode.visit(t);
  3496     // where
  3497         private static final UnaryVisitor<Integer> hashCode = new UnaryVisitor<Integer>() {
  3499             public Integer visitType(Type t, Void ignored) {
  3500                 return t.tag.ordinal();
  3503             @Override
  3504             public Integer visitClassType(ClassType t, Void ignored) {
  3505                 int result = visit(t.getEnclosingType());
  3506                 result *= 127;
  3507                 result += t.tsym.flatName().hashCode();
  3508                 for (Type s : t.getTypeArguments()) {
  3509                     result *= 127;
  3510                     result += visit(s);
  3512                 return result;
  3515             @Override
  3516             public Integer visitMethodType(MethodType t, Void ignored) {
  3517                 int h = METHOD.ordinal();
  3518                 for (List<Type> thisargs = t.argtypes;
  3519                      thisargs.tail != null;
  3520                      thisargs = thisargs.tail)
  3521                     h = (h << 5) + visit(thisargs.head);
  3522                 return (h << 5) + visit(t.restype);
  3525             @Override
  3526             public Integer visitWildcardType(WildcardType t, Void ignored) {
  3527                 int result = t.kind.hashCode();
  3528                 if (t.type != null) {
  3529                     result *= 127;
  3530                     result += visit(t.type);
  3532                 return result;
  3535             @Override
  3536             public Integer visitArrayType(ArrayType t, Void ignored) {
  3537                 return visit(t.elemtype) + 12;
  3540             @Override
  3541             public Integer visitTypeVar(TypeVar t, Void ignored) {
  3542                 return System.identityHashCode(t.tsym);
  3545             @Override
  3546             public Integer visitUndetVar(UndetVar t, Void ignored) {
  3547                 return System.identityHashCode(t);
  3550             @Override
  3551             public Integer visitErrorType(ErrorType t, Void ignored) {
  3552                 return 0;
  3554         };
  3555     // </editor-fold>
  3557     // <editor-fold defaultstate="collapsed" desc="Return-Type-Substitutable">
  3558     /**
  3559      * Does t have a result that is a subtype of the result type of s,
  3560      * suitable for covariant returns?  It is assumed that both types
  3561      * are (possibly polymorphic) method types.  Monomorphic method
  3562      * types are handled in the obvious way.  Polymorphic method types
  3563      * require renaming all type variables of one to corresponding
  3564      * type variables in the other, where correspondence is by
  3565      * position in the type parameter list. */
  3566     public boolean resultSubtype(Type t, Type s, Warner warner) {
  3567         List<Type> tvars = t.getTypeArguments();
  3568         List<Type> svars = s.getTypeArguments();
  3569         Type tres = t.getReturnType();
  3570         Type sres = subst(s.getReturnType(), svars, tvars);
  3571         return covariantReturnType(tres, sres, warner);
  3574     /**
  3575      * Return-Type-Substitutable.
  3576      * @jls section 8.4.5
  3577      */
  3578     public boolean returnTypeSubstitutable(Type r1, Type r2) {
  3579         if (hasSameArgs(r1, r2))
  3580             return resultSubtype(r1, r2, noWarnings);
  3581         else
  3582             return covariantReturnType(r1.getReturnType(),
  3583                                        erasure(r2.getReturnType()),
  3584                                        noWarnings);
  3587     public boolean returnTypeSubstitutable(Type r1,
  3588                                            Type r2, Type r2res,
  3589                                            Warner warner) {
  3590         if (isSameType(r1.getReturnType(), r2res))
  3591             return true;
  3592         if (r1.getReturnType().isPrimitive() || r2res.isPrimitive())
  3593             return false;
  3595         if (hasSameArgs(r1, r2))
  3596             return covariantReturnType(r1.getReturnType(), r2res, warner);
  3597         if (!allowCovariantReturns)
  3598             return false;
  3599         if (isSubtypeUnchecked(r1.getReturnType(), r2res, warner))
  3600             return true;
  3601         if (!isSubtype(r1.getReturnType(), erasure(r2res)))
  3602             return false;
  3603         warner.warn(LintCategory.UNCHECKED);
  3604         return true;
  3607     /**
  3608      * Is t an appropriate return type in an overrider for a
  3609      * method that returns s?
  3610      */
  3611     public boolean covariantReturnType(Type t, Type s, Warner warner) {
  3612         return
  3613             isSameType(t, s) ||
  3614             allowCovariantReturns &&
  3615             !t.isPrimitive() &&
  3616             !s.isPrimitive() &&
  3617             isAssignable(t, s, warner);
  3619     // </editor-fold>
  3621     // <editor-fold defaultstate="collapsed" desc="Box/unbox support">
  3622     /**
  3623      * Return the class that boxes the given primitive.
  3624      */
  3625     public ClassSymbol boxedClass(Type t) {
  3626         return reader.enterClass(syms.boxedName[t.tag.ordinal()]);
  3629     /**
  3630      * Return the boxed type if 't' is primitive, otherwise return 't' itself.
  3631      */
  3632     public Type boxedTypeOrType(Type t) {
  3633         return t.isPrimitive() ?
  3634             boxedClass(t).type :
  3635             t;
  3638     /**
  3639      * Return the primitive type corresponding to a boxed type.
  3640      */
  3641     public Type unboxedType(Type t) {
  3642         if (allowBoxing) {
  3643             for (int i=0; i<syms.boxedName.length; i++) {
  3644                 Name box = syms.boxedName[i];
  3645                 if (box != null &&
  3646                     asSuper(t, reader.enterClass(box)) != null)
  3647                     return syms.typeOfTag[i];
  3650         return Type.noType;
  3653     /**
  3654      * Return the unboxed type if 't' is a boxed class, otherwise return 't' itself.
  3655      */
  3656     public Type unboxedTypeOrType(Type t) {
  3657         Type unboxedType = unboxedType(t);
  3658         return unboxedType.tag == NONE ? t : unboxedType;
  3660     // </editor-fold>
  3662     // <editor-fold defaultstate="collapsed" desc="Capture conversion">
  3663     /*
  3664      * JLS 5.1.10 Capture Conversion:
  3666      * Let G name a generic type declaration with n formal type
  3667      * parameters A1 ... An with corresponding bounds U1 ... Un. There
  3668      * exists a capture conversion from G<T1 ... Tn> to G<S1 ... Sn>,
  3669      * where, for 1 <= i <= n:
  3671      * + If Ti is a wildcard type argument (4.5.1) of the form ? then
  3672      *   Si is a fresh type variable whose upper bound is
  3673      *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is the null
  3674      *   type.
  3676      * + If Ti is a wildcard type argument of the form ? extends Bi,
  3677      *   then Si is a fresh type variable whose upper bound is
  3678      *   glb(Bi, Ui[A1 := S1, ..., An := Sn]) and whose lower bound is
  3679      *   the null type, where glb(V1,... ,Vm) is V1 & ... & Vm. It is
  3680      *   a compile-time error if for any two classes (not interfaces)
  3681      *   Vi and Vj,Vi is not a subclass of Vj or vice versa.
  3683      * + If Ti is a wildcard type argument of the form ? super Bi,
  3684      *   then Si is a fresh type variable whose upper bound is
  3685      *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is Bi.
  3687      * + Otherwise, Si = Ti.
  3689      * Capture conversion on any type other than a parameterized type
  3690      * (4.5) acts as an identity conversion (5.1.1). Capture
  3691      * conversions never require a special action at run time and
  3692      * therefore never throw an exception at run time.
  3694      * Capture conversion is not applied recursively.
  3695      */
  3696     /**
  3697      * Capture conversion as specified by the JLS.
  3698      */
  3700     public List<Type> capture(List<Type> ts) {
  3701         List<Type> buf = List.nil();
  3702         for (Type t : ts) {
  3703             buf = buf.prepend(capture(t));
  3705         return buf.reverse();
  3707     public Type capture(Type t) {
  3708         if (t.tag != CLASS)
  3709             return t;
  3710         if (t.getEnclosingType() != Type.noType) {
  3711             Type capturedEncl = capture(t.getEnclosingType());
  3712             if (capturedEncl != t.getEnclosingType()) {
  3713                 Type type1 = memberType(capturedEncl, t.tsym);
  3714                 t = subst(type1, t.tsym.type.getTypeArguments(), t.getTypeArguments());
  3717         t = t.unannotatedType();
  3718         ClassType cls = (ClassType)t;
  3719         if (cls.isRaw() || !cls.isParameterized())
  3720             return cls;
  3722         ClassType G = (ClassType)cls.asElement().asType();
  3723         List<Type> A = G.getTypeArguments();
  3724         List<Type> T = cls.getTypeArguments();
  3725         List<Type> S = freshTypeVariables(T);
  3727         List<Type> currentA = A;
  3728         List<Type> currentT = T;
  3729         List<Type> currentS = S;
  3730         boolean captured = false;
  3731         while (!currentA.isEmpty() &&
  3732                !currentT.isEmpty() &&
  3733                !currentS.isEmpty()) {
  3734             if (currentS.head != currentT.head) {
  3735                 captured = true;
  3736                 WildcardType Ti = (WildcardType)currentT.head;
  3737                 Type Ui = currentA.head.getUpperBound();
  3738                 CapturedType Si = (CapturedType)currentS.head;
  3739                 if (Ui == null)
  3740                     Ui = syms.objectType;
  3741                 switch (Ti.kind) {
  3742                 case UNBOUND:
  3743                     Si.bound = subst(Ui, A, S);
  3744                     Si.lower = syms.botType;
  3745                     break;
  3746                 case EXTENDS:
  3747                     Si.bound = glb(Ti.getExtendsBound(), subst(Ui, A, S));
  3748                     Si.lower = syms.botType;
  3749                     break;
  3750                 case SUPER:
  3751                     Si.bound = subst(Ui, A, S);
  3752                     Si.lower = Ti.getSuperBound();
  3753                     break;
  3755                 if (Si.bound == Si.lower)
  3756                     currentS.head = Si.bound;
  3758             currentA = currentA.tail;
  3759             currentT = currentT.tail;
  3760             currentS = currentS.tail;
  3762         if (!currentA.isEmpty() || !currentT.isEmpty() || !currentS.isEmpty())
  3763             return erasure(t); // some "rare" type involved
  3765         if (captured)
  3766             return new ClassType(cls.getEnclosingType(), S, cls.tsym);
  3767         else
  3768             return t;
  3770     // where
  3771         public List<Type> freshTypeVariables(List<Type> types) {
  3772             ListBuffer<Type> result = lb();
  3773             for (Type t : types) {
  3774                 if (t.tag == WILDCARD) {
  3775                     Type bound = ((WildcardType)t).getExtendsBound();
  3776                     if (bound == null)
  3777                         bound = syms.objectType;
  3778                     result.append(new CapturedType(capturedName,
  3779                                                    syms.noSymbol,
  3780                                                    bound,
  3781                                                    syms.botType,
  3782                                                    (WildcardType)t));
  3783                 } else {
  3784                     result.append(t);
  3787             return result.toList();
  3789     // </editor-fold>
  3791     // <editor-fold defaultstate="collapsed" desc="Internal utility methods">
  3792     private List<Type> upperBounds(List<Type> ss) {
  3793         if (ss.isEmpty()) return ss;
  3794         Type head = upperBound(ss.head);
  3795         List<Type> tail = upperBounds(ss.tail);
  3796         if (head != ss.head || tail != ss.tail)
  3797             return tail.prepend(head);
  3798         else
  3799             return ss;
  3802     private boolean sideCast(Type from, Type to, Warner warn) {
  3803         // We are casting from type $from$ to type $to$, which are
  3804         // non-final unrelated types.  This method
  3805         // tries to reject a cast by transferring type parameters
  3806         // from $to$ to $from$ by common superinterfaces.
  3807         boolean reverse = false;
  3808         Type target = to;
  3809         if ((to.tsym.flags() & INTERFACE) == 0) {
  3810             Assert.check((from.tsym.flags() & INTERFACE) != 0);
  3811             reverse = true;
  3812             to = from;
  3813             from = target;
  3815         List<Type> commonSupers = superClosure(to, erasure(from));
  3816         boolean giveWarning = commonSupers.isEmpty();
  3817         // The arguments to the supers could be unified here to
  3818         // get a more accurate analysis
  3819         while (commonSupers.nonEmpty()) {
  3820             Type t1 = asSuper(from, commonSupers.head.tsym);
  3821             Type t2 = commonSupers.head; // same as asSuper(to, commonSupers.head.tsym);
  3822             if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
  3823                 return false;
  3824             giveWarning = giveWarning || (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2));
  3825             commonSupers = commonSupers.tail;
  3827         if (giveWarning && !isReifiable(reverse ? from : to))
  3828             warn.warn(LintCategory.UNCHECKED);
  3829         if (!allowCovariantReturns)
  3830             // reject if there is a common method signature with
  3831             // incompatible return types.
  3832             chk.checkCompatibleAbstracts(warn.pos(), from, to);
  3833         return true;
  3836     private boolean sideCastFinal(Type from, Type to, Warner warn) {
  3837         // We are casting from type $from$ to type $to$, which are
  3838         // unrelated types one of which is final and the other of
  3839         // which is an interface.  This method
  3840         // tries to reject a cast by transferring type parameters
  3841         // from the final class to the interface.
  3842         boolean reverse = false;
  3843         Type target = to;
  3844         if ((to.tsym.flags() & INTERFACE) == 0) {
  3845             Assert.check((from.tsym.flags() & INTERFACE) != 0);
  3846             reverse = true;
  3847             to = from;
  3848             from = target;
  3850         Assert.check((from.tsym.flags() & FINAL) != 0);
  3851         Type t1 = asSuper(from, to.tsym);
  3852         if (t1 == null) return false;
  3853         Type t2 = to;
  3854         if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
  3855             return false;
  3856         if (!allowCovariantReturns)
  3857             // reject if there is a common method signature with
  3858             // incompatible return types.
  3859             chk.checkCompatibleAbstracts(warn.pos(), from, to);
  3860         if (!isReifiable(target) &&
  3861             (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2)))
  3862             warn.warn(LintCategory.UNCHECKED);
  3863         return true;
  3866     private boolean giveWarning(Type from, Type to) {
  3867         Type subFrom = asSub(from, to.tsym);
  3868         return to.isParameterized() &&
  3869                 (!(isUnbounded(to) ||
  3870                 isSubtype(from, to) ||
  3871                 ((subFrom != null) && containsType(to.allparams(), subFrom.allparams()))));
  3874     private List<Type> superClosure(Type t, Type s) {
  3875         List<Type> cl = List.nil();
  3876         for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
  3877             if (isSubtype(s, erasure(l.head))) {
  3878                 cl = insert(cl, l.head);
  3879             } else {
  3880                 cl = union(cl, superClosure(l.head, s));
  3883         return cl;
  3886     private boolean containsTypeEquivalent(Type t, Type s) {
  3887         return
  3888             isSameType(t, s) || // shortcut
  3889             containsType(t, s) && containsType(s, t);
  3892     // <editor-fold defaultstate="collapsed" desc="adapt">
  3893     /**
  3894      * Adapt a type by computing a substitution which maps a source
  3895      * type to a target type.
  3897      * @param source    the source type
  3898      * @param target    the target type
  3899      * @param from      the type variables of the computed substitution
  3900      * @param to        the types of the computed substitution.
  3901      */
  3902     public void adapt(Type source,
  3903                        Type target,
  3904                        ListBuffer<Type> from,
  3905                        ListBuffer<Type> to) throws AdaptFailure {
  3906         new Adapter(from, to).adapt(source, target);
  3909     class Adapter extends SimpleVisitor<Void, Type> {
  3911         ListBuffer<Type> from;
  3912         ListBuffer<Type> to;
  3913         Map<Symbol,Type> mapping;
  3915         Adapter(ListBuffer<Type> from, ListBuffer<Type> to) {
  3916             this.from = from;
  3917             this.to = to;
  3918             mapping = new HashMap<Symbol,Type>();
  3921         public void adapt(Type source, Type target) throws AdaptFailure {
  3922             visit(source, target);
  3923             List<Type> fromList = from.toList();
  3924             List<Type> toList = to.toList();
  3925             while (!fromList.isEmpty()) {
  3926                 Type val = mapping.get(fromList.head.tsym);
  3927                 if (toList.head != val)
  3928                     toList.head = val;
  3929                 fromList = fromList.tail;
  3930                 toList = toList.tail;
  3934         @Override
  3935         public Void visitClassType(ClassType source, Type target) throws AdaptFailure {
  3936             if (target.tag == CLASS)
  3937                 adaptRecursive(source.allparams(), target.allparams());
  3938             return null;
  3941         @Override
  3942         public Void visitArrayType(ArrayType source, Type target) throws AdaptFailure {
  3943             if (target.tag == ARRAY)
  3944                 adaptRecursive(elemtype(source), elemtype(target));
  3945             return null;
  3948         @Override
  3949         public Void visitWildcardType(WildcardType source, Type target) throws AdaptFailure {
  3950             if (source.isExtendsBound())
  3951                 adaptRecursive(upperBound(source), upperBound(target));
  3952             else if (source.isSuperBound())
  3953                 adaptRecursive(lowerBound(source), lowerBound(target));
  3954             return null;
  3957         @Override
  3958         public Void visitTypeVar(TypeVar source, Type target) throws AdaptFailure {
  3959             // Check to see if there is
  3960             // already a mapping for $source$, in which case
  3961             // the old mapping will be merged with the new
  3962             Type val = mapping.get(source.tsym);
  3963             if (val != null) {
  3964                 if (val.isSuperBound() && target.isSuperBound()) {
  3965                     val = isSubtype(lowerBound(val), lowerBound(target))
  3966                         ? target : val;
  3967                 } else if (val.isExtendsBound() && target.isExtendsBound()) {
  3968                     val = isSubtype(upperBound(val), upperBound(target))
  3969                         ? val : target;
  3970                 } else if (!isSameType(val, target)) {
  3971                     throw new AdaptFailure();
  3973             } else {
  3974                 val = target;
  3975                 from.append(source);
  3976                 to.append(target);
  3978             mapping.put(source.tsym, val);
  3979             return null;
  3982         @Override
  3983         public Void visitType(Type source, Type target) {
  3984             return null;
  3987         private Set<TypePair> cache = new HashSet<TypePair>();
  3989         private void adaptRecursive(Type source, Type target) {
  3990             TypePair pair = new TypePair(source, target);
  3991             if (cache.add(pair)) {
  3992                 try {
  3993                     visit(source, target);
  3994                 } finally {
  3995                     cache.remove(pair);
  4000         private void adaptRecursive(List<Type> source, List<Type> target) {
  4001             if (source.length() == target.length()) {
  4002                 while (source.nonEmpty()) {
  4003                     adaptRecursive(source.head, target.head);
  4004                     source = source.tail;
  4005                     target = target.tail;
  4011     public static class AdaptFailure extends RuntimeException {
  4012         static final long serialVersionUID = -7490231548272701566L;
  4015     private void adaptSelf(Type t,
  4016                            ListBuffer<Type> from,
  4017                            ListBuffer<Type> to) {
  4018         try {
  4019             //if (t.tsym.type != t)
  4020                 adapt(t.tsym.type, t, from, to);
  4021         } catch (AdaptFailure ex) {
  4022             // Adapt should never fail calculating a mapping from
  4023             // t.tsym.type to t as there can be no merge problem.
  4024             throw new AssertionError(ex);
  4027     // </editor-fold>
  4029     /**
  4030      * Rewrite all type variables (universal quantifiers) in the given
  4031      * type to wildcards (existential quantifiers).  This is used to
  4032      * determine if a cast is allowed.  For example, if high is true
  4033      * and {@code T <: Number}, then {@code List<T>} is rewritten to
  4034      * {@code List<?  extends Number>}.  Since {@code List<Integer> <:
  4035      * List<? extends Number>} a {@code List<T>} can be cast to {@code
  4036      * List<Integer>} with a warning.
  4037      * @param t a type
  4038      * @param high if true return an upper bound; otherwise a lower
  4039      * bound
  4040      * @param rewriteTypeVars only rewrite captured wildcards if false;
  4041      * otherwise rewrite all type variables
  4042      * @return the type rewritten with wildcards (existential
  4043      * quantifiers) only
  4044      */
  4045     private Type rewriteQuantifiers(Type t, boolean high, boolean rewriteTypeVars) {
  4046         return new Rewriter(high, rewriteTypeVars).visit(t);
  4049     class Rewriter extends UnaryVisitor<Type> {
  4051         boolean high;
  4052         boolean rewriteTypeVars;
  4054         Rewriter(boolean high, boolean rewriteTypeVars) {
  4055             this.high = high;
  4056             this.rewriteTypeVars = rewriteTypeVars;
  4059         @Override
  4060         public Type visitClassType(ClassType t, Void s) {
  4061             ListBuffer<Type> rewritten = new ListBuffer<Type>();
  4062             boolean changed = false;
  4063             for (Type arg : t.allparams()) {
  4064                 Type bound = visit(arg);
  4065                 if (arg != bound) {
  4066                     changed = true;
  4068                 rewritten.append(bound);
  4070             if (changed)
  4071                 return subst(t.tsym.type,
  4072                         t.tsym.type.allparams(),
  4073                         rewritten.toList());
  4074             else
  4075                 return t;
  4078         public Type visitType(Type t, Void s) {
  4079             return high ? upperBound(t) : lowerBound(t);
  4082         @Override
  4083         public Type visitCapturedType(CapturedType t, Void s) {
  4084             Type w_bound = t.wildcard.type;
  4085             Type bound = w_bound.contains(t) ?
  4086                         erasure(w_bound) :
  4087                         visit(w_bound);
  4088             return rewriteAsWildcardType(visit(bound), t.wildcard.bound, t.wildcard.kind);
  4091         @Override
  4092         public Type visitTypeVar(TypeVar t, Void s) {
  4093             if (rewriteTypeVars) {
  4094                 Type bound = t.bound.contains(t) ?
  4095                         erasure(t.bound) :
  4096                         visit(t.bound);
  4097                 return rewriteAsWildcardType(bound, t, EXTENDS);
  4098             } else {
  4099                 return t;
  4103         @Override
  4104         public Type visitWildcardType(WildcardType t, Void s) {
  4105             Type bound2 = visit(t.type);
  4106             return t.type == bound2 ? t : rewriteAsWildcardType(bound2, t.bound, t.kind);
  4109         private Type rewriteAsWildcardType(Type bound, TypeVar formal, BoundKind bk) {
  4110             switch (bk) {
  4111                case EXTENDS: return high ?
  4112                        makeExtendsWildcard(B(bound), formal) :
  4113                        makeExtendsWildcard(syms.objectType, formal);
  4114                case SUPER: return high ?
  4115                        makeSuperWildcard(syms.botType, formal) :
  4116                        makeSuperWildcard(B(bound), formal);
  4117                case UNBOUND: return makeExtendsWildcard(syms.objectType, formal);
  4118                default:
  4119                    Assert.error("Invalid bound kind " + bk);
  4120                    return null;
  4124         Type B(Type t) {
  4125             while (t.tag == WILDCARD) {
  4126                 WildcardType w = (WildcardType)t;
  4127                 t = high ?
  4128                     w.getExtendsBound() :
  4129                     w.getSuperBound();
  4130                 if (t == null) {
  4131                     t = high ? syms.objectType : syms.botType;
  4134             return t;
  4139     /**
  4140      * Create a wildcard with the given upper (extends) bound; create
  4141      * an unbounded wildcard if bound is Object.
  4143      * @param bound the upper bound
  4144      * @param formal the formal type parameter that will be
  4145      * substituted by the wildcard
  4146      */
  4147     private WildcardType makeExtendsWildcard(Type bound, TypeVar formal) {
  4148         if (bound == syms.objectType) {
  4149             return new WildcardType(syms.objectType,
  4150                                     BoundKind.UNBOUND,
  4151                                     syms.boundClass,
  4152                                     formal);
  4153         } else {
  4154             return new WildcardType(bound,
  4155                                     BoundKind.EXTENDS,
  4156                                     syms.boundClass,
  4157                                     formal);
  4161     /**
  4162      * Create a wildcard with the given lower (super) bound; create an
  4163      * unbounded wildcard if bound is bottom (type of {@code null}).
  4165      * @param bound the lower bound
  4166      * @param formal the formal type parameter that will be
  4167      * substituted by the wildcard
  4168      */
  4169     private WildcardType makeSuperWildcard(Type bound, TypeVar formal) {
  4170         if (bound.tag == BOT) {
  4171             return new WildcardType(syms.objectType,
  4172                                     BoundKind.UNBOUND,
  4173                                     syms.boundClass,
  4174                                     formal);
  4175         } else {
  4176             return new WildcardType(bound,
  4177                                     BoundKind.SUPER,
  4178                                     syms.boundClass,
  4179                                     formal);
  4183     /**
  4184      * A wrapper for a type that allows use in sets.
  4185      */
  4186     public static class UniqueType {
  4187         public final Type type;
  4188         final Types types;
  4190         public UniqueType(Type type, Types types) {
  4191             this.type = type;
  4192             this.types = types;
  4195         public int hashCode() {
  4196             return types.hashCode(type);
  4199         public boolean equals(Object obj) {
  4200             return (obj instanceof UniqueType) &&
  4201                 types.isSameType(type, ((UniqueType)obj).type);
  4204         public String toString() {
  4205             return type.toString();
  4209     // </editor-fold>
  4211     // <editor-fold defaultstate="collapsed" desc="Visitors">
  4212     /**
  4213      * A default visitor for types.  All visitor methods except
  4214      * visitType are implemented by delegating to visitType.  Concrete
  4215      * subclasses must provide an implementation of visitType and can
  4216      * override other methods as needed.
  4218      * @param <R> the return type of the operation implemented by this
  4219      * visitor; use Void if no return type is needed.
  4220      * @param <S> the type of the second argument (the first being the
  4221      * type itself) of the operation implemented by this visitor; use
  4222      * Void if a second argument is not needed.
  4223      */
  4224     public static abstract class DefaultTypeVisitor<R,S> implements Type.Visitor<R,S> {
  4225         final public R visit(Type t, S s)               { return t.accept(this, s); }
  4226         public R visitClassType(ClassType t, S s)       { return visitType(t, s); }
  4227         public R visitWildcardType(WildcardType t, S s) { return visitType(t, s); }
  4228         public R visitArrayType(ArrayType t, S s)       { return visitType(t, s); }
  4229         public R visitMethodType(MethodType t, S s)     { return visitType(t, s); }
  4230         public R visitPackageType(PackageType t, S s)   { return visitType(t, s); }
  4231         public R visitTypeVar(TypeVar t, S s)           { return visitType(t, s); }
  4232         public R visitCapturedType(CapturedType t, S s) { return visitType(t, s); }
  4233         public R visitForAll(ForAll t, S s)             { return visitType(t, s); }
  4234         public R visitUndetVar(UndetVar t, S s)         { return visitType(t, s); }
  4235         public R visitErrorType(ErrorType t, S s)       { return visitType(t, s); }
  4236         // Pretend annotations don't exist
  4237         public R visitAnnotatedType(AnnotatedType t, S s) { return visit(t.underlyingType, s); }
  4240     /**
  4241      * A default visitor for symbols.  All visitor methods except
  4242      * visitSymbol are implemented by delegating to visitSymbol.  Concrete
  4243      * subclasses must provide an implementation of visitSymbol and can
  4244      * override other methods as needed.
  4246      * @param <R> the return type of the operation implemented by this
  4247      * visitor; use Void if no return type is needed.
  4248      * @param <S> the type of the second argument (the first being the
  4249      * symbol itself) of the operation implemented by this visitor; use
  4250      * Void if a second argument is not needed.
  4251      */
  4252     public static abstract class DefaultSymbolVisitor<R,S> implements Symbol.Visitor<R,S> {
  4253         final public R visit(Symbol s, S arg)                   { return s.accept(this, arg); }
  4254         public R visitClassSymbol(ClassSymbol s, S arg)         { return visitSymbol(s, arg); }
  4255         public R visitMethodSymbol(MethodSymbol s, S arg)       { return visitSymbol(s, arg); }
  4256         public R visitOperatorSymbol(OperatorSymbol s, S arg)   { return visitSymbol(s, arg); }
  4257         public R visitPackageSymbol(PackageSymbol s, S arg)     { return visitSymbol(s, arg); }
  4258         public R visitTypeSymbol(TypeSymbol s, S arg)           { return visitSymbol(s, arg); }
  4259         public R visitVarSymbol(VarSymbol s, S arg)             { return visitSymbol(s, arg); }
  4262     /**
  4263      * A <em>simple</em> visitor for types.  This visitor is simple as
  4264      * captured wildcards, for-all types (generic methods), and
  4265      * undetermined type variables (part of inference) are hidden.
  4266      * Captured wildcards are hidden by treating them as type
  4267      * variables and the rest are hidden by visiting their qtypes.
  4269      * @param <R> the return type of the operation implemented by this
  4270      * visitor; use Void if no return type is needed.
  4271      * @param <S> the type of the second argument (the first being the
  4272      * type itself) of the operation implemented by this visitor; use
  4273      * Void if a second argument is not needed.
  4274      */
  4275     public static abstract class SimpleVisitor<R,S> extends DefaultTypeVisitor<R,S> {
  4276         @Override
  4277         public R visitCapturedType(CapturedType t, S s) {
  4278             return visitTypeVar(t, s);
  4280         @Override
  4281         public R visitForAll(ForAll t, S s) {
  4282             return visit(t.qtype, s);
  4284         @Override
  4285         public R visitUndetVar(UndetVar t, S s) {
  4286             return visit(t.qtype, s);
  4290     /**
  4291      * A plain relation on types.  That is a 2-ary function on the
  4292      * form Type&nbsp;&times;&nbsp;Type&nbsp;&rarr;&nbsp;Boolean.
  4293      * <!-- In plain text: Type x Type -> Boolean -->
  4294      */
  4295     public static abstract class TypeRelation extends SimpleVisitor<Boolean,Type> {}
  4297     /**
  4298      * A convenience visitor for implementing operations that only
  4299      * require one argument (the type itself), that is, unary
  4300      * operations.
  4302      * @param <R> the return type of the operation implemented by this
  4303      * visitor; use Void if no return type is needed.
  4304      */
  4305     public static abstract class UnaryVisitor<R> extends SimpleVisitor<R,Void> {
  4306         final public R visit(Type t) { return t.accept(this, null); }
  4309     /**
  4310      * A visitor for implementing a mapping from types to types.  The
  4311      * default behavior of this class is to implement the identity
  4312      * mapping (mapping a type to itself).  This can be overridden in
  4313      * subclasses.
  4315      * @param <S> the type of the second argument (the first being the
  4316      * type itself) of this mapping; use Void if a second argument is
  4317      * not needed.
  4318      */
  4319     public static class MapVisitor<S> extends DefaultTypeVisitor<Type,S> {
  4320         final public Type visit(Type t) { return t.accept(this, null); }
  4321         public Type visitType(Type t, S s) { return t; }
  4323     // </editor-fold>
  4326     // <editor-fold defaultstate="collapsed" desc="Annotation support">
  4328     public RetentionPolicy getRetention(Attribute.Compound a) {
  4329         return getRetention(a.type.tsym);
  4332     public RetentionPolicy getRetention(Symbol sym) {
  4333         RetentionPolicy vis = RetentionPolicy.CLASS; // the default
  4334         Attribute.Compound c = sym.attribute(syms.retentionType.tsym);
  4335         if (c != null) {
  4336             Attribute value = c.member(names.value);
  4337             if (value != null && value instanceof Attribute.Enum) {
  4338                 Name levelName = ((Attribute.Enum)value).value.name;
  4339                 if (levelName == names.SOURCE) vis = RetentionPolicy.SOURCE;
  4340                 else if (levelName == names.CLASS) vis = RetentionPolicy.CLASS;
  4341                 else if (levelName == names.RUNTIME) vis = RetentionPolicy.RUNTIME;
  4342                 else ;// /* fail soft */ throw new AssertionError(levelName);
  4345         return vis;
  4347     // </editor-fold>

mercurial