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

Fri, 15 Feb 2013 18:40:38 -0800

author
rfield
date
Fri, 15 Feb 2013 18:40:38 -0800
changeset 1587
f1f605f85850
parent 1582
3cd997b9fd84
child 1598
7ac9242d2ca6
permissions
-rw-r--r--

8004969: Generate $deserializeLambda$ method
8006763: super in method reference used in anonymous class - ClassFormatError is produced
8005632: Inner classes within lambdas cause build failures
8005653: Lambdas containing inner classes referencing external type variables do not correctly parameterize the inner classes
Reviewed-by: mcimadamore

     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.jvm.ClassFile.externalize;
    52 import static com.sun.tools.javac.util.ListBuffer.lb;
    54 /**
    55  * Utility class containing various operations on types.
    56  *
    57  * <p>Unless other names are more illustrative, the following naming
    58  * conventions should be observed in this file:
    59  *
    60  * <dl>
    61  * <dt>t</dt>
    62  * <dd>If the first argument to an operation is a type, it should be named t.</dd>
    63  * <dt>s</dt>
    64  * <dd>Similarly, if the second argument to an operation is a type, it should be named s.</dd>
    65  * <dt>ts</dt>
    66  * <dd>If an operations takes a list of types, the first should be named ts.</dd>
    67  * <dt>ss</dt>
    68  * <dd>A second list of types should be named ss.</dd>
    69  * </dl>
    70  *
    71  * <p><b>This is NOT part of any supported API.
    72  * If you write code that depends on this, you do so at your own risk.
    73  * This code and its internal interfaces are subject to change or
    74  * deletion without notice.</b>
    75  */
    76 public class Types {
    77     protected static final Context.Key<Types> typesKey =
    78         new Context.Key<Types>();
    80     final Symtab syms;
    81     final JavacMessages messages;
    82     final Names names;
    83     final boolean allowBoxing;
    84     final boolean allowCovariantReturns;
    85     final boolean allowObjectToPrimitiveCast;
    86     final boolean allowDefaultMethods;
    87     final ClassReader reader;
    88     final Check chk;
    89     JCDiagnostic.Factory diags;
    90     List<Warner> warnStack = List.nil();
    91     final Name capturedName;
    92     private final FunctionDescriptorLookupError functionDescriptorLookupError;
    94     public final Warner noWarnings;
    96     // <editor-fold defaultstate="collapsed" desc="Instantiating">
    97     public static Types instance(Context context) {
    98         Types instance = context.get(typesKey);
    99         if (instance == null)
   100             instance = new Types(context);
   101         return instance;
   102     }
   104     protected Types(Context context) {
   105         context.put(typesKey, this);
   106         syms = Symtab.instance(context);
   107         names = Names.instance(context);
   108         Source source = Source.instance(context);
   109         allowBoxing = source.allowBoxing();
   110         allowCovariantReturns = source.allowCovariantReturns();
   111         allowObjectToPrimitiveCast = source.allowObjectToPrimitiveCast();
   112         allowDefaultMethods = source.allowDefaultMethods();
   113         reader = ClassReader.instance(context);
   114         chk = Check.instance(context);
   115         capturedName = names.fromString("<captured wildcard>");
   116         messages = JavacMessages.instance(context);
   117         diags = JCDiagnostic.Factory.instance(context);
   118         functionDescriptorLookupError = new FunctionDescriptorLookupError();
   119         noWarnings = new Warner(null);
   120     }
   121     // </editor-fold>
   123     // <editor-fold defaultstate="collapsed" desc="upperBound">
   124     /**
   125      * The "rvalue conversion".<br>
   126      * The upper bound of most types is the type
   127      * itself.  Wildcards, on the other hand have upper
   128      * and lower bounds.
   129      * @param t a type
   130      * @return the upper bound of the given type
   131      */
   132     public Type upperBound(Type t) {
   133         return upperBound.visit(t);
   134     }
   135     // where
   136         private final MapVisitor<Void> upperBound = new MapVisitor<Void>() {
   138             @Override
   139             public Type visitWildcardType(WildcardType t, Void ignored) {
   140                 if (t.isSuperBound())
   141                     return t.bound == null ? syms.objectType : t.bound.bound;
   142                 else
   143                     return visit(t.type);
   144             }
   146             @Override
   147             public Type visitCapturedType(CapturedType t, Void ignored) {
   148                 return visit(t.bound);
   149             }
   150         };
   151     // </editor-fold>
   153     // <editor-fold defaultstate="collapsed" desc="lowerBound">
   154     /**
   155      * The "lvalue conversion".<br>
   156      * The lower bound of most types is the type
   157      * itself.  Wildcards, on the other hand have upper
   158      * and lower bounds.
   159      * @param t a type
   160      * @return the lower bound of the given type
   161      */
   162     public Type lowerBound(Type t) {
   163         return lowerBound.visit(t);
   164     }
   165     // where
   166         private final MapVisitor<Void> lowerBound = new MapVisitor<Void>() {
   168             @Override
   169             public Type visitWildcardType(WildcardType t, Void ignored) {
   170                 return t.isExtendsBound() ? syms.botType : visit(t.type);
   171             }
   173             @Override
   174             public Type visitCapturedType(CapturedType t, Void ignored) {
   175                 return visit(t.getLowerBound());
   176             }
   177         };
   178     // </editor-fold>
   180     // <editor-fold defaultstate="collapsed" desc="isUnbounded">
   181     /**
   182      * Checks that all the arguments to a class are unbounded
   183      * wildcards or something else that doesn't make any restrictions
   184      * on the arguments. If a class isUnbounded, a raw super- or
   185      * subclass can be cast to it without a warning.
   186      * @param t a type
   187      * @return true iff the given type is unbounded or raw
   188      */
   189     public boolean isUnbounded(Type t) {
   190         return isUnbounded.visit(t);
   191     }
   192     // where
   193         private final UnaryVisitor<Boolean> isUnbounded = new UnaryVisitor<Boolean>() {
   195             public Boolean visitType(Type t, Void ignored) {
   196                 return true;
   197             }
   199             @Override
   200             public Boolean visitClassType(ClassType t, Void ignored) {
   201                 List<Type> parms = t.tsym.type.allparams();
   202                 List<Type> args = t.allparams();
   203                 while (parms.nonEmpty()) {
   204                     WildcardType unb = new WildcardType(syms.objectType,
   205                                                         BoundKind.UNBOUND,
   206                                                         syms.boundClass,
   207                                                         (TypeVar)parms.head);
   208                     if (!containsType(args.head, unb))
   209                         return false;
   210                     parms = parms.tail;
   211                     args = args.tail;
   212                 }
   213                 return true;
   214             }
   215         };
   216     // </editor-fold>
   218     // <editor-fold defaultstate="collapsed" desc="asSub">
   219     /**
   220      * Return the least specific subtype of t that starts with symbol
   221      * sym.  If none exists, return null.  The least specific subtype
   222      * is determined as follows:
   223      *
   224      * <p>If there is exactly one parameterized instance of sym that is a
   225      * subtype of t, that parameterized instance is returned.<br>
   226      * Otherwise, if the plain type or raw type `sym' is a subtype of
   227      * type t, the type `sym' itself is returned.  Otherwise, null is
   228      * returned.
   229      */
   230     public Type asSub(Type t, Symbol sym) {
   231         return asSub.visit(t, sym);
   232     }
   233     // where
   234         private final SimpleVisitor<Type,Symbol> asSub = new SimpleVisitor<Type,Symbol>() {
   236             public Type visitType(Type t, Symbol sym) {
   237                 return null;
   238             }
   240             @Override
   241             public Type visitClassType(ClassType t, Symbol sym) {
   242                 if (t.tsym == sym)
   243                     return t;
   244                 Type base = asSuper(sym.type, t.tsym);
   245                 if (base == null)
   246                     return null;
   247                 ListBuffer<Type> from = new ListBuffer<Type>();
   248                 ListBuffer<Type> to = new ListBuffer<Type>();
   249                 try {
   250                     adapt(base, t, from, to);
   251                 } catch (AdaptFailure ex) {
   252                     return null;
   253                 }
   254                 Type res = subst(sym.type, from.toList(), to.toList());
   255                 if (!isSubtype(res, t))
   256                     return null;
   257                 ListBuffer<Type> openVars = new ListBuffer<Type>();
   258                 for (List<Type> l = sym.type.allparams();
   259                      l.nonEmpty(); l = l.tail)
   260                     if (res.contains(l.head) && !t.contains(l.head))
   261                         openVars.append(l.head);
   262                 if (openVars.nonEmpty()) {
   263                     if (t.isRaw()) {
   264                         // The subtype of a raw type is raw
   265                         res = erasure(res);
   266                     } else {
   267                         // Unbound type arguments default to ?
   268                         List<Type> opens = openVars.toList();
   269                         ListBuffer<Type> qs = new ListBuffer<Type>();
   270                         for (List<Type> iter = opens; iter.nonEmpty(); iter = iter.tail) {
   271                             qs.append(new WildcardType(syms.objectType, BoundKind.UNBOUND, syms.boundClass, (TypeVar) iter.head));
   272                         }
   273                         res = subst(res, opens, qs.toList());
   274                     }
   275                 }
   276                 return res;
   277             }
   279             @Override
   280             public Type visitErrorType(ErrorType t, Symbol sym) {
   281                 return t;
   282             }
   283         };
   284     // </editor-fold>
   286     // <editor-fold defaultstate="collapsed" desc="isConvertible">
   287     /**
   288      * Is t a subtype of or convertible via boxing/unboxing
   289      * conversion to s?
   290      */
   291     public boolean isConvertible(Type t, Type s, Warner warn) {
   292         if (t.tag == ERROR)
   293             return true;
   294         boolean tPrimitive = t.isPrimitive();
   295         boolean sPrimitive = s.isPrimitive();
   296         if (tPrimitive == sPrimitive) {
   297             return isSubtypeUnchecked(t, s, warn);
   298         }
   299         if (!allowBoxing) return false;
   300         return tPrimitive
   301             ? isSubtype(boxedClass(t).type, s)
   302             : isSubtype(unboxedType(t), s);
   303     }
   305     /**
   306      * Is t a subtype of or convertiable via boxing/unboxing
   307      * convertions to s?
   308      */
   309     public boolean isConvertible(Type t, Type s) {
   310         return isConvertible(t, s, noWarnings);
   311     }
   312     // </editor-fold>
   314     // <editor-fold defaultstate="collapsed" desc="findSam">
   316     /**
   317      * Exception used to report a function descriptor lookup failure. The exception
   318      * wraps a diagnostic that can be used to generate more details error
   319      * messages.
   320      */
   321     public static class FunctionDescriptorLookupError extends RuntimeException {
   322         private static final long serialVersionUID = 0;
   324         JCDiagnostic diagnostic;
   326         FunctionDescriptorLookupError() {
   327             this.diagnostic = null;
   328         }
   330         FunctionDescriptorLookupError setMessage(JCDiagnostic diag) {
   331             this.diagnostic = diag;
   332             return this;
   333         }
   335         public JCDiagnostic getDiagnostic() {
   336             return diagnostic;
   337         }
   338     }
   340     /**
   341      * A cache that keeps track of function descriptors associated with given
   342      * functional interfaces.
   343      */
   344     class DescriptorCache {
   346         private WeakHashMap<TypeSymbol, Entry> _map = new WeakHashMap<TypeSymbol, Entry>();
   348         class FunctionDescriptor {
   349             Symbol descSym;
   351             FunctionDescriptor(Symbol descSym) {
   352                 this.descSym = descSym;
   353             }
   355             public Symbol getSymbol() {
   356                 return descSym;
   357             }
   359             public Type getType(Type site) {
   360                 site = removeWildcards(site);
   361                 if (!chk.checkValidGenericType(site)) {
   362                     //if the inferred functional interface type is not well-formed,
   363                     //or if it's not a subtype of the original target, issue an error
   364                     throw failure(diags.fragment("no.suitable.functional.intf.inst", site));
   365                 }
   366                 return memberType(site, descSym);
   367             }
   368         }
   370         class Entry {
   371             final FunctionDescriptor cachedDescRes;
   372             final int prevMark;
   374             public Entry(FunctionDescriptor cachedDescRes,
   375                     int prevMark) {
   376                 this.cachedDescRes = cachedDescRes;
   377                 this.prevMark = prevMark;
   378             }
   380             boolean matches(int mark) {
   381                 return  this.prevMark == mark;
   382             }
   383         }
   385         FunctionDescriptor get(TypeSymbol origin) throws FunctionDescriptorLookupError {
   386             Entry e = _map.get(origin);
   387             CompoundScope members = membersClosure(origin.type, false);
   388             if (e == null ||
   389                     !e.matches(members.getMark())) {
   390                 FunctionDescriptor descRes = findDescriptorInternal(origin, members);
   391                 _map.put(origin, new Entry(descRes, members.getMark()));
   392                 return descRes;
   393             }
   394             else {
   395                 return e.cachedDescRes;
   396             }
   397         }
   399         /**
   400          * Compute the function descriptor associated with a given functional interface
   401          */
   402         public FunctionDescriptor findDescriptorInternal(TypeSymbol origin, CompoundScope membersCache) throws FunctionDescriptorLookupError {
   403             if (!origin.isInterface() || (origin.flags() & ANNOTATION) != 0) {
   404                 //t must be an interface
   405                 throw failure("not.a.functional.intf", origin);
   406             }
   408             final ListBuffer<Symbol> abstracts = ListBuffer.lb();
   409             for (Symbol sym : membersCache.getElements(new DescriptorFilter(origin))) {
   410                 Type mtype = memberType(origin.type, sym);
   411                 if (abstracts.isEmpty() ||
   412                         (sym.name == abstracts.first().name &&
   413                         overrideEquivalent(mtype, memberType(origin.type, abstracts.first())))) {
   414                     abstracts.append(sym);
   415                 } else {
   416                     //the target method(s) should be the only abstract members of t
   417                     throw failure("not.a.functional.intf.1",  origin,
   418                             diags.fragment("incompatible.abstracts", Kinds.kindName(origin), origin));
   419                 }
   420             }
   421             if (abstracts.isEmpty()) {
   422                 //t must define a suitable non-generic method
   423                 throw failure("not.a.functional.intf.1", origin,
   424                             diags.fragment("no.abstracts", Kinds.kindName(origin), origin));
   425             } else if (abstracts.size() == 1) {
   426                 return new FunctionDescriptor(abstracts.first());
   427             } else { // size > 1
   428                 FunctionDescriptor descRes = mergeDescriptors(origin, abstracts.toList());
   429                 if (descRes == null) {
   430                     //we can get here if the functional interface is ill-formed
   431                     ListBuffer<JCDiagnostic> descriptors = ListBuffer.lb();
   432                     for (Symbol desc : abstracts) {
   433                         String key = desc.type.getThrownTypes().nonEmpty() ?
   434                                 "descriptor.throws" : "descriptor";
   435                         descriptors.append(diags.fragment(key, desc.name,
   436                                 desc.type.getParameterTypes(),
   437                                 desc.type.getReturnType(),
   438                                 desc.type.getThrownTypes()));
   439                     }
   440                     JCDiagnostic.MultilineDiagnostic incompatibleDescriptors =
   441                             new JCDiagnostic.MultilineDiagnostic(diags.fragment("incompatible.descs.in.functional.intf",
   442                             Kinds.kindName(origin), origin), descriptors.toList());
   443                     throw failure(incompatibleDescriptors);
   444                 }
   445                 return descRes;
   446             }
   447         }
   449         /**
   450          * Compute a synthetic type for the target descriptor given a list
   451          * of override-equivalent methods in the functional interface type.
   452          * The resulting method type is a method type that is override-equivalent
   453          * and return-type substitutable with each method in the original list.
   454          */
   455         private FunctionDescriptor mergeDescriptors(TypeSymbol origin, List<Symbol> methodSyms) {
   456             //pick argument types - simply take the signature that is a
   457             //subsignature of all other signatures in the list (as per JLS 8.4.2)
   458             List<Symbol> mostSpecific = List.nil();
   459             outer: for (Symbol msym1 : methodSyms) {
   460                 Type mt1 = memberType(origin.type, msym1);
   461                 for (Symbol msym2 : methodSyms) {
   462                     Type mt2 = memberType(origin.type, msym2);
   463                     if (!isSubSignature(mt1, mt2)) {
   464                         continue outer;
   465                     }
   466                 }
   467                 mostSpecific = mostSpecific.prepend(msym1);
   468             }
   469             if (mostSpecific.isEmpty()) {
   470                 return null;
   471             }
   474             //pick return types - this is done in two phases: (i) first, the most
   475             //specific return type is chosen using strict subtyping; if this fails,
   476             //a second attempt is made using return type substitutability (see JLS 8.4.5)
   477             boolean phase2 = false;
   478             Symbol bestSoFar = null;
   479             while (bestSoFar == null) {
   480                 outer: for (Symbol msym1 : mostSpecific) {
   481                     Type mt1 = memberType(origin.type, msym1);
   482                     for (Symbol msym2 : methodSyms) {
   483                         Type mt2 = memberType(origin.type, msym2);
   484                         if (phase2 ?
   485                                 !returnTypeSubstitutable(mt1, mt2) :
   486                                 !isSubtypeInternal(mt1.getReturnType(), mt2.getReturnType())) {
   487                             continue outer;
   488                         }
   489                     }
   490                     bestSoFar = msym1;
   491                 }
   492                 if (phase2) {
   493                     break;
   494                 } else {
   495                     phase2 = true;
   496                 }
   497             }
   498             if (bestSoFar == null) return null;
   500             //merge thrown types - form the intersection of all the thrown types in
   501             //all the signatures in the list
   502             List<Type> thrown = null;
   503             for (Symbol msym1 : methodSyms) {
   504                 Type mt1 = memberType(origin.type, msym1);
   505                 thrown = (thrown == null) ?
   506                     mt1.getThrownTypes() :
   507                     chk.intersect(mt1.getThrownTypes(), thrown);
   508             }
   510             final List<Type> thrown1 = thrown;
   511             return new FunctionDescriptor(bestSoFar) {
   512                 @Override
   513                 public Type getType(Type origin) {
   514                     Type mt = memberType(origin, getSymbol());
   515                     return new MethodType(mt.getParameterTypes(), mt.getReturnType(), thrown1, syms.methodClass);
   516                 }
   517             };
   518         }
   520         boolean isSubtypeInternal(Type s, Type t) {
   521             return (s.isPrimitive() && t.isPrimitive()) ?
   522                     isSameType(t, s) :
   523                     isSubtype(s, t);
   524         }
   526         FunctionDescriptorLookupError failure(String msg, Object... args) {
   527             return failure(diags.fragment(msg, args));
   528         }
   530         FunctionDescriptorLookupError failure(JCDiagnostic diag) {
   531             return functionDescriptorLookupError.setMessage(diag);
   532         }
   533     }
   535     private DescriptorCache descCache = new DescriptorCache();
   537     /**
   538      * Find the method descriptor associated to this class symbol - if the
   539      * symbol 'origin' is not a functional interface, an exception is thrown.
   540      */
   541     public Symbol findDescriptorSymbol(TypeSymbol origin) throws FunctionDescriptorLookupError {
   542         return descCache.get(origin).getSymbol();
   543     }
   545     /**
   546      * Find the type of the method descriptor associated to this class symbol -
   547      * if the symbol 'origin' is not a functional interface, an exception is thrown.
   548      */
   549     public Type findDescriptorType(Type origin) throws FunctionDescriptorLookupError {
   550         return descCache.get(origin.tsym).getType(origin);
   551     }
   553     /**
   554      * Is given type a functional interface?
   555      */
   556     public boolean isFunctionalInterface(TypeSymbol tsym) {
   557         try {
   558             findDescriptorSymbol(tsym);
   559             return true;
   560         } catch (FunctionDescriptorLookupError ex) {
   561             return false;
   562         }
   563     }
   565     public boolean isFunctionalInterface(Type site) {
   566         try {
   567             findDescriptorType(site);
   568             return true;
   569         } catch (FunctionDescriptorLookupError ex) {
   570             return false;
   571         }
   572     }
   574     public Type removeWildcards(Type site) {
   575         if (capture(site) != site) {
   576             Type formalInterface = site.tsym.type;
   577             ListBuffer<Type> typeargs = ListBuffer.lb();
   578             List<Type> actualTypeargs = site.getTypeArguments();
   579             //simply replace the wildcards with its bound
   580             for (Type t : formalInterface.getTypeArguments()) {
   581                 if (actualTypeargs.head.hasTag(WILDCARD)) {
   582                     WildcardType wt = (WildcardType)actualTypeargs.head;
   583                     typeargs.append(wt.type);
   584                 } else {
   585                     typeargs.append(actualTypeargs.head);
   586                 }
   587                 actualTypeargs = actualTypeargs.tail;
   588             }
   589             return subst(formalInterface, formalInterface.getTypeArguments(), typeargs.toList());
   590         } else {
   591             return site;
   592         }
   593     }
   594     // </editor-fold>
   596    /**
   597     * Scope filter used to skip methods that should be ignored (such as methods
   598     * overridden by j.l.Object) during function interface conversion/marker interface checks
   599     */
   600     class DescriptorFilter implements Filter<Symbol> {
   602        TypeSymbol origin;
   604        DescriptorFilter(TypeSymbol origin) {
   605            this.origin = origin;
   606        }
   608        @Override
   609        public boolean accepts(Symbol sym) {
   610            return sym.kind == Kinds.MTH &&
   611                    (sym.flags() & (ABSTRACT | DEFAULT)) == ABSTRACT &&
   612                    !overridesObjectMethod(origin, sym) &&
   613                    (interfaceCandidates(origin.type, (MethodSymbol)sym).head.flags() & DEFAULT) == 0;
   614        }
   615     };
   617     // <editor-fold defaultstate="collapsed" desc="isMarker">
   619     /**
   620      * A cache that keeps track of marker interfaces
   621      */
   622     class MarkerCache {
   624         private WeakHashMap<TypeSymbol, Entry> _map = new WeakHashMap<TypeSymbol, Entry>();
   626         class Entry {
   627             final boolean isMarkerIntf;
   628             final int prevMark;
   630             public Entry(boolean isMarkerIntf,
   631                     int prevMark) {
   632                 this.isMarkerIntf = isMarkerIntf;
   633                 this.prevMark = prevMark;
   634             }
   636             boolean matches(int mark) {
   637                 return  this.prevMark == mark;
   638             }
   639         }
   641         boolean get(TypeSymbol origin) throws FunctionDescriptorLookupError {
   642             Entry e = _map.get(origin);
   643             CompoundScope members = membersClosure(origin.type, false);
   644             if (e == null ||
   645                     !e.matches(members.getMark())) {
   646                 boolean isMarkerIntf = isMarkerInterfaceInternal(origin, members);
   647                 _map.put(origin, new Entry(isMarkerIntf, members.getMark()));
   648                 return isMarkerIntf;
   649             }
   650             else {
   651                 return e.isMarkerIntf;
   652             }
   653         }
   655         /**
   656          * Is given symbol a marker interface
   657          */
   658         public boolean isMarkerInterfaceInternal(TypeSymbol origin, CompoundScope membersCache) throws FunctionDescriptorLookupError {
   659             return !origin.isInterface() ?
   660                     false :
   661                     !membersCache.getElements(new DescriptorFilter(origin)).iterator().hasNext();
   662         }
   663     }
   665     private MarkerCache markerCache = new MarkerCache();
   667     /**
   668      * Is given type a marker interface?
   669      */
   670     public boolean isMarkerInterface(Type site) {
   671         return markerCache.get(site.tsym);
   672     }
   673     // </editor-fold>
   675     // <editor-fold defaultstate="collapsed" desc="isSubtype">
   676     /**
   677      * Is t an unchecked subtype of s?
   678      */
   679     public boolean isSubtypeUnchecked(Type t, Type s) {
   680         return isSubtypeUnchecked(t, s, noWarnings);
   681     }
   682     /**
   683      * Is t an unchecked subtype of s?
   684      */
   685     public boolean isSubtypeUnchecked(Type t, Type s, Warner warn) {
   686         boolean result = isSubtypeUncheckedInternal(t, s, warn);
   687         if (result) {
   688             checkUnsafeVarargsConversion(t, s, warn);
   689         }
   690         return result;
   691     }
   692     //where
   693         private boolean isSubtypeUncheckedInternal(Type t, Type s, Warner warn) {
   694             if (t.hasTag(ARRAY) && s.hasTag(ARRAY)) {
   695                 t = t.unannotatedType();
   696                 s = s.unannotatedType();
   697                 if (((ArrayType)t).elemtype.isPrimitive()) {
   698                     return isSameType(elemtype(t), elemtype(s));
   699                 } else {
   700                     return isSubtypeUnchecked(elemtype(t), elemtype(s), warn);
   701                 }
   702             } else if (isSubtype(t, s)) {
   703                 return true;
   704             }
   705             else if (t.tag == TYPEVAR) {
   706                 return isSubtypeUnchecked(t.getUpperBound(), s, warn);
   707             }
   708             else if (!s.isRaw()) {
   709                 Type t2 = asSuper(t, s.tsym);
   710                 if (t2 != null && t2.isRaw()) {
   711                     if (isReifiable(s))
   712                         warn.silentWarn(LintCategory.UNCHECKED);
   713                     else
   714                         warn.warn(LintCategory.UNCHECKED);
   715                     return true;
   716                 }
   717             }
   718             return false;
   719         }
   721         private void checkUnsafeVarargsConversion(Type t, Type s, Warner warn) {
   722             if (t.tag != ARRAY || isReifiable(t))
   723                 return;
   724             t = t.unannotatedType();
   725             s = s.unannotatedType();
   726             ArrayType from = (ArrayType)t;
   727             boolean shouldWarn = false;
   728             switch (s.tag) {
   729                 case ARRAY:
   730                     ArrayType to = (ArrayType)s;
   731                     shouldWarn = from.isVarargs() &&
   732                             !to.isVarargs() &&
   733                             !isReifiable(from);
   734                     break;
   735                 case CLASS:
   736                     shouldWarn = from.isVarargs();
   737                     break;
   738             }
   739             if (shouldWarn) {
   740                 warn.warn(LintCategory.VARARGS);
   741             }
   742         }
   744     /**
   745      * Is t a subtype of s?<br>
   746      * (not defined for Method and ForAll types)
   747      */
   748     final public boolean isSubtype(Type t, Type s) {
   749         return isSubtype(t, s, true);
   750     }
   751     final public boolean isSubtypeNoCapture(Type t, Type s) {
   752         return isSubtype(t, s, false);
   753     }
   754     public boolean isSubtype(Type t, Type s, boolean capture) {
   755         if (t == s)
   756             return true;
   758         t = t.unannotatedType();
   759         s = s.unannotatedType();
   761         if (t == s)
   762             return true;
   764         if (s.isPartial())
   765             return isSuperType(s, t);
   767         if (s.isCompound()) {
   768             for (Type s2 : interfaces(s).prepend(supertype(s))) {
   769                 if (!isSubtype(t, s2, capture))
   770                     return false;
   771             }
   772             return true;
   773         }
   775         Type lower = lowerBound(s);
   776         if (s != lower)
   777             return isSubtype(capture ? capture(t) : t, lower, false);
   779         return isSubtype.visit(capture ? capture(t) : t, s);
   780     }
   781     // where
   782         private TypeRelation isSubtype = new TypeRelation()
   783         {
   784             public Boolean visitType(Type t, Type s) {
   785                 switch (t.tag) {
   786                  case BYTE:
   787                      return (!s.hasTag(CHAR) && t.getTag().isSubRangeOf(s.getTag()));
   788                  case CHAR:
   789                      return (!s.hasTag(SHORT) && t.getTag().isSubRangeOf(s.getTag()));
   790                  case SHORT: case INT: case LONG:
   791                  case FLOAT: case DOUBLE:
   792                      return t.getTag().isSubRangeOf(s.getTag());
   793                  case BOOLEAN: case VOID:
   794                      return t.hasTag(s.getTag());
   795                  case TYPEVAR:
   796                      return isSubtypeNoCapture(t.getUpperBound(), s);
   797                  case BOT:
   798                      return
   799                          s.hasTag(BOT) || s.hasTag(CLASS) ||
   800                          s.hasTag(ARRAY) || s.hasTag(TYPEVAR);
   801                  case WILDCARD: //we shouldn't be here - avoids crash (see 7034495)
   802                  case NONE:
   803                      return false;
   804                  default:
   805                      throw new AssertionError("isSubtype " + t.tag);
   806                  }
   807             }
   809             private Set<TypePair> cache = new HashSet<TypePair>();
   811             private boolean containsTypeRecursive(Type t, Type s) {
   812                 TypePair pair = new TypePair(t, s);
   813                 if (cache.add(pair)) {
   814                     try {
   815                         return containsType(t.getTypeArguments(),
   816                                             s.getTypeArguments());
   817                     } finally {
   818                         cache.remove(pair);
   819                     }
   820                 } else {
   821                     return containsType(t.getTypeArguments(),
   822                                         rewriteSupers(s).getTypeArguments());
   823                 }
   824             }
   826             private Type rewriteSupers(Type t) {
   827                 if (!t.isParameterized())
   828                     return t;
   829                 ListBuffer<Type> from = lb();
   830                 ListBuffer<Type> to = lb();
   831                 adaptSelf(t, from, to);
   832                 if (from.isEmpty())
   833                     return t;
   834                 ListBuffer<Type> rewrite = lb();
   835                 boolean changed = false;
   836                 for (Type orig : to.toList()) {
   837                     Type s = rewriteSupers(orig);
   838                     if (s.isSuperBound() && !s.isExtendsBound()) {
   839                         s = new WildcardType(syms.objectType,
   840                                              BoundKind.UNBOUND,
   841                                              syms.boundClass);
   842                         changed = true;
   843                     } else if (s != orig) {
   844                         s = new WildcardType(upperBound(s),
   845                                              BoundKind.EXTENDS,
   846                                              syms.boundClass);
   847                         changed = true;
   848                     }
   849                     rewrite.append(s);
   850                 }
   851                 if (changed)
   852                     return subst(t.tsym.type, from.toList(), rewrite.toList());
   853                 else
   854                     return t;
   855             }
   857             @Override
   858             public Boolean visitClassType(ClassType t, Type s) {
   859                 Type sup = asSuper(t, s.tsym);
   860                 return sup != null
   861                     && sup.tsym == s.tsym
   862                     // You're not allowed to write
   863                     //     Vector<Object> vec = new Vector<String>();
   864                     // But with wildcards you can write
   865                     //     Vector<? extends Object> vec = new Vector<String>();
   866                     // which means that subtype checking must be done
   867                     // here instead of same-type checking (via containsType).
   868                     && (!s.isParameterized() || containsTypeRecursive(s, sup))
   869                     && isSubtypeNoCapture(sup.getEnclosingType(),
   870                                           s.getEnclosingType());
   871             }
   873             @Override
   874             public Boolean visitArrayType(ArrayType t, Type s) {
   875                 if (s.tag == ARRAY) {
   876                     if (t.elemtype.isPrimitive())
   877                         return isSameType(t.elemtype, elemtype(s));
   878                     else
   879                         return isSubtypeNoCapture(t.elemtype, elemtype(s));
   880                 }
   882                 if (s.tag == CLASS) {
   883                     Name sname = s.tsym.getQualifiedName();
   884                     return sname == names.java_lang_Object
   885                         || sname == names.java_lang_Cloneable
   886                         || sname == names.java_io_Serializable;
   887                 }
   889                 return false;
   890             }
   892             @Override
   893             public Boolean visitUndetVar(UndetVar t, Type s) {
   894                 //todo: test against origin needed? or replace with substitution?
   895                 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN) {
   896                     return true;
   897                 } else if (s.tag == BOT) {
   898                     //if 's' is 'null' there's no instantiated type U for which
   899                     //U <: s (but 'null' itself, which is not a valid type)
   900                     return false;
   901                 }
   903                 t.addBound(InferenceBound.UPPER, s, Types.this);
   904                 return true;
   905             }
   907             @Override
   908             public Boolean visitErrorType(ErrorType t, Type s) {
   909                 return true;
   910             }
   911         };
   913     /**
   914      * Is t a subtype of every type in given list `ts'?<br>
   915      * (not defined for Method and ForAll types)<br>
   916      * Allows unchecked conversions.
   917      */
   918     public boolean isSubtypeUnchecked(Type t, List<Type> ts, Warner warn) {
   919         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
   920             if (!isSubtypeUnchecked(t, l.head, warn))
   921                 return false;
   922         return true;
   923     }
   925     /**
   926      * Are corresponding elements of ts subtypes of ss?  If lists are
   927      * of different length, return false.
   928      */
   929     public boolean isSubtypes(List<Type> ts, List<Type> ss) {
   930         while (ts.tail != null && ss.tail != null
   931                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   932                isSubtype(ts.head, ss.head)) {
   933             ts = ts.tail;
   934             ss = ss.tail;
   935         }
   936         return ts.tail == null && ss.tail == null;
   937         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   938     }
   940     /**
   941      * Are corresponding elements of ts subtypes of ss, allowing
   942      * unchecked conversions?  If lists are of different length,
   943      * return false.
   944      **/
   945     public boolean isSubtypesUnchecked(List<Type> ts, List<Type> ss, Warner warn) {
   946         while (ts.tail != null && ss.tail != null
   947                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   948                isSubtypeUnchecked(ts.head, ss.head, warn)) {
   949             ts = ts.tail;
   950             ss = ss.tail;
   951         }
   952         return ts.tail == null && ss.tail == null;
   953         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   954     }
   955     // </editor-fold>
   957     // <editor-fold defaultstate="collapsed" desc="isSuperType">
   958     /**
   959      * Is t a supertype of s?
   960      */
   961     public boolean isSuperType(Type t, Type s) {
   962         switch (t.tag) {
   963         case ERROR:
   964             return true;
   965         case UNDETVAR: {
   966             UndetVar undet = (UndetVar)t;
   967             if (t == s ||
   968                 undet.qtype == s ||
   969                 s.tag == ERROR ||
   970                 s.tag == BOT) return true;
   971             undet.addBound(InferenceBound.LOWER, s, this);
   972             return true;
   973         }
   974         default:
   975             return isSubtype(s, t);
   976         }
   977     }
   978     // </editor-fold>
   980     // <editor-fold defaultstate="collapsed" desc="isSameType">
   981     /**
   982      * Are corresponding elements of the lists the same type?  If
   983      * lists are of different length, return false.
   984      */
   985     public boolean isSameTypes(List<Type> ts, List<Type> ss) {
   986         return isSameTypes(ts, ss, false);
   987     }
   988     public boolean isSameTypes(List<Type> ts, List<Type> ss, boolean strict) {
   989         while (ts.tail != null && ss.tail != null
   990                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   991                isSameType(ts.head, ss.head, strict)) {
   992             ts = ts.tail;
   993             ss = ss.tail;
   994         }
   995         return ts.tail == null && ss.tail == null;
   996         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   997     }
   999     /**
  1000      * Is t the same type as s?
  1001      */
  1002     public boolean isSameType(Type t, Type s) {
  1003         return isSameType(t, s, false);
  1005     public boolean isSameType(Type t, Type s, boolean strict) {
  1006         return strict ?
  1007                 isSameTypeStrict.visit(t, s) :
  1008                 isSameTypeLoose.visit(t, s);
  1010     // where
  1011         abstract class SameTypeVisitor extends TypeRelation {
  1013             public Boolean visitType(Type t, Type s) {
  1014                 if (t == s)
  1015                     return true;
  1017                 if (s.isPartial())
  1018                     return visit(s, t);
  1020                 switch (t.tag) {
  1021                 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
  1022                 case DOUBLE: case BOOLEAN: case VOID: case BOT: case NONE:
  1023                     return t.tag == s.tag;
  1024                 case TYPEVAR: {
  1025                     if (s.tag == TYPEVAR) {
  1026                         //type-substitution does not preserve type-var types
  1027                         //check that type var symbols and bounds are indeed the same
  1028                         return sameTypeVars((TypeVar)t, (TypeVar)s);
  1030                     else {
  1031                         //special case for s == ? super X, where upper(s) = u
  1032                         //check that u == t, where u has been set by Type.withTypeVar
  1033                         return s.isSuperBound() &&
  1034                                 !s.isExtendsBound() &&
  1035                                 visit(t, upperBound(s));
  1038                 default:
  1039                     throw new AssertionError("isSameType " + t.tag);
  1043             abstract boolean sameTypeVars(TypeVar tv1, TypeVar tv2);
  1045             @Override
  1046             public Boolean visitWildcardType(WildcardType t, Type s) {
  1047                 if (s.isPartial())
  1048                     return visit(s, t);
  1049                 else
  1050                     return false;
  1053             @Override
  1054             public Boolean visitClassType(ClassType t, Type s) {
  1055                 if (t == s)
  1056                     return true;
  1058                 if (s.isPartial())
  1059                     return visit(s, t);
  1061                 if (s.isSuperBound() && !s.isExtendsBound())
  1062                     return visit(t, upperBound(s)) && visit(t, lowerBound(s));
  1064                 if (t.isCompound() && s.isCompound()) {
  1065                     if (!visit(supertype(t), supertype(s)))
  1066                         return false;
  1068                     HashSet<UniqueType> set = new HashSet<UniqueType>();
  1069                     for (Type x : interfaces(t))
  1070                         set.add(new UniqueType(x, Types.this));
  1071                     for (Type x : interfaces(s)) {
  1072                         if (!set.remove(new UniqueType(x, Types.this)))
  1073                             return false;
  1075                     return (set.isEmpty());
  1077                 return t.tsym == s.tsym
  1078                     && visit(t.getEnclosingType(), s.getEnclosingType())
  1079                     && containsTypes(t.getTypeArguments(), s.getTypeArguments());
  1082             abstract protected boolean containsTypes(List<Type> ts1, List<Type> ts2);
  1084             @Override
  1085             public Boolean visitArrayType(ArrayType t, Type s) {
  1086                 if (t == s)
  1087                     return true;
  1089                 if (s.isPartial())
  1090                     return visit(s, t);
  1092                 return s.hasTag(ARRAY)
  1093                     && containsTypeEquivalent(t.elemtype, elemtype(s));
  1096             @Override
  1097             public Boolean visitMethodType(MethodType t, Type s) {
  1098                 // isSameType for methods does not take thrown
  1099                 // exceptions into account!
  1100                 return hasSameArgs(t, s) && visit(t.getReturnType(), s.getReturnType());
  1103             @Override
  1104             public Boolean visitPackageType(PackageType t, Type s) {
  1105                 return t == s;
  1108             @Override
  1109             public Boolean visitForAll(ForAll t, Type s) {
  1110                 if (s.tag != FORALL)
  1111                     return false;
  1113                 ForAll forAll = (ForAll)s;
  1114                 return hasSameBounds(t, forAll)
  1115                     && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
  1118             @Override
  1119             public Boolean visitUndetVar(UndetVar t, Type s) {
  1120                 if (s.tag == WILDCARD)
  1121                     // FIXME, this might be leftovers from before capture conversion
  1122                     return false;
  1124                 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN)
  1125                     return true;
  1127                 t.addBound(InferenceBound.EQ, s, Types.this);
  1129                 return true;
  1132             @Override
  1133             public Boolean visitErrorType(ErrorType t, Type s) {
  1134                 return true;
  1138         /**
  1139          * Standard type-equality relation - type variables are considered
  1140          * equals if they share the same type symbol.
  1141          */
  1142         TypeRelation isSameTypeLoose = new SameTypeVisitor() {
  1143             @Override
  1144             boolean sameTypeVars(TypeVar tv1, TypeVar tv2) {
  1145                 return tv1.tsym == tv2.tsym && visit(tv1.getUpperBound(), tv2.getUpperBound());
  1147             @Override
  1148             protected boolean containsTypes(List<Type> ts1, List<Type> ts2) {
  1149                 return containsTypeEquivalent(ts1, ts2);
  1151         };
  1153         /**
  1154          * Strict type-equality relation - type variables are considered
  1155          * equals if they share the same object identity.
  1156          */
  1157         TypeRelation isSameTypeStrict = new SameTypeVisitor() {
  1158             @Override
  1159             boolean sameTypeVars(TypeVar tv1, TypeVar tv2) {
  1160                 return tv1 == tv2;
  1162             @Override
  1163             protected boolean containsTypes(List<Type> ts1, List<Type> ts2) {
  1164                 return isSameTypes(ts1, ts2, true);
  1166         };
  1167     // </editor-fold>
  1169     // <editor-fold defaultstate="collapsed" desc="Contains Type">
  1170     public boolean containedBy(Type t, Type s) {
  1171         switch (t.tag) {
  1172         case UNDETVAR:
  1173             if (s.tag == WILDCARD) {
  1174                 UndetVar undetvar = (UndetVar)t;
  1175                 WildcardType wt = (WildcardType)s;
  1176                 switch(wt.kind) {
  1177                     case UNBOUND: //similar to ? extends Object
  1178                     case EXTENDS: {
  1179                         Type bound = upperBound(s);
  1180                         undetvar.addBound(InferenceBound.UPPER, bound, this);
  1181                         break;
  1183                     case SUPER: {
  1184                         Type bound = lowerBound(s);
  1185                         undetvar.addBound(InferenceBound.LOWER, bound, this);
  1186                         break;
  1189                 return true;
  1190             } else {
  1191                 return isSameType(t, s);
  1193         case ERROR:
  1194             return true;
  1195         default:
  1196             return containsType(s, t);
  1200     boolean containsType(List<Type> ts, List<Type> ss) {
  1201         while (ts.nonEmpty() && ss.nonEmpty()
  1202                && containsType(ts.head, ss.head)) {
  1203             ts = ts.tail;
  1204             ss = ss.tail;
  1206         return ts.isEmpty() && ss.isEmpty();
  1209     /**
  1210      * Check if t contains s.
  1212      * <p>T contains S if:
  1214      * <p>{@code L(T) <: L(S) && U(S) <: U(T)}
  1216      * <p>This relation is only used by ClassType.isSubtype(), that
  1217      * is,
  1219      * <p>{@code C<S> <: C<T> if T contains S.}
  1221      * <p>Because of F-bounds, this relation can lead to infinite
  1222      * recursion.  Thus we must somehow break that recursion.  Notice
  1223      * that containsType() is only called from ClassType.isSubtype().
  1224      * Since the arguments have already been checked against their
  1225      * bounds, we know:
  1227      * <p>{@code U(S) <: U(T) if T is "super" bound (U(T) *is* the bound)}
  1229      * <p>{@code L(T) <: L(S) if T is "extends" bound (L(T) is bottom)}
  1231      * @param t a type
  1232      * @param s a type
  1233      */
  1234     public boolean containsType(Type t, Type s) {
  1235         return containsType.visit(t, s);
  1237     // where
  1238         private TypeRelation containsType = new TypeRelation() {
  1240             private Type U(Type t) {
  1241                 while (t.tag == WILDCARD) {
  1242                     WildcardType w = (WildcardType)t;
  1243                     if (w.isSuperBound())
  1244                         return w.bound == null ? syms.objectType : w.bound.bound;
  1245                     else
  1246                         t = w.type;
  1248                 return t;
  1251             private Type L(Type t) {
  1252                 while (t.tag == WILDCARD) {
  1253                     WildcardType w = (WildcardType)t;
  1254                     if (w.isExtendsBound())
  1255                         return syms.botType;
  1256                     else
  1257                         t = w.type;
  1259                 return t;
  1262             public Boolean visitType(Type t, Type s) {
  1263                 if (s.isPartial())
  1264                     return containedBy(s, t);
  1265                 else
  1266                     return isSameType(t, s);
  1269 //            void debugContainsType(WildcardType t, Type s) {
  1270 //                System.err.println();
  1271 //                System.err.format(" does %s contain %s?%n", t, s);
  1272 //                System.err.format(" %s U(%s) <: U(%s) %s = %s%n",
  1273 //                                  upperBound(s), s, t, U(t),
  1274 //                                  t.isSuperBound()
  1275 //                                  || isSubtypeNoCapture(upperBound(s), U(t)));
  1276 //                System.err.format(" %s L(%s) <: L(%s) %s = %s%n",
  1277 //                                  L(t), t, s, lowerBound(s),
  1278 //                                  t.isExtendsBound()
  1279 //                                  || isSubtypeNoCapture(L(t), lowerBound(s)));
  1280 //                System.err.println();
  1281 //            }
  1283             @Override
  1284             public Boolean visitWildcardType(WildcardType t, Type s) {
  1285                 if (s.isPartial())
  1286                     return containedBy(s, t);
  1287                 else {
  1288 //                    debugContainsType(t, s);
  1289                     return isSameWildcard(t, s)
  1290                         || isCaptureOf(s, t)
  1291                         || ((t.isExtendsBound() || isSubtypeNoCapture(L(t), lowerBound(s))) &&
  1292                             (t.isSuperBound() || isSubtypeNoCapture(upperBound(s), U(t))));
  1296             @Override
  1297             public Boolean visitUndetVar(UndetVar t, Type s) {
  1298                 if (s.tag != WILDCARD)
  1299                     return isSameType(t, s);
  1300                 else
  1301                     return false;
  1304             @Override
  1305             public Boolean visitErrorType(ErrorType t, Type s) {
  1306                 return true;
  1308         };
  1310     public boolean isCaptureOf(Type s, WildcardType t) {
  1311         if (s.tag != TYPEVAR || !((TypeVar)s).isCaptured())
  1312             return false;
  1313         return isSameWildcard(t, ((CapturedType)s).wildcard);
  1316     public boolean isSameWildcard(WildcardType t, Type s) {
  1317         if (s.tag != WILDCARD)
  1318             return false;
  1319         WildcardType w = (WildcardType)s;
  1320         return w.kind == t.kind && w.type == t.type;
  1323     public boolean containsTypeEquivalent(List<Type> ts, List<Type> ss) {
  1324         while (ts.nonEmpty() && ss.nonEmpty()
  1325                && containsTypeEquivalent(ts.head, ss.head)) {
  1326             ts = ts.tail;
  1327             ss = ss.tail;
  1329         return ts.isEmpty() && ss.isEmpty();
  1331     // </editor-fold>
  1333     // <editor-fold defaultstate="collapsed" desc="isCastable">
  1334     public boolean isCastable(Type t, Type s) {
  1335         return isCastable(t, s, noWarnings);
  1338     /**
  1339      * Is t is castable to s?<br>
  1340      * s is assumed to be an erased type.<br>
  1341      * (not defined for Method and ForAll types).
  1342      */
  1343     public boolean isCastable(Type t, Type s, Warner warn) {
  1344         if (t == s)
  1345             return true;
  1347         if (t.isPrimitive() != s.isPrimitive())
  1348             return allowBoxing && (
  1349                     isConvertible(t, s, warn)
  1350                     || (allowObjectToPrimitiveCast &&
  1351                         s.isPrimitive() &&
  1352                         isSubtype(boxedClass(s).type, t)));
  1353         if (warn != warnStack.head) {
  1354             try {
  1355                 warnStack = warnStack.prepend(warn);
  1356                 checkUnsafeVarargsConversion(t, s, warn);
  1357                 return isCastable.visit(t,s);
  1358             } finally {
  1359                 warnStack = warnStack.tail;
  1361         } else {
  1362             return isCastable.visit(t,s);
  1365     // where
  1366         private TypeRelation isCastable = new TypeRelation() {
  1368             public Boolean visitType(Type t, Type s) {
  1369                 if (s.tag == ERROR)
  1370                     return true;
  1372                 switch (t.tag) {
  1373                 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
  1374                 case DOUBLE:
  1375                     return s.isNumeric();
  1376                 case BOOLEAN:
  1377                     return s.tag == BOOLEAN;
  1378                 case VOID:
  1379                     return false;
  1380                 case BOT:
  1381                     return isSubtype(t, s);
  1382                 default:
  1383                     throw new AssertionError();
  1387             @Override
  1388             public Boolean visitWildcardType(WildcardType t, Type s) {
  1389                 return isCastable(upperBound(t), s, warnStack.head);
  1392             @Override
  1393             public Boolean visitClassType(ClassType t, Type s) {
  1394                 if (s.tag == ERROR || s.tag == BOT)
  1395                     return true;
  1397                 if (s.tag == TYPEVAR) {
  1398                     if (isCastable(t, s.getUpperBound(), noWarnings)) {
  1399                         warnStack.head.warn(LintCategory.UNCHECKED);
  1400                         return true;
  1401                     } else {
  1402                         return false;
  1406                 if (t.isCompound()) {
  1407                     Warner oldWarner = warnStack.head;
  1408                     warnStack.head = noWarnings;
  1409                     if (!visit(supertype(t), s))
  1410                         return false;
  1411                     for (Type intf : interfaces(t)) {
  1412                         if (!visit(intf, s))
  1413                             return false;
  1415                     if (warnStack.head.hasLint(LintCategory.UNCHECKED))
  1416                         oldWarner.warn(LintCategory.UNCHECKED);
  1417                     return true;
  1420                 if (s.isCompound()) {
  1421                     // call recursively to reuse the above code
  1422                     return visitClassType((ClassType)s, t);
  1425                 if (s.tag == CLASS || s.tag == ARRAY) {
  1426                     boolean upcast;
  1427                     if ((upcast = isSubtype(erasure(t), erasure(s)))
  1428                         || isSubtype(erasure(s), erasure(t))) {
  1429                         if (!upcast && s.tag == ARRAY) {
  1430                             if (!isReifiable(s))
  1431                                 warnStack.head.warn(LintCategory.UNCHECKED);
  1432                             return true;
  1433                         } else if (s.isRaw()) {
  1434                             return true;
  1435                         } else if (t.isRaw()) {
  1436                             if (!isUnbounded(s))
  1437                                 warnStack.head.warn(LintCategory.UNCHECKED);
  1438                             return true;
  1440                         // Assume |a| <: |b|
  1441                         final Type a = upcast ? t : s;
  1442                         final Type b = upcast ? s : t;
  1443                         final boolean HIGH = true;
  1444                         final boolean LOW = false;
  1445                         final boolean DONT_REWRITE_TYPEVARS = false;
  1446                         Type aHigh = rewriteQuantifiers(a, HIGH, DONT_REWRITE_TYPEVARS);
  1447                         Type aLow  = rewriteQuantifiers(a, LOW,  DONT_REWRITE_TYPEVARS);
  1448                         Type bHigh = rewriteQuantifiers(b, HIGH, DONT_REWRITE_TYPEVARS);
  1449                         Type bLow  = rewriteQuantifiers(b, LOW,  DONT_REWRITE_TYPEVARS);
  1450                         Type lowSub = asSub(bLow, aLow.tsym);
  1451                         Type highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
  1452                         if (highSub == null) {
  1453                             final boolean REWRITE_TYPEVARS = true;
  1454                             aHigh = rewriteQuantifiers(a, HIGH, REWRITE_TYPEVARS);
  1455                             aLow  = rewriteQuantifiers(a, LOW,  REWRITE_TYPEVARS);
  1456                             bHigh = rewriteQuantifiers(b, HIGH, REWRITE_TYPEVARS);
  1457                             bLow  = rewriteQuantifiers(b, LOW,  REWRITE_TYPEVARS);
  1458                             lowSub = asSub(bLow, aLow.tsym);
  1459                             highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
  1461                         if (highSub != null) {
  1462                             if (!(a.tsym == highSub.tsym && a.tsym == lowSub.tsym)) {
  1463                                 Assert.error(a.tsym + " != " + highSub.tsym + " != " + lowSub.tsym);
  1465                             if (!disjointTypes(aHigh.allparams(), highSub.allparams())
  1466                                 && !disjointTypes(aHigh.allparams(), lowSub.allparams())
  1467                                 && !disjointTypes(aLow.allparams(), highSub.allparams())
  1468                                 && !disjointTypes(aLow.allparams(), lowSub.allparams())) {
  1469                                 if (upcast ? giveWarning(a, b) :
  1470                                     giveWarning(b, a))
  1471                                     warnStack.head.warn(LintCategory.UNCHECKED);
  1472                                 return true;
  1475                         if (isReifiable(s))
  1476                             return isSubtypeUnchecked(a, b);
  1477                         else
  1478                             return isSubtypeUnchecked(a, b, warnStack.head);
  1481                     // Sidecast
  1482                     if (s.tag == CLASS) {
  1483                         if ((s.tsym.flags() & INTERFACE) != 0) {
  1484                             return ((t.tsym.flags() & FINAL) == 0)
  1485                                 ? sideCast(t, s, warnStack.head)
  1486                                 : sideCastFinal(t, s, warnStack.head);
  1487                         } else if ((t.tsym.flags() & INTERFACE) != 0) {
  1488                             return ((s.tsym.flags() & FINAL) == 0)
  1489                                 ? sideCast(t, s, warnStack.head)
  1490                                 : sideCastFinal(t, s, warnStack.head);
  1491                         } else {
  1492                             // unrelated class types
  1493                             return false;
  1497                 return false;
  1500             @Override
  1501             public Boolean visitArrayType(ArrayType t, Type s) {
  1502                 switch (s.tag) {
  1503                 case ERROR:
  1504                 case BOT:
  1505                     return true;
  1506                 case TYPEVAR:
  1507                     if (isCastable(s, t, noWarnings)) {
  1508                         warnStack.head.warn(LintCategory.UNCHECKED);
  1509                         return true;
  1510                     } else {
  1511                         return false;
  1513                 case CLASS:
  1514                     return isSubtype(t, s);
  1515                 case ARRAY:
  1516                     if (elemtype(t).isPrimitive() || elemtype(s).isPrimitive()) {
  1517                         return elemtype(t).tag == elemtype(s).tag;
  1518                     } else {
  1519                         return visit(elemtype(t), elemtype(s));
  1521                 default:
  1522                     return false;
  1526             @Override
  1527             public Boolean visitTypeVar(TypeVar t, Type s) {
  1528                 switch (s.tag) {
  1529                 case ERROR:
  1530                 case BOT:
  1531                     return true;
  1532                 case TYPEVAR:
  1533                     if (isSubtype(t, s)) {
  1534                         return true;
  1535                     } else if (isCastable(t.bound, s, noWarnings)) {
  1536                         warnStack.head.warn(LintCategory.UNCHECKED);
  1537                         return true;
  1538                     } else {
  1539                         return false;
  1541                 default:
  1542                     return isCastable(t.bound, s, warnStack.head);
  1546             @Override
  1547             public Boolean visitErrorType(ErrorType t, Type s) {
  1548                 return true;
  1550         };
  1551     // </editor-fold>
  1553     // <editor-fold defaultstate="collapsed" desc="disjointTypes">
  1554     public boolean disjointTypes(List<Type> ts, List<Type> ss) {
  1555         while (ts.tail != null && ss.tail != null) {
  1556             if (disjointType(ts.head, ss.head)) return true;
  1557             ts = ts.tail;
  1558             ss = ss.tail;
  1560         return false;
  1563     /**
  1564      * Two types or wildcards are considered disjoint if it can be
  1565      * proven that no type can be contained in both. It is
  1566      * conservative in that it is allowed to say that two types are
  1567      * not disjoint, even though they actually are.
  1569      * The type {@code C<X>} is castable to {@code C<Y>} exactly if
  1570      * {@code X} and {@code Y} are not disjoint.
  1571      */
  1572     public boolean disjointType(Type t, Type s) {
  1573         return disjointType.visit(t, s);
  1575     // where
  1576         private TypeRelation disjointType = new TypeRelation() {
  1578             private Set<TypePair> cache = new HashSet<TypePair>();
  1580             public Boolean visitType(Type t, Type s) {
  1581                 if (s.tag == WILDCARD)
  1582                     return visit(s, t);
  1583                 else
  1584                     return notSoftSubtypeRecursive(t, s) || notSoftSubtypeRecursive(s, t);
  1587             private boolean isCastableRecursive(Type t, Type s) {
  1588                 TypePair pair = new TypePair(t, s);
  1589                 if (cache.add(pair)) {
  1590                     try {
  1591                         return Types.this.isCastable(t, s);
  1592                     } finally {
  1593                         cache.remove(pair);
  1595                 } else {
  1596                     return true;
  1600             private boolean notSoftSubtypeRecursive(Type t, Type s) {
  1601                 TypePair pair = new TypePair(t, s);
  1602                 if (cache.add(pair)) {
  1603                     try {
  1604                         return Types.this.notSoftSubtype(t, s);
  1605                     } finally {
  1606                         cache.remove(pair);
  1608                 } else {
  1609                     return false;
  1613             @Override
  1614             public Boolean visitWildcardType(WildcardType t, Type s) {
  1615                 if (t.isUnbound())
  1616                     return false;
  1618                 if (s.tag != WILDCARD) {
  1619                     if (t.isExtendsBound())
  1620                         return notSoftSubtypeRecursive(s, t.type);
  1621                     else // isSuperBound()
  1622                         return notSoftSubtypeRecursive(t.type, s);
  1625                 if (s.isUnbound())
  1626                     return false;
  1628                 if (t.isExtendsBound()) {
  1629                     if (s.isExtendsBound())
  1630                         return !isCastableRecursive(t.type, upperBound(s));
  1631                     else if (s.isSuperBound())
  1632                         return notSoftSubtypeRecursive(lowerBound(s), t.type);
  1633                 } else if (t.isSuperBound()) {
  1634                     if (s.isExtendsBound())
  1635                         return notSoftSubtypeRecursive(t.type, upperBound(s));
  1637                 return false;
  1639         };
  1640     // </editor-fold>
  1642     // <editor-fold defaultstate="collapsed" desc="lowerBoundArgtypes">
  1643     /**
  1644      * Returns the lower bounds of the formals of a method.
  1645      */
  1646     public List<Type> lowerBoundArgtypes(Type t) {
  1647         return lowerBounds(t.getParameterTypes());
  1649     public List<Type> lowerBounds(List<Type> ts) {
  1650         return map(ts, lowerBoundMapping);
  1652     private final Mapping lowerBoundMapping = new Mapping("lowerBound") {
  1653             public Type apply(Type t) {
  1654                 return lowerBound(t);
  1656         };
  1657     // </editor-fold>
  1659     // <editor-fold defaultstate="collapsed" desc="notSoftSubtype">
  1660     /**
  1661      * This relation answers the question: is impossible that
  1662      * something of type `t' can be a subtype of `s'? This is
  1663      * different from the question "is `t' not a subtype of `s'?"
  1664      * when type variables are involved: Integer is not a subtype of T
  1665      * where {@code <T extends Number>} but it is not true that Integer cannot
  1666      * possibly be a subtype of T.
  1667      */
  1668     public boolean notSoftSubtype(Type t, Type s) {
  1669         if (t == s) return false;
  1670         if (t.tag == TYPEVAR) {
  1671             TypeVar tv = (TypeVar) t;
  1672             return !isCastable(tv.bound,
  1673                                relaxBound(s),
  1674                                noWarnings);
  1676         if (s.tag != WILDCARD)
  1677             s = upperBound(s);
  1679         return !isSubtype(t, relaxBound(s));
  1682     private Type relaxBound(Type t) {
  1683         if (t.tag == TYPEVAR) {
  1684             while (t.tag == TYPEVAR)
  1685                 t = t.getUpperBound();
  1686             t = rewriteQuantifiers(t, true, true);
  1688         return t;
  1690     // </editor-fold>
  1692     // <editor-fold defaultstate="collapsed" desc="isReifiable">
  1693     public boolean isReifiable(Type t) {
  1694         return isReifiable.visit(t);
  1696     // where
  1697         private UnaryVisitor<Boolean> isReifiable = new UnaryVisitor<Boolean>() {
  1699             public Boolean visitType(Type t, Void ignored) {
  1700                 return true;
  1703             @Override
  1704             public Boolean visitClassType(ClassType t, Void ignored) {
  1705                 if (t.isCompound())
  1706                     return false;
  1707                 else {
  1708                     if (!t.isParameterized())
  1709                         return true;
  1711                     for (Type param : t.allparams()) {
  1712                         if (!param.isUnbound())
  1713                             return false;
  1715                     return true;
  1719             @Override
  1720             public Boolean visitArrayType(ArrayType t, Void ignored) {
  1721                 return visit(t.elemtype);
  1724             @Override
  1725             public Boolean visitTypeVar(TypeVar t, Void ignored) {
  1726                 return false;
  1728         };
  1729     // </editor-fold>
  1731     // <editor-fold defaultstate="collapsed" desc="Array Utils">
  1732     public boolean isArray(Type t) {
  1733         while (t.tag == WILDCARD)
  1734             t = upperBound(t);
  1735         return t.tag == ARRAY;
  1738     /**
  1739      * The element type of an array.
  1740      */
  1741     public Type elemtype(Type t) {
  1742         switch (t.tag) {
  1743         case WILDCARD:
  1744             return elemtype(upperBound(t));
  1745         case ARRAY:
  1746             t = t.unannotatedType();
  1747             return ((ArrayType)t).elemtype;
  1748         case FORALL:
  1749             return elemtype(((ForAll)t).qtype);
  1750         case ERROR:
  1751             return t;
  1752         default:
  1753             return null;
  1757     public Type elemtypeOrType(Type t) {
  1758         Type elemtype = elemtype(t);
  1759         return elemtype != null ?
  1760             elemtype :
  1761             t;
  1764     /**
  1765      * Mapping to take element type of an arraytype
  1766      */
  1767     private Mapping elemTypeFun = new Mapping ("elemTypeFun") {
  1768         public Type apply(Type t) { return elemtype(t); }
  1769     };
  1771     /**
  1772      * The number of dimensions of an array type.
  1773      */
  1774     public int dimensions(Type t) {
  1775         int result = 0;
  1776         while (t.tag == ARRAY) {
  1777             result++;
  1778             t = elemtype(t);
  1780         return result;
  1783     /**
  1784      * Returns an ArrayType with the component type t
  1786      * @param t The component type of the ArrayType
  1787      * @return the ArrayType for the given component
  1788      */
  1789     public ArrayType makeArrayType(Type t) {
  1790         if (t.tag == VOID ||
  1791             t.tag == PACKAGE) {
  1792             Assert.error("Type t must not be a VOID or PACKAGE type, " + t.toString());
  1794         return new ArrayType(t, syms.arrayClass);
  1796     // </editor-fold>
  1798     // <editor-fold defaultstate="collapsed" desc="asSuper">
  1799     /**
  1800      * Return the (most specific) base type of t that starts with the
  1801      * given symbol.  If none exists, return null.
  1803      * @param t a type
  1804      * @param sym a symbol
  1805      */
  1806     public Type asSuper(Type t, Symbol sym) {
  1807         return asSuper.visit(t, sym);
  1809     // where
  1810         private SimpleVisitor<Type,Symbol> asSuper = new SimpleVisitor<Type,Symbol>() {
  1812             public Type visitType(Type t, Symbol sym) {
  1813                 return null;
  1816             @Override
  1817             public Type visitClassType(ClassType t, Symbol sym) {
  1818                 if (t.tsym == sym)
  1819                     return t;
  1821                 Type st = supertype(t);
  1822                 if (st.tag == CLASS || st.tag == TYPEVAR || st.tag == ERROR) {
  1823                     Type x = asSuper(st, sym);
  1824                     if (x != null)
  1825                         return x;
  1827                 if ((sym.flags() & INTERFACE) != 0) {
  1828                     for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
  1829                         Type x = asSuper(l.head, sym);
  1830                         if (x != null)
  1831                             return x;
  1834                 return null;
  1837             @Override
  1838             public Type visitArrayType(ArrayType t, Symbol sym) {
  1839                 return isSubtype(t, sym.type) ? sym.type : null;
  1842             @Override
  1843             public Type visitTypeVar(TypeVar t, Symbol sym) {
  1844                 if (t.tsym == sym)
  1845                     return t;
  1846                 else
  1847                     return asSuper(t.bound, sym);
  1850             @Override
  1851             public Type visitErrorType(ErrorType t, Symbol sym) {
  1852                 return t;
  1854         };
  1856     /**
  1857      * Return the base type of t or any of its outer types that starts
  1858      * with the given symbol.  If none exists, return null.
  1860      * @param t a type
  1861      * @param sym a symbol
  1862      */
  1863     public Type asOuterSuper(Type t, Symbol sym) {
  1864         switch (t.tag) {
  1865         case CLASS:
  1866             do {
  1867                 Type s = asSuper(t, sym);
  1868                 if (s != null) return s;
  1869                 t = t.getEnclosingType();
  1870             } while (t.tag == CLASS);
  1871             return null;
  1872         case ARRAY:
  1873             return isSubtype(t, sym.type) ? sym.type : null;
  1874         case TYPEVAR:
  1875             return asSuper(t, sym);
  1876         case ERROR:
  1877             return t;
  1878         default:
  1879             return null;
  1883     /**
  1884      * Return the base type of t or any of its enclosing types that
  1885      * starts with the given symbol.  If none exists, return null.
  1887      * @param t a type
  1888      * @param sym a symbol
  1889      */
  1890     public Type asEnclosingSuper(Type t, Symbol sym) {
  1891         switch (t.tag) {
  1892         case CLASS:
  1893             do {
  1894                 Type s = asSuper(t, sym);
  1895                 if (s != null) return s;
  1896                 Type outer = t.getEnclosingType();
  1897                 t = (outer.tag == CLASS) ? outer :
  1898                     (t.tsym.owner.enclClass() != null) ? t.tsym.owner.enclClass().type :
  1899                     Type.noType;
  1900             } while (t.tag == CLASS);
  1901             return null;
  1902         case ARRAY:
  1903             return isSubtype(t, sym.type) ? sym.type : null;
  1904         case TYPEVAR:
  1905             return asSuper(t, sym);
  1906         case ERROR:
  1907             return t;
  1908         default:
  1909             return null;
  1912     // </editor-fold>
  1914     // <editor-fold defaultstate="collapsed" desc="memberType">
  1915     /**
  1916      * The type of given symbol, seen as a member of t.
  1918      * @param t a type
  1919      * @param sym a symbol
  1920      */
  1921     public Type memberType(Type t, Symbol sym) {
  1922         return (sym.flags() & STATIC) != 0
  1923             ? sym.type
  1924             : memberType.visit(t, sym);
  1926     // where
  1927         private SimpleVisitor<Type,Symbol> memberType = new SimpleVisitor<Type,Symbol>() {
  1929             public Type visitType(Type t, Symbol sym) {
  1930                 return sym.type;
  1933             @Override
  1934             public Type visitWildcardType(WildcardType t, Symbol sym) {
  1935                 return memberType(upperBound(t), sym);
  1938             @Override
  1939             public Type visitClassType(ClassType t, Symbol sym) {
  1940                 Symbol owner = sym.owner;
  1941                 long flags = sym.flags();
  1942                 if (((flags & STATIC) == 0) && owner.type.isParameterized()) {
  1943                     Type base = asOuterSuper(t, owner);
  1944                     //if t is an intersection type T = CT & I1 & I2 ... & In
  1945                     //its supertypes CT, I1, ... In might contain wildcards
  1946                     //so we need to go through capture conversion
  1947                     base = t.isCompound() ? capture(base) : base;
  1948                     if (base != null) {
  1949                         List<Type> ownerParams = owner.type.allparams();
  1950                         List<Type> baseParams = base.allparams();
  1951                         if (ownerParams.nonEmpty()) {
  1952                             if (baseParams.isEmpty()) {
  1953                                 // then base is a raw type
  1954                                 return erasure(sym.type);
  1955                             } else {
  1956                                 return subst(sym.type, ownerParams, baseParams);
  1961                 return sym.type;
  1964             @Override
  1965             public Type visitTypeVar(TypeVar t, Symbol sym) {
  1966                 return memberType(t.bound, sym);
  1969             @Override
  1970             public Type visitErrorType(ErrorType t, Symbol sym) {
  1971                 return t;
  1973         };
  1974     // </editor-fold>
  1976     // <editor-fold defaultstate="collapsed" desc="isAssignable">
  1977     public boolean isAssignable(Type t, Type s) {
  1978         return isAssignable(t, s, noWarnings);
  1981     /**
  1982      * Is t assignable to s?<br>
  1983      * Equivalent to subtype except for constant values and raw
  1984      * types.<br>
  1985      * (not defined for Method and ForAll types)
  1986      */
  1987     public boolean isAssignable(Type t, Type s, Warner warn) {
  1988         if (t.tag == ERROR)
  1989             return true;
  1990         if (t.tag.isSubRangeOf(INT) && t.constValue() != null) {
  1991             int value = ((Number)t.constValue()).intValue();
  1992             switch (s.tag) {
  1993             case BYTE:
  1994                 if (Byte.MIN_VALUE <= value && value <= Byte.MAX_VALUE)
  1995                     return true;
  1996                 break;
  1997             case CHAR:
  1998                 if (Character.MIN_VALUE <= value && value <= Character.MAX_VALUE)
  1999                     return true;
  2000                 break;
  2001             case SHORT:
  2002                 if (Short.MIN_VALUE <= value && value <= Short.MAX_VALUE)
  2003                     return true;
  2004                 break;
  2005             case INT:
  2006                 return true;
  2007             case CLASS:
  2008                 switch (unboxedType(s).tag) {
  2009                 case BYTE:
  2010                 case CHAR:
  2011                 case SHORT:
  2012                     return isAssignable(t, unboxedType(s), warn);
  2014                 break;
  2017         return isConvertible(t, s, warn);
  2019     // </editor-fold>
  2021     // <editor-fold defaultstate="collapsed" desc="erasure">
  2022     /**
  2023      * The erasure of t {@code |t|} -- the type that results when all
  2024      * type parameters in t are deleted.
  2025      */
  2026     public Type erasure(Type t) {
  2027         return eraseNotNeeded(t)? t : erasure(t, false);
  2029     //where
  2030     private boolean eraseNotNeeded(Type t) {
  2031         // We don't want to erase primitive types and String type as that
  2032         // operation is idempotent. Also, erasing these could result in loss
  2033         // of information such as constant values attached to such types.
  2034         return (t.isPrimitive()) || (syms.stringType.tsym == t.tsym);
  2037     private Type erasure(Type t, boolean recurse) {
  2038         if (t.isPrimitive())
  2039             return t; /* fast special case */
  2040         else
  2041             return erasure.visit(t, recurse);
  2043     // where
  2044         private SimpleVisitor<Type, Boolean> erasure = new SimpleVisitor<Type, Boolean>() {
  2045             public Type visitType(Type t, Boolean recurse) {
  2046                 if (t.isPrimitive())
  2047                     return t; /*fast special case*/
  2048                 else
  2049                     return t.map(recurse ? erasureRecFun : erasureFun);
  2052             @Override
  2053             public Type visitWildcardType(WildcardType t, Boolean recurse) {
  2054                 return erasure(upperBound(t), recurse);
  2057             @Override
  2058             public Type visitClassType(ClassType t, Boolean recurse) {
  2059                 Type erased = t.tsym.erasure(Types.this);
  2060                 if (recurse) {
  2061                     erased = new ErasedClassType(erased.getEnclosingType(),erased.tsym);
  2063                 return erased;
  2066             @Override
  2067             public Type visitTypeVar(TypeVar t, Boolean recurse) {
  2068                 return erasure(t.bound, recurse);
  2071             @Override
  2072             public Type visitErrorType(ErrorType t, Boolean recurse) {
  2073                 return t;
  2076             @Override
  2077             public Type visitAnnotatedType(AnnotatedType t, Boolean recurse) {
  2078                 Type erased = erasure(t.underlyingType, recurse);
  2079                 if (erased.getKind() == TypeKind.ANNOTATED) {
  2080                     // This can only happen when the underlying type is a
  2081                     // type variable and the upper bound of it is annotated.
  2082                     // The annotation on the type variable overrides the one
  2083                     // on the bound.
  2084                     erased = ((AnnotatedType)erased).underlyingType;
  2086                 return new AnnotatedType(t.typeAnnotations, erased);
  2088         };
  2090     private Mapping erasureFun = new Mapping ("erasure") {
  2091             public Type apply(Type t) { return erasure(t); }
  2092         };
  2094     private Mapping erasureRecFun = new Mapping ("erasureRecursive") {
  2095         public Type apply(Type t) { return erasureRecursive(t); }
  2096     };
  2098     public List<Type> erasure(List<Type> ts) {
  2099         return Type.map(ts, erasureFun);
  2102     public Type erasureRecursive(Type t) {
  2103         return erasure(t, true);
  2106     public List<Type> erasureRecursive(List<Type> ts) {
  2107         return Type.map(ts, erasureRecFun);
  2109     // </editor-fold>
  2111     // <editor-fold defaultstate="collapsed" desc="makeCompoundType">
  2112     /**
  2113      * Make a compound type from non-empty list of types
  2115      * @param bounds            the types from which the compound type is formed
  2116      * @param supertype         is objectType if all bounds are interfaces,
  2117      *                          null otherwise.
  2118      */
  2119     public Type makeCompoundType(List<Type> bounds) {
  2120         return makeCompoundType(bounds, bounds.head.tsym.isInterface());
  2122     public Type makeCompoundType(List<Type> bounds, boolean allInterfaces) {
  2123         Assert.check(bounds.nonEmpty());
  2124         Type firstExplicitBound = bounds.head;
  2125         if (allInterfaces) {
  2126             bounds = bounds.prepend(syms.objectType);
  2128         ClassSymbol bc =
  2129             new ClassSymbol(ABSTRACT|PUBLIC|SYNTHETIC|COMPOUND|ACYCLIC,
  2130                             Type.moreInfo
  2131                                 ? names.fromString(bounds.toString())
  2132                                 : names.empty,
  2133                             null,
  2134                             syms.noSymbol);
  2135         bc.type = new IntersectionClassType(bounds, bc, allInterfaces);
  2136         bc.erasure_field = (bounds.head.tag == TYPEVAR) ?
  2137                 syms.objectType : // error condition, recover
  2138                 erasure(firstExplicitBound);
  2139         bc.members_field = new Scope(bc);
  2140         return bc.type;
  2143     /**
  2144      * A convenience wrapper for {@link #makeCompoundType(List)}; the
  2145      * arguments are converted to a list and passed to the other
  2146      * method.  Note that this might cause a symbol completion.
  2147      * Hence, this version of makeCompoundType may not be called
  2148      * during a classfile read.
  2149      */
  2150     public Type makeCompoundType(Type bound1, Type bound2) {
  2151         return makeCompoundType(List.of(bound1, bound2));
  2153     // </editor-fold>
  2155     // <editor-fold defaultstate="collapsed" desc="supertype">
  2156     public Type supertype(Type t) {
  2157         return supertype.visit(t);
  2159     // where
  2160         private UnaryVisitor<Type> supertype = new UnaryVisitor<Type>() {
  2162             public Type visitType(Type t, Void ignored) {
  2163                 // A note on wildcards: there is no good way to
  2164                 // determine a supertype for a super bounded wildcard.
  2165                 return null;
  2168             @Override
  2169             public Type visitClassType(ClassType t, Void ignored) {
  2170                 if (t.supertype_field == null) {
  2171                     Type supertype = ((ClassSymbol)t.tsym).getSuperclass();
  2172                     // An interface has no superclass; its supertype is Object.
  2173                     if (t.isInterface())
  2174                         supertype = ((ClassType)t.tsym.type).supertype_field;
  2175                     if (t.supertype_field == null) {
  2176                         List<Type> actuals = classBound(t).allparams();
  2177                         List<Type> formals = t.tsym.type.allparams();
  2178                         if (t.hasErasedSupertypes()) {
  2179                             t.supertype_field = erasureRecursive(supertype);
  2180                         } else if (formals.nonEmpty()) {
  2181                             t.supertype_field = subst(supertype, formals, actuals);
  2183                         else {
  2184                             t.supertype_field = supertype;
  2188                 return t.supertype_field;
  2191             /**
  2192              * The supertype is always a class type. If the type
  2193              * variable's bounds start with a class type, this is also
  2194              * the supertype.  Otherwise, the supertype is
  2195              * java.lang.Object.
  2196              */
  2197             @Override
  2198             public Type visitTypeVar(TypeVar t, Void ignored) {
  2199                 if (t.bound.tag == TYPEVAR ||
  2200                     (!t.bound.isCompound() && !t.bound.isInterface())) {
  2201                     return t.bound;
  2202                 } else {
  2203                     return supertype(t.bound);
  2207             @Override
  2208             public Type visitArrayType(ArrayType t, Void ignored) {
  2209                 if (t.elemtype.isPrimitive() || isSameType(t.elemtype, syms.objectType))
  2210                     return arraySuperType();
  2211                 else
  2212                     return new ArrayType(supertype(t.elemtype), t.tsym);
  2215             @Override
  2216             public Type visitErrorType(ErrorType t, Void ignored) {
  2217                 return t;
  2219         };
  2220     // </editor-fold>
  2222     // <editor-fold defaultstate="collapsed" desc="interfaces">
  2223     /**
  2224      * Return the interfaces implemented by this class.
  2225      */
  2226     public List<Type> interfaces(Type t) {
  2227         return interfaces.visit(t);
  2229     // where
  2230         private UnaryVisitor<List<Type>> interfaces = new UnaryVisitor<List<Type>>() {
  2232             public List<Type> visitType(Type t, Void ignored) {
  2233                 return List.nil();
  2236             @Override
  2237             public List<Type> visitClassType(ClassType t, Void ignored) {
  2238                 if (t.interfaces_field == null) {
  2239                     List<Type> interfaces = ((ClassSymbol)t.tsym).getInterfaces();
  2240                     if (t.interfaces_field == null) {
  2241                         // If t.interfaces_field is null, then t must
  2242                         // be a parameterized type (not to be confused
  2243                         // with a generic type declaration).
  2244                         // Terminology:
  2245                         //    Parameterized type: List<String>
  2246                         //    Generic type declaration: class List<E> { ... }
  2247                         // So t corresponds to List<String> and
  2248                         // t.tsym.type corresponds to List<E>.
  2249                         // The reason t must be parameterized type is
  2250                         // that completion will happen as a side
  2251                         // effect of calling
  2252                         // ClassSymbol.getInterfaces.  Since
  2253                         // t.interfaces_field is null after
  2254                         // completion, we can assume that t is not the
  2255                         // type of a class/interface declaration.
  2256                         Assert.check(t != t.tsym.type, t);
  2257                         List<Type> actuals = t.allparams();
  2258                         List<Type> formals = t.tsym.type.allparams();
  2259                         if (t.hasErasedSupertypes()) {
  2260                             t.interfaces_field = erasureRecursive(interfaces);
  2261                         } else if (formals.nonEmpty()) {
  2262                             t.interfaces_field =
  2263                                 upperBounds(subst(interfaces, formals, actuals));
  2265                         else {
  2266                             t.interfaces_field = interfaces;
  2270                 return t.interfaces_field;
  2273             @Override
  2274             public List<Type> visitTypeVar(TypeVar t, Void ignored) {
  2275                 if (t.bound.isCompound())
  2276                     return interfaces(t.bound);
  2278                 if (t.bound.isInterface())
  2279                     return List.of(t.bound);
  2281                 return List.nil();
  2283         };
  2285     public boolean isDirectSuperInterface(TypeSymbol isym, TypeSymbol origin) {
  2286         for (Type i2 : interfaces(origin.type)) {
  2287             if (isym == i2.tsym) return true;
  2289         return false;
  2291     // </editor-fold>
  2293     // <editor-fold defaultstate="collapsed" desc="isDerivedRaw">
  2294     Map<Type,Boolean> isDerivedRawCache = new HashMap<Type,Boolean>();
  2296     public boolean isDerivedRaw(Type t) {
  2297         Boolean result = isDerivedRawCache.get(t);
  2298         if (result == null) {
  2299             result = isDerivedRawInternal(t);
  2300             isDerivedRawCache.put(t, result);
  2302         return result;
  2305     public boolean isDerivedRawInternal(Type t) {
  2306         if (t.isErroneous())
  2307             return false;
  2308         return
  2309             t.isRaw() ||
  2310             supertype(t) != null && isDerivedRaw(supertype(t)) ||
  2311             isDerivedRaw(interfaces(t));
  2314     public boolean isDerivedRaw(List<Type> ts) {
  2315         List<Type> l = ts;
  2316         while (l.nonEmpty() && !isDerivedRaw(l.head)) l = l.tail;
  2317         return l.nonEmpty();
  2319     // </editor-fold>
  2321     // <editor-fold defaultstate="collapsed" desc="setBounds">
  2322     /**
  2323      * Set the bounds field of the given type variable to reflect a
  2324      * (possibly multiple) list of bounds.
  2325      * @param t                 a type variable
  2326      * @param bounds            the bounds, must be nonempty
  2327      * @param supertype         is objectType if all bounds are interfaces,
  2328      *                          null otherwise.
  2329      */
  2330     public void setBounds(TypeVar t, List<Type> bounds) {
  2331         setBounds(t, bounds, bounds.head.tsym.isInterface());
  2334     /**
  2335      * Same as {@link #setBounds(Type.TypeVar,List,Type)}, except that
  2336      * third parameter is computed directly, as follows: if all
  2337      * all bounds are interface types, the computed supertype is Object,
  2338      * otherwise the supertype is simply left null (in this case, the supertype
  2339      * is assumed to be the head of the bound list passed as second argument).
  2340      * Note that this check might cause a symbol completion. Hence, this version of
  2341      * setBounds may not be called during a classfile read.
  2342      */
  2343     public void setBounds(TypeVar t, List<Type> bounds, boolean allInterfaces) {
  2344         t.bound = bounds.tail.isEmpty() ?
  2345                 bounds.head :
  2346                 makeCompoundType(bounds, allInterfaces);
  2347         t.rank_field = -1;
  2349     // </editor-fold>
  2351     // <editor-fold defaultstate="collapsed" desc="getBounds">
  2352     /**
  2353      * Return list of bounds of the given type variable.
  2354      */
  2355     public List<Type> getBounds(TypeVar t) {
  2356         if (t.bound.hasTag(NONE))
  2357             return List.nil();
  2358         else if (t.bound.isErroneous() || !t.bound.isCompound())
  2359             return List.of(t.bound);
  2360         else if ((erasure(t).tsym.flags() & INTERFACE) == 0)
  2361             return interfaces(t).prepend(supertype(t));
  2362         else
  2363             // No superclass was given in bounds.
  2364             // In this case, supertype is Object, erasure is first interface.
  2365             return interfaces(t);
  2367     // </editor-fold>
  2369     // <editor-fold defaultstate="collapsed" desc="classBound">
  2370     /**
  2371      * If the given type is a (possibly selected) type variable,
  2372      * return the bounding class of this type, otherwise return the
  2373      * type itself.
  2374      */
  2375     public Type classBound(Type t) {
  2376         return classBound.visit(t);
  2378     // where
  2379         private UnaryVisitor<Type> classBound = new UnaryVisitor<Type>() {
  2381             public Type visitType(Type t, Void ignored) {
  2382                 return t;
  2385             @Override
  2386             public Type visitClassType(ClassType t, Void ignored) {
  2387                 Type outer1 = classBound(t.getEnclosingType());
  2388                 if (outer1 != t.getEnclosingType())
  2389                     return new ClassType(outer1, t.getTypeArguments(), t.tsym);
  2390                 else
  2391                     return t;
  2394             @Override
  2395             public Type visitTypeVar(TypeVar t, Void ignored) {
  2396                 return classBound(supertype(t));
  2399             @Override
  2400             public Type visitErrorType(ErrorType t, Void ignored) {
  2401                 return t;
  2403         };
  2404     // </editor-fold>
  2406     // <editor-fold defaultstate="collapsed" desc="sub signature / override equivalence">
  2407     /**
  2408      * Returns true iff the first signature is a <em>sub
  2409      * signature</em> of the other.  This is <b>not</b> an equivalence
  2410      * relation.
  2412      * @jls section 8.4.2.
  2413      * @see #overrideEquivalent(Type t, Type s)
  2414      * @param t first signature (possibly raw).
  2415      * @param s second signature (could be subjected to erasure).
  2416      * @return true if t is a sub signature of s.
  2417      */
  2418     public boolean isSubSignature(Type t, Type s) {
  2419         return isSubSignature(t, s, true);
  2422     public boolean isSubSignature(Type t, Type s, boolean strict) {
  2423         return hasSameArgs(t, s, strict) || hasSameArgs(t, erasure(s), strict);
  2426     /**
  2427      * Returns true iff these signatures are related by <em>override
  2428      * equivalence</em>.  This is the natural extension of
  2429      * isSubSignature to an equivalence relation.
  2431      * @jls section 8.4.2.
  2432      * @see #isSubSignature(Type t, Type s)
  2433      * @param t a signature (possible raw, could be subjected to
  2434      * erasure).
  2435      * @param s a signature (possible raw, could be subjected to
  2436      * erasure).
  2437      * @return true if either argument is a sub signature of the other.
  2438      */
  2439     public boolean overrideEquivalent(Type t, Type s) {
  2440         return hasSameArgs(t, s) ||
  2441             hasSameArgs(t, erasure(s)) || hasSameArgs(erasure(t), s);
  2444     public boolean overridesObjectMethod(TypeSymbol origin, Symbol msym) {
  2445         for (Scope.Entry e = syms.objectType.tsym.members().lookup(msym.name) ; e.scope != null ; e = e.next()) {
  2446             if (msym.overrides(e.sym, origin, Types.this, true)) {
  2447                 return true;
  2450         return false;
  2453     // <editor-fold defaultstate="collapsed" desc="Determining method implementation in given site">
  2454     class ImplementationCache {
  2456         private WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>> _map =
  2457                 new WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>>();
  2459         class Entry {
  2460             final MethodSymbol cachedImpl;
  2461             final Filter<Symbol> implFilter;
  2462             final boolean checkResult;
  2463             final int prevMark;
  2465             public Entry(MethodSymbol cachedImpl,
  2466                     Filter<Symbol> scopeFilter,
  2467                     boolean checkResult,
  2468                     int prevMark) {
  2469                 this.cachedImpl = cachedImpl;
  2470                 this.implFilter = scopeFilter;
  2471                 this.checkResult = checkResult;
  2472                 this.prevMark = prevMark;
  2475             boolean matches(Filter<Symbol> scopeFilter, boolean checkResult, int mark) {
  2476                 return this.implFilter == scopeFilter &&
  2477                         this.checkResult == checkResult &&
  2478                         this.prevMark == mark;
  2482         MethodSymbol get(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
  2483             SoftReference<Map<TypeSymbol, Entry>> ref_cache = _map.get(ms);
  2484             Map<TypeSymbol, Entry> cache = ref_cache != null ? ref_cache.get() : null;
  2485             if (cache == null) {
  2486                 cache = new HashMap<TypeSymbol, Entry>();
  2487                 _map.put(ms, new SoftReference<Map<TypeSymbol, Entry>>(cache));
  2489             Entry e = cache.get(origin);
  2490             CompoundScope members = membersClosure(origin.type, true);
  2491             if (e == null ||
  2492                     !e.matches(implFilter, checkResult, members.getMark())) {
  2493                 MethodSymbol impl = implementationInternal(ms, origin, checkResult, implFilter);
  2494                 cache.put(origin, new Entry(impl, implFilter, checkResult, members.getMark()));
  2495                 return impl;
  2497             else {
  2498                 return e.cachedImpl;
  2502         private MethodSymbol implementationInternal(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
  2503             for (Type t = origin.type; t.tag == CLASS || t.tag == TYPEVAR; t = supertype(t)) {
  2504                 while (t.tag == TYPEVAR)
  2505                     t = t.getUpperBound();
  2506                 TypeSymbol c = t.tsym;
  2507                 for (Scope.Entry e = c.members().lookup(ms.name, implFilter);
  2508                      e.scope != null;
  2509                      e = e.next(implFilter)) {
  2510                     if (e.sym != null &&
  2511                              e.sym.overrides(ms, origin, Types.this, checkResult))
  2512                         return (MethodSymbol)e.sym;
  2515             return null;
  2519     private ImplementationCache implCache = new ImplementationCache();
  2521     public MethodSymbol implementation(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
  2522         return implCache.get(ms, origin, checkResult, implFilter);
  2524     // </editor-fold>
  2526     // <editor-fold defaultstate="collapsed" desc="compute transitive closure of all members in given site">
  2527     class MembersClosureCache extends SimpleVisitor<CompoundScope, Boolean> {
  2529         private WeakHashMap<TypeSymbol, Entry> _map =
  2530                 new WeakHashMap<TypeSymbol, Entry>();
  2532         class Entry {
  2533             final boolean skipInterfaces;
  2534             final CompoundScope compoundScope;
  2536             public Entry(boolean skipInterfaces, CompoundScope compoundScope) {
  2537                 this.skipInterfaces = skipInterfaces;
  2538                 this.compoundScope = compoundScope;
  2541             boolean matches(boolean skipInterfaces) {
  2542                 return this.skipInterfaces == skipInterfaces;
  2546         List<TypeSymbol> seenTypes = List.nil();
  2548         /** members closure visitor methods **/
  2550         public CompoundScope visitType(Type t, Boolean skipInterface) {
  2551             return null;
  2554         @Override
  2555         public CompoundScope visitClassType(ClassType t, Boolean skipInterface) {
  2556             if (seenTypes.contains(t.tsym)) {
  2557                 //this is possible when an interface is implemented in multiple
  2558                 //superclasses, or when a classs hierarchy is circular - in such
  2559                 //cases we don't need to recurse (empty scope is returned)
  2560                 return new CompoundScope(t.tsym);
  2562             try {
  2563                 seenTypes = seenTypes.prepend(t.tsym);
  2564                 ClassSymbol csym = (ClassSymbol)t.tsym;
  2565                 Entry e = _map.get(csym);
  2566                 if (e == null || !e.matches(skipInterface)) {
  2567                     CompoundScope membersClosure = new CompoundScope(csym);
  2568                     if (!skipInterface) {
  2569                         for (Type i : interfaces(t)) {
  2570                             membersClosure.addSubScope(visit(i, skipInterface));
  2573                     membersClosure.addSubScope(visit(supertype(t), skipInterface));
  2574                     membersClosure.addSubScope(csym.members());
  2575                     e = new Entry(skipInterface, membersClosure);
  2576                     _map.put(csym, e);
  2578                 return e.compoundScope;
  2580             finally {
  2581                 seenTypes = seenTypes.tail;
  2585         @Override
  2586         public CompoundScope visitTypeVar(TypeVar t, Boolean skipInterface) {
  2587             return visit(t.getUpperBound(), skipInterface);
  2591     private MembersClosureCache membersCache = new MembersClosureCache();
  2593     public CompoundScope membersClosure(Type site, boolean skipInterface) {
  2594         return membersCache.visit(site, skipInterface);
  2596     // </editor-fold>
  2599     //where
  2600     public List<MethodSymbol> interfaceCandidates(Type site, MethodSymbol ms) {
  2601         Filter<Symbol> filter = new MethodFilter(ms, site);
  2602         List<MethodSymbol> candidates = List.nil();
  2603         for (Symbol s : membersClosure(site, false).getElements(filter)) {
  2604             if (!site.tsym.isInterface() && !s.owner.isInterface()) {
  2605                 return List.of((MethodSymbol)s);
  2606             } else if (!candidates.contains(s)) {
  2607                 candidates = candidates.prepend((MethodSymbol)s);
  2610         return prune(candidates);
  2613     public List<MethodSymbol> prune(List<MethodSymbol> methods) {
  2614         ListBuffer<MethodSymbol> methodsMin = ListBuffer.lb();
  2615         for (MethodSymbol m1 : methods) {
  2616             boolean isMin_m1 = true;
  2617             for (MethodSymbol m2 : methods) {
  2618                 if (m1 == m2) continue;
  2619                 if (m2.owner != m1.owner &&
  2620                         asSuper(m2.owner.type, m1.owner) != null) {
  2621                     isMin_m1 = false;
  2622                     break;
  2625             if (isMin_m1)
  2626                 methodsMin.append(m1);
  2628         return methodsMin.toList();
  2630     // where
  2631             private class MethodFilter implements Filter<Symbol> {
  2633                 Symbol msym;
  2634                 Type site;
  2636                 MethodFilter(Symbol msym, Type site) {
  2637                     this.msym = msym;
  2638                     this.site = site;
  2641                 public boolean accepts(Symbol s) {
  2642                     return s.kind == Kinds.MTH &&
  2643                             s.name == msym.name &&
  2644                             s.isInheritedIn(site.tsym, Types.this) &&
  2645                             overrideEquivalent(memberType(site, s), memberType(site, msym));
  2647             };
  2648     // </editor-fold>
  2650     /**
  2651      * Does t have the same arguments as s?  It is assumed that both
  2652      * types are (possibly polymorphic) method types.  Monomorphic
  2653      * method types "have the same arguments", if their argument lists
  2654      * are equal.  Polymorphic method types "have the same arguments",
  2655      * if they have the same arguments after renaming all type
  2656      * variables of one to corresponding type variables in the other,
  2657      * where correspondence is by position in the type parameter list.
  2658      */
  2659     public boolean hasSameArgs(Type t, Type s) {
  2660         return hasSameArgs(t, s, true);
  2663     public boolean hasSameArgs(Type t, Type s, boolean strict) {
  2664         return hasSameArgs(t, s, strict ? hasSameArgs_strict : hasSameArgs_nonstrict);
  2667     private boolean hasSameArgs(Type t, Type s, TypeRelation hasSameArgs) {
  2668         return hasSameArgs.visit(t, s);
  2670     // where
  2671         private class HasSameArgs extends TypeRelation {
  2673             boolean strict;
  2675             public HasSameArgs(boolean strict) {
  2676                 this.strict = strict;
  2679             public Boolean visitType(Type t, Type s) {
  2680                 throw new AssertionError();
  2683             @Override
  2684             public Boolean visitMethodType(MethodType t, Type s) {
  2685                 return s.tag == METHOD
  2686                     && containsTypeEquivalent(t.argtypes, s.getParameterTypes());
  2689             @Override
  2690             public Boolean visitForAll(ForAll t, Type s) {
  2691                 if (s.tag != FORALL)
  2692                     return strict ? false : visitMethodType(t.asMethodType(), s);
  2694                 ForAll forAll = (ForAll)s;
  2695                 return hasSameBounds(t, forAll)
  2696                     && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
  2699             @Override
  2700             public Boolean visitErrorType(ErrorType t, Type s) {
  2701                 return false;
  2703         };
  2705         TypeRelation hasSameArgs_strict = new HasSameArgs(true);
  2706         TypeRelation hasSameArgs_nonstrict = new HasSameArgs(false);
  2708     // </editor-fold>
  2710     // <editor-fold defaultstate="collapsed" desc="subst">
  2711     public List<Type> subst(List<Type> ts,
  2712                             List<Type> from,
  2713                             List<Type> to) {
  2714         return new Subst(from, to).subst(ts);
  2717     /**
  2718      * Substitute all occurrences of a type in `from' with the
  2719      * corresponding type in `to' in 't'. Match lists `from' and `to'
  2720      * from the right: If lists have different length, discard leading
  2721      * elements of the longer list.
  2722      */
  2723     public Type subst(Type t, List<Type> from, List<Type> to) {
  2724         return new Subst(from, to).subst(t);
  2727     private class Subst extends UnaryVisitor<Type> {
  2728         List<Type> from;
  2729         List<Type> to;
  2731         public Subst(List<Type> from, List<Type> to) {
  2732             int fromLength = from.length();
  2733             int toLength = to.length();
  2734             while (fromLength > toLength) {
  2735                 fromLength--;
  2736                 from = from.tail;
  2738             while (fromLength < toLength) {
  2739                 toLength--;
  2740                 to = to.tail;
  2742             this.from = from;
  2743             this.to = to;
  2746         Type subst(Type t) {
  2747             if (from.tail == null)
  2748                 return t;
  2749             else
  2750                 return visit(t);
  2753         List<Type> subst(List<Type> ts) {
  2754             if (from.tail == null)
  2755                 return ts;
  2756             boolean wild = false;
  2757             if (ts.nonEmpty() && from.nonEmpty()) {
  2758                 Type head1 = subst(ts.head);
  2759                 List<Type> tail1 = subst(ts.tail);
  2760                 if (head1 != ts.head || tail1 != ts.tail)
  2761                     return tail1.prepend(head1);
  2763             return ts;
  2766         public Type visitType(Type t, Void ignored) {
  2767             return t;
  2770         @Override
  2771         public Type visitMethodType(MethodType t, Void ignored) {
  2772             List<Type> argtypes = subst(t.argtypes);
  2773             Type restype = subst(t.restype);
  2774             List<Type> thrown = subst(t.thrown);
  2775             if (argtypes == t.argtypes &&
  2776                 restype == t.restype &&
  2777                 thrown == t.thrown)
  2778                 return t;
  2779             else
  2780                 return new MethodType(argtypes, restype, thrown, t.tsym);
  2783         @Override
  2784         public Type visitTypeVar(TypeVar t, Void ignored) {
  2785             for (List<Type> from = this.from, to = this.to;
  2786                  from.nonEmpty();
  2787                  from = from.tail, to = to.tail) {
  2788                 if (t == from.head) {
  2789                     return to.head.withTypeVar(t);
  2792             return t;
  2795         @Override
  2796         public Type visitClassType(ClassType t, Void ignored) {
  2797             if (!t.isCompound()) {
  2798                 List<Type> typarams = t.getTypeArguments();
  2799                 List<Type> typarams1 = subst(typarams);
  2800                 Type outer = t.getEnclosingType();
  2801                 Type outer1 = subst(outer);
  2802                 if (typarams1 == typarams && outer1 == outer)
  2803                     return t;
  2804                 else
  2805                     return new ClassType(outer1, typarams1, t.tsym);
  2806             } else {
  2807                 Type st = subst(supertype(t));
  2808                 List<Type> is = upperBounds(subst(interfaces(t)));
  2809                 if (st == supertype(t) && is == interfaces(t))
  2810                     return t;
  2811                 else
  2812                     return makeCompoundType(is.prepend(st));
  2816         @Override
  2817         public Type visitWildcardType(WildcardType t, Void ignored) {
  2818             Type bound = t.type;
  2819             if (t.kind != BoundKind.UNBOUND)
  2820                 bound = subst(bound);
  2821             if (bound == t.type) {
  2822                 return t;
  2823             } else {
  2824                 if (t.isExtendsBound() && bound.isExtendsBound())
  2825                     bound = upperBound(bound);
  2826                 return new WildcardType(bound, t.kind, syms.boundClass, t.bound);
  2830         @Override
  2831         public Type visitArrayType(ArrayType t, Void ignored) {
  2832             Type elemtype = subst(t.elemtype);
  2833             if (elemtype == t.elemtype)
  2834                 return t;
  2835             else
  2836                 return new ArrayType(upperBound(elemtype), t.tsym);
  2839         @Override
  2840         public Type visitForAll(ForAll t, Void ignored) {
  2841             if (Type.containsAny(to, t.tvars)) {
  2842                 //perform alpha-renaming of free-variables in 't'
  2843                 //if 'to' types contain variables that are free in 't'
  2844                 List<Type> freevars = newInstances(t.tvars);
  2845                 t = new ForAll(freevars,
  2846                         Types.this.subst(t.qtype, t.tvars, freevars));
  2848             List<Type> tvars1 = substBounds(t.tvars, from, to);
  2849             Type qtype1 = subst(t.qtype);
  2850             if (tvars1 == t.tvars && qtype1 == t.qtype) {
  2851                 return t;
  2852             } else if (tvars1 == t.tvars) {
  2853                 return new ForAll(tvars1, qtype1);
  2854             } else {
  2855                 return new ForAll(tvars1, Types.this.subst(qtype1, t.tvars, tvars1));
  2859         @Override
  2860         public Type visitErrorType(ErrorType t, Void ignored) {
  2861             return t;
  2865     public List<Type> substBounds(List<Type> tvars,
  2866                                   List<Type> from,
  2867                                   List<Type> to) {
  2868         if (tvars.isEmpty())
  2869             return tvars;
  2870         ListBuffer<Type> newBoundsBuf = lb();
  2871         boolean changed = false;
  2872         // calculate new bounds
  2873         for (Type t : tvars) {
  2874             TypeVar tv = (TypeVar) t;
  2875             Type bound = subst(tv.bound, from, to);
  2876             if (bound != tv.bound)
  2877                 changed = true;
  2878             newBoundsBuf.append(bound);
  2880         if (!changed)
  2881             return tvars;
  2882         ListBuffer<Type> newTvars = lb();
  2883         // create new type variables without bounds
  2884         for (Type t : tvars) {
  2885             newTvars.append(new TypeVar(t.tsym, null, syms.botType));
  2887         // the new bounds should use the new type variables in place
  2888         // of the old
  2889         List<Type> newBounds = newBoundsBuf.toList();
  2890         from = tvars;
  2891         to = newTvars.toList();
  2892         for (; !newBounds.isEmpty(); newBounds = newBounds.tail) {
  2893             newBounds.head = subst(newBounds.head, from, to);
  2895         newBounds = newBoundsBuf.toList();
  2896         // set the bounds of new type variables to the new bounds
  2897         for (Type t : newTvars.toList()) {
  2898             TypeVar tv = (TypeVar) t;
  2899             tv.bound = newBounds.head;
  2900             newBounds = newBounds.tail;
  2902         return newTvars.toList();
  2905     public TypeVar substBound(TypeVar t, List<Type> from, List<Type> to) {
  2906         Type bound1 = subst(t.bound, from, to);
  2907         if (bound1 == t.bound)
  2908             return t;
  2909         else {
  2910             // create new type variable without bounds
  2911             TypeVar tv = new TypeVar(t.tsym, null, syms.botType);
  2912             // the new bound should use the new type variable in place
  2913             // of the old
  2914             tv.bound = subst(bound1, List.<Type>of(t), List.<Type>of(tv));
  2915             return tv;
  2918     // </editor-fold>
  2920     // <editor-fold defaultstate="collapsed" desc="hasSameBounds">
  2921     /**
  2922      * Does t have the same bounds for quantified variables as s?
  2923      */
  2924     boolean hasSameBounds(ForAll t, ForAll s) {
  2925         List<Type> l1 = t.tvars;
  2926         List<Type> l2 = s.tvars;
  2927         while (l1.nonEmpty() && l2.nonEmpty() &&
  2928                isSameType(l1.head.getUpperBound(),
  2929                           subst(l2.head.getUpperBound(),
  2930                                 s.tvars,
  2931                                 t.tvars))) {
  2932             l1 = l1.tail;
  2933             l2 = l2.tail;
  2935         return l1.isEmpty() && l2.isEmpty();
  2937     // </editor-fold>
  2939     // <editor-fold defaultstate="collapsed" desc="newInstances">
  2940     /** Create new vector of type variables from list of variables
  2941      *  changing all recursive bounds from old to new list.
  2942      */
  2943     public List<Type> newInstances(List<Type> tvars) {
  2944         List<Type> tvars1 = Type.map(tvars, newInstanceFun);
  2945         for (List<Type> l = tvars1; l.nonEmpty(); l = l.tail) {
  2946             TypeVar tv = (TypeVar) l.head;
  2947             tv.bound = subst(tv.bound, tvars, tvars1);
  2949         return tvars1;
  2951     private static final Mapping newInstanceFun = new Mapping("newInstanceFun") {
  2952             public Type apply(Type t) { return new TypeVar(t.tsym, t.getUpperBound(), t.getLowerBound()); }
  2953         };
  2954     // </editor-fold>
  2956     public Type createMethodTypeWithParameters(Type original, List<Type> newParams) {
  2957         return original.accept(methodWithParameters, newParams);
  2959     // where
  2960         private final MapVisitor<List<Type>> methodWithParameters = new MapVisitor<List<Type>>() {
  2961             public Type visitType(Type t, List<Type> newParams) {
  2962                 throw new IllegalArgumentException("Not a method type: " + t);
  2964             public Type visitMethodType(MethodType t, List<Type> newParams) {
  2965                 return new MethodType(newParams, t.restype, t.thrown, t.tsym);
  2967             public Type visitForAll(ForAll t, List<Type> newParams) {
  2968                 return new ForAll(t.tvars, t.qtype.accept(this, newParams));
  2970         };
  2972     public Type createMethodTypeWithThrown(Type original, List<Type> newThrown) {
  2973         return original.accept(methodWithThrown, newThrown);
  2975     // where
  2976         private final MapVisitor<List<Type>> methodWithThrown = new MapVisitor<List<Type>>() {
  2977             public Type visitType(Type t, List<Type> newThrown) {
  2978                 throw new IllegalArgumentException("Not a method type: " + t);
  2980             public Type visitMethodType(MethodType t, List<Type> newThrown) {
  2981                 return new MethodType(t.argtypes, t.restype, newThrown, t.tsym);
  2983             public Type visitForAll(ForAll t, List<Type> newThrown) {
  2984                 return new ForAll(t.tvars, t.qtype.accept(this, newThrown));
  2986         };
  2988     public Type createMethodTypeWithReturn(Type original, Type newReturn) {
  2989         return original.accept(methodWithReturn, newReturn);
  2991     // where
  2992         private final MapVisitor<Type> methodWithReturn = new MapVisitor<Type>() {
  2993             public Type visitType(Type t, Type newReturn) {
  2994                 throw new IllegalArgumentException("Not a method type: " + t);
  2996             public Type visitMethodType(MethodType t, Type newReturn) {
  2997                 return new MethodType(t.argtypes, newReturn, t.thrown, t.tsym);
  2999             public Type visitForAll(ForAll t, Type newReturn) {
  3000                 return new ForAll(t.tvars, t.qtype.accept(this, newReturn));
  3002         };
  3004     // <editor-fold defaultstate="collapsed" desc="createErrorType">
  3005     public Type createErrorType(Type originalType) {
  3006         return new ErrorType(originalType, syms.errSymbol);
  3009     public Type createErrorType(ClassSymbol c, Type originalType) {
  3010         return new ErrorType(c, originalType);
  3013     public Type createErrorType(Name name, TypeSymbol container, Type originalType) {
  3014         return new ErrorType(name, container, originalType);
  3016     // </editor-fold>
  3018     // <editor-fold defaultstate="collapsed" desc="rank">
  3019     /**
  3020      * The rank of a class is the length of the longest path between
  3021      * the class and java.lang.Object in the class inheritance
  3022      * graph. Undefined for all but reference types.
  3023      */
  3024     public int rank(Type t) {
  3025         t = t.unannotatedType();
  3026         switch(t.tag) {
  3027         case CLASS: {
  3028             ClassType cls = (ClassType)t;
  3029             if (cls.rank_field < 0) {
  3030                 Name fullname = cls.tsym.getQualifiedName();
  3031                 if (fullname == names.java_lang_Object)
  3032                     cls.rank_field = 0;
  3033                 else {
  3034                     int r = rank(supertype(cls));
  3035                     for (List<Type> l = interfaces(cls);
  3036                          l.nonEmpty();
  3037                          l = l.tail) {
  3038                         if (rank(l.head) > r)
  3039                             r = rank(l.head);
  3041                     cls.rank_field = r + 1;
  3044             return cls.rank_field;
  3046         case TYPEVAR: {
  3047             TypeVar tvar = (TypeVar)t;
  3048             if (tvar.rank_field < 0) {
  3049                 int r = rank(supertype(tvar));
  3050                 for (List<Type> l = interfaces(tvar);
  3051                      l.nonEmpty();
  3052                      l = l.tail) {
  3053                     if (rank(l.head) > r) r = rank(l.head);
  3055                 tvar.rank_field = r + 1;
  3057             return tvar.rank_field;
  3059         case ERROR:
  3060             return 0;
  3061         default:
  3062             throw new AssertionError();
  3065     // </editor-fold>
  3067     /**
  3068      * Helper method for generating a string representation of a given type
  3069      * accordingly to a given locale
  3070      */
  3071     public String toString(Type t, Locale locale) {
  3072         return Printer.createStandardPrinter(messages).visit(t, locale);
  3075     /**
  3076      * Helper method for generating a string representation of a given type
  3077      * accordingly to a given locale
  3078      */
  3079     public String toString(Symbol t, Locale locale) {
  3080         return Printer.createStandardPrinter(messages).visit(t, locale);
  3083     // <editor-fold defaultstate="collapsed" desc="toString">
  3084     /**
  3085      * This toString is slightly more descriptive than the one on Type.
  3087      * @deprecated Types.toString(Type t, Locale l) provides better support
  3088      * for localization
  3089      */
  3090     @Deprecated
  3091     public String toString(Type t) {
  3092         if (t.tag == FORALL) {
  3093             ForAll forAll = (ForAll)t;
  3094             return typaramsString(forAll.tvars) + forAll.qtype;
  3096         return "" + t;
  3098     // where
  3099         private String typaramsString(List<Type> tvars) {
  3100             StringBuilder s = new StringBuilder();
  3101             s.append('<');
  3102             boolean first = true;
  3103             for (Type t : tvars) {
  3104                 if (!first) s.append(", ");
  3105                 first = false;
  3106                 appendTyparamString(((TypeVar)t), s);
  3108             s.append('>');
  3109             return s.toString();
  3111         private void appendTyparamString(TypeVar t, StringBuilder buf) {
  3112             buf.append(t);
  3113             if (t.bound == null ||
  3114                 t.bound.tsym.getQualifiedName() == names.java_lang_Object)
  3115                 return;
  3116             buf.append(" extends "); // Java syntax; no need for i18n
  3117             Type bound = t.bound;
  3118             if (!bound.isCompound()) {
  3119                 buf.append(bound);
  3120             } else if ((erasure(t).tsym.flags() & INTERFACE) == 0) {
  3121                 buf.append(supertype(t));
  3122                 for (Type intf : interfaces(t)) {
  3123                     buf.append('&');
  3124                     buf.append(intf);
  3126             } else {
  3127                 // No superclass was given in bounds.
  3128                 // In this case, supertype is Object, erasure is first interface.
  3129                 boolean first = true;
  3130                 for (Type intf : interfaces(t)) {
  3131                     if (!first) buf.append('&');
  3132                     first = false;
  3133                     buf.append(intf);
  3137     // </editor-fold>
  3139     // <editor-fold defaultstate="collapsed" desc="Determining least upper bounds of types">
  3140     /**
  3141      * A cache for closures.
  3143      * <p>A closure is a list of all the supertypes and interfaces of
  3144      * a class or interface type, ordered by ClassSymbol.precedes
  3145      * (that is, subclasses come first, arbitrary but fixed
  3146      * otherwise).
  3147      */
  3148     private Map<Type,List<Type>> closureCache = new HashMap<Type,List<Type>>();
  3150     /**
  3151      * Returns the closure of a class or interface type.
  3152      */
  3153     public List<Type> closure(Type t) {
  3154         List<Type> cl = closureCache.get(t);
  3155         if (cl == null) {
  3156             Type st = supertype(t);
  3157             if (!t.isCompound()) {
  3158                 if (st.tag == CLASS) {
  3159                     cl = insert(closure(st), t);
  3160                 } else if (st.tag == TYPEVAR) {
  3161                     cl = closure(st).prepend(t);
  3162                 } else {
  3163                     cl = List.of(t);
  3165             } else {
  3166                 cl = closure(supertype(t));
  3168             for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail)
  3169                 cl = union(cl, closure(l.head));
  3170             closureCache.put(t, cl);
  3172         return cl;
  3175     /**
  3176      * Insert a type in a closure
  3177      */
  3178     public List<Type> insert(List<Type> cl, Type t) {
  3179         if (cl.isEmpty() || t.tsym.precedes(cl.head.tsym, this)) {
  3180             return cl.prepend(t);
  3181         } else if (cl.head.tsym.precedes(t.tsym, this)) {
  3182             return insert(cl.tail, t).prepend(cl.head);
  3183         } else {
  3184             return cl;
  3188     /**
  3189      * Form the union of two closures
  3190      */
  3191     public List<Type> union(List<Type> cl1, List<Type> cl2) {
  3192         if (cl1.isEmpty()) {
  3193             return cl2;
  3194         } else if (cl2.isEmpty()) {
  3195             return cl1;
  3196         } else if (cl1.head.tsym.precedes(cl2.head.tsym, this)) {
  3197             return union(cl1.tail, cl2).prepend(cl1.head);
  3198         } else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) {
  3199             return union(cl1, cl2.tail).prepend(cl2.head);
  3200         } else {
  3201             return union(cl1.tail, cl2.tail).prepend(cl1.head);
  3205     /**
  3206      * Intersect two closures
  3207      */
  3208     public List<Type> intersect(List<Type> cl1, List<Type> cl2) {
  3209         if (cl1 == cl2)
  3210             return cl1;
  3211         if (cl1.isEmpty() || cl2.isEmpty())
  3212             return List.nil();
  3213         if (cl1.head.tsym.precedes(cl2.head.tsym, this))
  3214             return intersect(cl1.tail, cl2);
  3215         if (cl2.head.tsym.precedes(cl1.head.tsym, this))
  3216             return intersect(cl1, cl2.tail);
  3217         if (isSameType(cl1.head, cl2.head))
  3218             return intersect(cl1.tail, cl2.tail).prepend(cl1.head);
  3219         if (cl1.head.tsym == cl2.head.tsym &&
  3220             cl1.head.tag == CLASS && cl2.head.tag == CLASS) {
  3221             if (cl1.head.isParameterized() && cl2.head.isParameterized()) {
  3222                 Type merge = merge(cl1.head,cl2.head);
  3223                 return intersect(cl1.tail, cl2.tail).prepend(merge);
  3225             if (cl1.head.isRaw() || cl2.head.isRaw())
  3226                 return intersect(cl1.tail, cl2.tail).prepend(erasure(cl1.head));
  3228         return intersect(cl1.tail, cl2.tail);
  3230     // where
  3231         class TypePair {
  3232             final Type t1;
  3233             final Type t2;
  3234             TypePair(Type t1, Type t2) {
  3235                 this.t1 = t1;
  3236                 this.t2 = t2;
  3238             @Override
  3239             public int hashCode() {
  3240                 return 127 * Types.this.hashCode(t1) + Types.this.hashCode(t2);
  3242             @Override
  3243             public boolean equals(Object obj) {
  3244                 if (!(obj instanceof TypePair))
  3245                     return false;
  3246                 TypePair typePair = (TypePair)obj;
  3247                 return isSameType(t1, typePair.t1)
  3248                     && isSameType(t2, typePair.t2);
  3251         Set<TypePair> mergeCache = new HashSet<TypePair>();
  3252         private Type merge(Type c1, Type c2) {
  3253             ClassType class1 = (ClassType) c1;
  3254             List<Type> act1 = class1.getTypeArguments();
  3255             ClassType class2 = (ClassType) c2;
  3256             List<Type> act2 = class2.getTypeArguments();
  3257             ListBuffer<Type> merged = new ListBuffer<Type>();
  3258             List<Type> typarams = class1.tsym.type.getTypeArguments();
  3260             while (act1.nonEmpty() && act2.nonEmpty() && typarams.nonEmpty()) {
  3261                 if (containsType(act1.head, act2.head)) {
  3262                     merged.append(act1.head);
  3263                 } else if (containsType(act2.head, act1.head)) {
  3264                     merged.append(act2.head);
  3265                 } else {
  3266                     TypePair pair = new TypePair(c1, c2);
  3267                     Type m;
  3268                     if (mergeCache.add(pair)) {
  3269                         m = new WildcardType(lub(upperBound(act1.head),
  3270                                                  upperBound(act2.head)),
  3271                                              BoundKind.EXTENDS,
  3272                                              syms.boundClass);
  3273                         mergeCache.remove(pair);
  3274                     } else {
  3275                         m = new WildcardType(syms.objectType,
  3276                                              BoundKind.UNBOUND,
  3277                                              syms.boundClass);
  3279                     merged.append(m.withTypeVar(typarams.head));
  3281                 act1 = act1.tail;
  3282                 act2 = act2.tail;
  3283                 typarams = typarams.tail;
  3285             Assert.check(act1.isEmpty() && act2.isEmpty() && typarams.isEmpty());
  3286             return new ClassType(class1.getEnclosingType(), merged.toList(), class1.tsym);
  3289     /**
  3290      * Return the minimum type of a closure, a compound type if no
  3291      * unique minimum exists.
  3292      */
  3293     private Type compoundMin(List<Type> cl) {
  3294         if (cl.isEmpty()) return syms.objectType;
  3295         List<Type> compound = closureMin(cl);
  3296         if (compound.isEmpty())
  3297             return null;
  3298         else if (compound.tail.isEmpty())
  3299             return compound.head;
  3300         else
  3301             return makeCompoundType(compound);
  3304     /**
  3305      * Return the minimum types of a closure, suitable for computing
  3306      * compoundMin or glb.
  3307      */
  3308     private List<Type> closureMin(List<Type> cl) {
  3309         ListBuffer<Type> classes = lb();
  3310         ListBuffer<Type> interfaces = lb();
  3311         while (!cl.isEmpty()) {
  3312             Type current = cl.head;
  3313             if (current.isInterface())
  3314                 interfaces.append(current);
  3315             else
  3316                 classes.append(current);
  3317             ListBuffer<Type> candidates = lb();
  3318             for (Type t : cl.tail) {
  3319                 if (!isSubtypeNoCapture(current, t))
  3320                     candidates.append(t);
  3322             cl = candidates.toList();
  3324         return classes.appendList(interfaces).toList();
  3327     /**
  3328      * Return the least upper bound of pair of types.  if the lub does
  3329      * not exist return null.
  3330      */
  3331     public Type lub(Type t1, Type t2) {
  3332         return lub(List.of(t1, t2));
  3335     /**
  3336      * Return the least upper bound (lub) of set of types.  If the lub
  3337      * does not exist return the type of null (bottom).
  3338      */
  3339     public Type lub(List<Type> ts) {
  3340         final int ARRAY_BOUND = 1;
  3341         final int CLASS_BOUND = 2;
  3342         int boundkind = 0;
  3343         for (Type t : ts) {
  3344             switch (t.tag) {
  3345             case CLASS:
  3346                 boundkind |= CLASS_BOUND;
  3347                 break;
  3348             case ARRAY:
  3349                 boundkind |= ARRAY_BOUND;
  3350                 break;
  3351             case  TYPEVAR:
  3352                 do {
  3353                     t = t.getUpperBound();
  3354                 } while (t.tag == TYPEVAR);
  3355                 if (t.tag == ARRAY) {
  3356                     boundkind |= ARRAY_BOUND;
  3357                 } else {
  3358                     boundkind |= CLASS_BOUND;
  3360                 break;
  3361             default:
  3362                 if (t.isPrimitive())
  3363                     return syms.errType;
  3366         switch (boundkind) {
  3367         case 0:
  3368             return syms.botType;
  3370         case ARRAY_BOUND:
  3371             // calculate lub(A[], B[])
  3372             List<Type> elements = Type.map(ts, elemTypeFun);
  3373             for (Type t : elements) {
  3374                 if (t.isPrimitive()) {
  3375                     // if a primitive type is found, then return
  3376                     // arraySuperType unless all the types are the
  3377                     // same
  3378                     Type first = ts.head;
  3379                     for (Type s : ts.tail) {
  3380                         if (!isSameType(first, s)) {
  3381                              // lub(int[], B[]) is Cloneable & Serializable
  3382                             return arraySuperType();
  3385                     // all the array types are the same, return one
  3386                     // lub(int[], int[]) is int[]
  3387                     return first;
  3390             // lub(A[], B[]) is lub(A, B)[]
  3391             return new ArrayType(lub(elements), syms.arrayClass);
  3393         case CLASS_BOUND:
  3394             // calculate lub(A, B)
  3395             while (ts.head.tag != CLASS && ts.head.tag != TYPEVAR)
  3396                 ts = ts.tail;
  3397             Assert.check(!ts.isEmpty());
  3398             //step 1 - compute erased candidate set (EC)
  3399             List<Type> cl = erasedSupertypes(ts.head);
  3400             for (Type t : ts.tail) {
  3401                 if (t.tag == CLASS || t.tag == TYPEVAR)
  3402                     cl = intersect(cl, erasedSupertypes(t));
  3404             //step 2 - compute minimal erased candidate set (MEC)
  3405             List<Type> mec = closureMin(cl);
  3406             //step 3 - for each element G in MEC, compute lci(Inv(G))
  3407             List<Type> candidates = List.nil();
  3408             for (Type erasedSupertype : mec) {
  3409                 List<Type> lci = List.of(asSuper(ts.head, erasedSupertype.tsym));
  3410                 for (Type t : ts) {
  3411                     lci = intersect(lci, List.of(asSuper(t, erasedSupertype.tsym)));
  3413                 candidates = candidates.appendList(lci);
  3415             //step 4 - let MEC be { G1, G2 ... Gn }, then we have that
  3416             //lub = lci(Inv(G1)) & lci(Inv(G2)) & ... & lci(Inv(Gn))
  3417             return compoundMin(candidates);
  3419         default:
  3420             // calculate lub(A, B[])
  3421             List<Type> classes = List.of(arraySuperType());
  3422             for (Type t : ts) {
  3423                 if (t.tag != ARRAY) // Filter out any arrays
  3424                     classes = classes.prepend(t);
  3426             // lub(A, B[]) is lub(A, arraySuperType)
  3427             return lub(classes);
  3430     // where
  3431         List<Type> erasedSupertypes(Type t) {
  3432             ListBuffer<Type> buf = lb();
  3433             for (Type sup : closure(t)) {
  3434                 if (sup.tag == TYPEVAR) {
  3435                     buf.append(sup);
  3436                 } else {
  3437                     buf.append(erasure(sup));
  3440             return buf.toList();
  3443         private Type arraySuperType = null;
  3444         private Type arraySuperType() {
  3445             // initialized lazily to avoid problems during compiler startup
  3446             if (arraySuperType == null) {
  3447                 synchronized (this) {
  3448                     if (arraySuperType == null) {
  3449                         // JLS 10.8: all arrays implement Cloneable and Serializable.
  3450                         arraySuperType = makeCompoundType(List.of(syms.serializableType,
  3451                                                                   syms.cloneableType), true);
  3455             return arraySuperType;
  3457     // </editor-fold>
  3459     // <editor-fold defaultstate="collapsed" desc="Greatest lower bound">
  3460     public Type glb(List<Type> ts) {
  3461         Type t1 = ts.head;
  3462         for (Type t2 : ts.tail) {
  3463             if (t1.isErroneous())
  3464                 return t1;
  3465             t1 = glb(t1, t2);
  3467         return t1;
  3469     //where
  3470     public Type glb(Type t, Type s) {
  3471         if (s == null)
  3472             return t;
  3473         else if (t.isPrimitive() || s.isPrimitive())
  3474             return syms.errType;
  3475         else if (isSubtypeNoCapture(t, s))
  3476             return t;
  3477         else if (isSubtypeNoCapture(s, t))
  3478             return s;
  3480         List<Type> closure = union(closure(t), closure(s));
  3481         List<Type> bounds = closureMin(closure);
  3483         if (bounds.isEmpty()) {             // length == 0
  3484             return syms.objectType;
  3485         } else if (bounds.tail.isEmpty()) { // length == 1
  3486             return bounds.head;
  3487         } else {                            // length > 1
  3488             int classCount = 0;
  3489             for (Type bound : bounds)
  3490                 if (!bound.isInterface())
  3491                     classCount++;
  3492             if (classCount > 1)
  3493                 return createErrorType(t);
  3495         return makeCompoundType(bounds);
  3497     // </editor-fold>
  3499     // <editor-fold defaultstate="collapsed" desc="hashCode">
  3500     /**
  3501      * Compute a hash code on a type.
  3502      */
  3503     public int hashCode(Type t) {
  3504         return hashCode.visit(t);
  3506     // where
  3507         private static final UnaryVisitor<Integer> hashCode = new UnaryVisitor<Integer>() {
  3509             public Integer visitType(Type t, Void ignored) {
  3510                 return t.tag.ordinal();
  3513             @Override
  3514             public Integer visitClassType(ClassType t, Void ignored) {
  3515                 int result = visit(t.getEnclosingType());
  3516                 result *= 127;
  3517                 result += t.tsym.flatName().hashCode();
  3518                 for (Type s : t.getTypeArguments()) {
  3519                     result *= 127;
  3520                     result += visit(s);
  3522                 return result;
  3525             @Override
  3526             public Integer visitMethodType(MethodType t, Void ignored) {
  3527                 int h = METHOD.ordinal();
  3528                 for (List<Type> thisargs = t.argtypes;
  3529                      thisargs.tail != null;
  3530                      thisargs = thisargs.tail)
  3531                     h = (h << 5) + visit(thisargs.head);
  3532                 return (h << 5) + visit(t.restype);
  3535             @Override
  3536             public Integer visitWildcardType(WildcardType t, Void ignored) {
  3537                 int result = t.kind.hashCode();
  3538                 if (t.type != null) {
  3539                     result *= 127;
  3540                     result += visit(t.type);
  3542                 return result;
  3545             @Override
  3546             public Integer visitArrayType(ArrayType t, Void ignored) {
  3547                 return visit(t.elemtype) + 12;
  3550             @Override
  3551             public Integer visitTypeVar(TypeVar t, Void ignored) {
  3552                 return System.identityHashCode(t.tsym);
  3555             @Override
  3556             public Integer visitUndetVar(UndetVar t, Void ignored) {
  3557                 return System.identityHashCode(t);
  3560             @Override
  3561             public Integer visitErrorType(ErrorType t, Void ignored) {
  3562                 return 0;
  3564         };
  3565     // </editor-fold>
  3567     // <editor-fold defaultstate="collapsed" desc="Return-Type-Substitutable">
  3568     /**
  3569      * Does t have a result that is a subtype of the result type of s,
  3570      * suitable for covariant returns?  It is assumed that both types
  3571      * are (possibly polymorphic) method types.  Monomorphic method
  3572      * types are handled in the obvious way.  Polymorphic method types
  3573      * require renaming all type variables of one to corresponding
  3574      * type variables in the other, where correspondence is by
  3575      * position in the type parameter list. */
  3576     public boolean resultSubtype(Type t, Type s, Warner warner) {
  3577         List<Type> tvars = t.getTypeArguments();
  3578         List<Type> svars = s.getTypeArguments();
  3579         Type tres = t.getReturnType();
  3580         Type sres = subst(s.getReturnType(), svars, tvars);
  3581         return covariantReturnType(tres, sres, warner);
  3584     /**
  3585      * Return-Type-Substitutable.
  3586      * @jls section 8.4.5
  3587      */
  3588     public boolean returnTypeSubstitutable(Type r1, Type r2) {
  3589         if (hasSameArgs(r1, r2))
  3590             return resultSubtype(r1, r2, noWarnings);
  3591         else
  3592             return covariantReturnType(r1.getReturnType(),
  3593                                        erasure(r2.getReturnType()),
  3594                                        noWarnings);
  3597     public boolean returnTypeSubstitutable(Type r1,
  3598                                            Type r2, Type r2res,
  3599                                            Warner warner) {
  3600         if (isSameType(r1.getReturnType(), r2res))
  3601             return true;
  3602         if (r1.getReturnType().isPrimitive() || r2res.isPrimitive())
  3603             return false;
  3605         if (hasSameArgs(r1, r2))
  3606             return covariantReturnType(r1.getReturnType(), r2res, warner);
  3607         if (!allowCovariantReturns)
  3608             return false;
  3609         if (isSubtypeUnchecked(r1.getReturnType(), r2res, warner))
  3610             return true;
  3611         if (!isSubtype(r1.getReturnType(), erasure(r2res)))
  3612             return false;
  3613         warner.warn(LintCategory.UNCHECKED);
  3614         return true;
  3617     /**
  3618      * Is t an appropriate return type in an overrider for a
  3619      * method that returns s?
  3620      */
  3621     public boolean covariantReturnType(Type t, Type s, Warner warner) {
  3622         return
  3623             isSameType(t, s) ||
  3624             allowCovariantReturns &&
  3625             !t.isPrimitive() &&
  3626             !s.isPrimitive() &&
  3627             isAssignable(t, s, warner);
  3629     // </editor-fold>
  3631     // <editor-fold defaultstate="collapsed" desc="Box/unbox support">
  3632     /**
  3633      * Return the class that boxes the given primitive.
  3634      */
  3635     public ClassSymbol boxedClass(Type t) {
  3636         return reader.enterClass(syms.boxedName[t.tag.ordinal()]);
  3639     /**
  3640      * Return the boxed type if 't' is primitive, otherwise return 't' itself.
  3641      */
  3642     public Type boxedTypeOrType(Type t) {
  3643         return t.isPrimitive() ?
  3644             boxedClass(t).type :
  3645             t;
  3648     /**
  3649      * Return the primitive type corresponding to a boxed type.
  3650      */
  3651     public Type unboxedType(Type t) {
  3652         if (allowBoxing) {
  3653             for (int i=0; i<syms.boxedName.length; i++) {
  3654                 Name box = syms.boxedName[i];
  3655                 if (box != null &&
  3656                     asSuper(t, reader.enterClass(box)) != null)
  3657                     return syms.typeOfTag[i];
  3660         return Type.noType;
  3663     /**
  3664      * Return the unboxed type if 't' is a boxed class, otherwise return 't' itself.
  3665      */
  3666     public Type unboxedTypeOrType(Type t) {
  3667         Type unboxedType = unboxedType(t);
  3668         return unboxedType.tag == NONE ? t : unboxedType;
  3670     // </editor-fold>
  3672     // <editor-fold defaultstate="collapsed" desc="Capture conversion">
  3673     /*
  3674      * JLS 5.1.10 Capture Conversion:
  3676      * Let G name a generic type declaration with n formal type
  3677      * parameters A1 ... An with corresponding bounds U1 ... Un. There
  3678      * exists a capture conversion from G<T1 ... Tn> to G<S1 ... Sn>,
  3679      * where, for 1 <= i <= n:
  3681      * + If Ti is a wildcard type argument (4.5.1) of the form ? then
  3682      *   Si is a fresh type variable whose upper bound is
  3683      *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is the null
  3684      *   type.
  3686      * + If Ti is a wildcard type argument of the form ? extends Bi,
  3687      *   then Si is a fresh type variable whose upper bound is
  3688      *   glb(Bi, Ui[A1 := S1, ..., An := Sn]) and whose lower bound is
  3689      *   the null type, where glb(V1,... ,Vm) is V1 & ... & Vm. It is
  3690      *   a compile-time error if for any two classes (not interfaces)
  3691      *   Vi and Vj,Vi is not a subclass of Vj or vice versa.
  3693      * + If Ti is a wildcard type argument of the form ? super Bi,
  3694      *   then Si is a fresh type variable whose upper bound is
  3695      *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is Bi.
  3697      * + Otherwise, Si = Ti.
  3699      * Capture conversion on any type other than a parameterized type
  3700      * (4.5) acts as an identity conversion (5.1.1). Capture
  3701      * conversions never require a special action at run time and
  3702      * therefore never throw an exception at run time.
  3704      * Capture conversion is not applied recursively.
  3705      */
  3706     /**
  3707      * Capture conversion as specified by the JLS.
  3708      */
  3710     public List<Type> capture(List<Type> ts) {
  3711         List<Type> buf = List.nil();
  3712         for (Type t : ts) {
  3713             buf = buf.prepend(capture(t));
  3715         return buf.reverse();
  3717     public Type capture(Type t) {
  3718         if (t.tag != CLASS)
  3719             return t;
  3720         if (t.getEnclosingType() != Type.noType) {
  3721             Type capturedEncl = capture(t.getEnclosingType());
  3722             if (capturedEncl != t.getEnclosingType()) {
  3723                 Type type1 = memberType(capturedEncl, t.tsym);
  3724                 t = subst(type1, t.tsym.type.getTypeArguments(), t.getTypeArguments());
  3727         t = t.unannotatedType();
  3728         ClassType cls = (ClassType)t;
  3729         if (cls.isRaw() || !cls.isParameterized())
  3730             return cls;
  3732         ClassType G = (ClassType)cls.asElement().asType();
  3733         List<Type> A = G.getTypeArguments();
  3734         List<Type> T = cls.getTypeArguments();
  3735         List<Type> S = freshTypeVariables(T);
  3737         List<Type> currentA = A;
  3738         List<Type> currentT = T;
  3739         List<Type> currentS = S;
  3740         boolean captured = false;
  3741         while (!currentA.isEmpty() &&
  3742                !currentT.isEmpty() &&
  3743                !currentS.isEmpty()) {
  3744             if (currentS.head != currentT.head) {
  3745                 captured = true;
  3746                 WildcardType Ti = (WildcardType)currentT.head;
  3747                 Type Ui = currentA.head.getUpperBound();
  3748                 CapturedType Si = (CapturedType)currentS.head;
  3749                 if (Ui == null)
  3750                     Ui = syms.objectType;
  3751                 switch (Ti.kind) {
  3752                 case UNBOUND:
  3753                     Si.bound = subst(Ui, A, S);
  3754                     Si.lower = syms.botType;
  3755                     break;
  3756                 case EXTENDS:
  3757                     Si.bound = glb(Ti.getExtendsBound(), subst(Ui, A, S));
  3758                     Si.lower = syms.botType;
  3759                     break;
  3760                 case SUPER:
  3761                     Si.bound = subst(Ui, A, S);
  3762                     Si.lower = Ti.getSuperBound();
  3763                     break;
  3765                 if (Si.bound == Si.lower)
  3766                     currentS.head = Si.bound;
  3768             currentA = currentA.tail;
  3769             currentT = currentT.tail;
  3770             currentS = currentS.tail;
  3772         if (!currentA.isEmpty() || !currentT.isEmpty() || !currentS.isEmpty())
  3773             return erasure(t); // some "rare" type involved
  3775         if (captured)
  3776             return new ClassType(cls.getEnclosingType(), S, cls.tsym);
  3777         else
  3778             return t;
  3780     // where
  3781         public List<Type> freshTypeVariables(List<Type> types) {
  3782             ListBuffer<Type> result = lb();
  3783             for (Type t : types) {
  3784                 if (t.tag == WILDCARD) {
  3785                     Type bound = ((WildcardType)t).getExtendsBound();
  3786                     if (bound == null)
  3787                         bound = syms.objectType;
  3788                     result.append(new CapturedType(capturedName,
  3789                                                    syms.noSymbol,
  3790                                                    bound,
  3791                                                    syms.botType,
  3792                                                    (WildcardType)t));
  3793                 } else {
  3794                     result.append(t);
  3797             return result.toList();
  3799     // </editor-fold>
  3801     // <editor-fold defaultstate="collapsed" desc="Internal utility methods">
  3802     private List<Type> upperBounds(List<Type> ss) {
  3803         if (ss.isEmpty()) return ss;
  3804         Type head = upperBound(ss.head);
  3805         List<Type> tail = upperBounds(ss.tail);
  3806         if (head != ss.head || tail != ss.tail)
  3807             return tail.prepend(head);
  3808         else
  3809             return ss;
  3812     private boolean sideCast(Type from, Type to, Warner warn) {
  3813         // We are casting from type $from$ to type $to$, which are
  3814         // non-final unrelated types.  This method
  3815         // tries to reject a cast by transferring type parameters
  3816         // from $to$ to $from$ by common superinterfaces.
  3817         boolean reverse = false;
  3818         Type target = to;
  3819         if ((to.tsym.flags() & INTERFACE) == 0) {
  3820             Assert.check((from.tsym.flags() & INTERFACE) != 0);
  3821             reverse = true;
  3822             to = from;
  3823             from = target;
  3825         List<Type> commonSupers = superClosure(to, erasure(from));
  3826         boolean giveWarning = commonSupers.isEmpty();
  3827         // The arguments to the supers could be unified here to
  3828         // get a more accurate analysis
  3829         while (commonSupers.nonEmpty()) {
  3830             Type t1 = asSuper(from, commonSupers.head.tsym);
  3831             Type t2 = commonSupers.head; // same as asSuper(to, commonSupers.head.tsym);
  3832             if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
  3833                 return false;
  3834             giveWarning = giveWarning || (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2));
  3835             commonSupers = commonSupers.tail;
  3837         if (giveWarning && !isReifiable(reverse ? from : to))
  3838             warn.warn(LintCategory.UNCHECKED);
  3839         if (!allowCovariantReturns)
  3840             // reject if there is a common method signature with
  3841             // incompatible return types.
  3842             chk.checkCompatibleAbstracts(warn.pos(), from, to);
  3843         return true;
  3846     private boolean sideCastFinal(Type from, Type to, Warner warn) {
  3847         // We are casting from type $from$ to type $to$, which are
  3848         // unrelated types one of which is final and the other of
  3849         // which is an interface.  This method
  3850         // tries to reject a cast by transferring type parameters
  3851         // from the final class to the interface.
  3852         boolean reverse = false;
  3853         Type target = to;
  3854         if ((to.tsym.flags() & INTERFACE) == 0) {
  3855             Assert.check((from.tsym.flags() & INTERFACE) != 0);
  3856             reverse = true;
  3857             to = from;
  3858             from = target;
  3860         Assert.check((from.tsym.flags() & FINAL) != 0);
  3861         Type t1 = asSuper(from, to.tsym);
  3862         if (t1 == null) return false;
  3863         Type t2 = to;
  3864         if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
  3865             return false;
  3866         if (!allowCovariantReturns)
  3867             // reject if there is a common method signature with
  3868             // incompatible return types.
  3869             chk.checkCompatibleAbstracts(warn.pos(), from, to);
  3870         if (!isReifiable(target) &&
  3871             (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2)))
  3872             warn.warn(LintCategory.UNCHECKED);
  3873         return true;
  3876     private boolean giveWarning(Type from, Type to) {
  3877         Type subFrom = asSub(from, to.tsym);
  3878         return to.isParameterized() &&
  3879                 (!(isUnbounded(to) ||
  3880                 isSubtype(from, to) ||
  3881                 ((subFrom != null) && containsType(to.allparams(), subFrom.allparams()))));
  3884     private List<Type> superClosure(Type t, Type s) {
  3885         List<Type> cl = List.nil();
  3886         for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
  3887             if (isSubtype(s, erasure(l.head))) {
  3888                 cl = insert(cl, l.head);
  3889             } else {
  3890                 cl = union(cl, superClosure(l.head, s));
  3893         return cl;
  3896     private boolean containsTypeEquivalent(Type t, Type s) {
  3897         return
  3898             isSameType(t, s) || // shortcut
  3899             containsType(t, s) && containsType(s, t);
  3902     // <editor-fold defaultstate="collapsed" desc="adapt">
  3903     /**
  3904      * Adapt a type by computing a substitution which maps a source
  3905      * type to a target type.
  3907      * @param source    the source type
  3908      * @param target    the target type
  3909      * @param from      the type variables of the computed substitution
  3910      * @param to        the types of the computed substitution.
  3911      */
  3912     public void adapt(Type source,
  3913                        Type target,
  3914                        ListBuffer<Type> from,
  3915                        ListBuffer<Type> to) throws AdaptFailure {
  3916         new Adapter(from, to).adapt(source, target);
  3919     class Adapter extends SimpleVisitor<Void, Type> {
  3921         ListBuffer<Type> from;
  3922         ListBuffer<Type> to;
  3923         Map<Symbol,Type> mapping;
  3925         Adapter(ListBuffer<Type> from, ListBuffer<Type> to) {
  3926             this.from = from;
  3927             this.to = to;
  3928             mapping = new HashMap<Symbol,Type>();
  3931         public void adapt(Type source, Type target) throws AdaptFailure {
  3932             visit(source, target);
  3933             List<Type> fromList = from.toList();
  3934             List<Type> toList = to.toList();
  3935             while (!fromList.isEmpty()) {
  3936                 Type val = mapping.get(fromList.head.tsym);
  3937                 if (toList.head != val)
  3938                     toList.head = val;
  3939                 fromList = fromList.tail;
  3940                 toList = toList.tail;
  3944         @Override
  3945         public Void visitClassType(ClassType source, Type target) throws AdaptFailure {
  3946             if (target.tag == CLASS)
  3947                 adaptRecursive(source.allparams(), target.allparams());
  3948             return null;
  3951         @Override
  3952         public Void visitArrayType(ArrayType source, Type target) throws AdaptFailure {
  3953             if (target.tag == ARRAY)
  3954                 adaptRecursive(elemtype(source), elemtype(target));
  3955             return null;
  3958         @Override
  3959         public Void visitWildcardType(WildcardType source, Type target) throws AdaptFailure {
  3960             if (source.isExtendsBound())
  3961                 adaptRecursive(upperBound(source), upperBound(target));
  3962             else if (source.isSuperBound())
  3963                 adaptRecursive(lowerBound(source), lowerBound(target));
  3964             return null;
  3967         @Override
  3968         public Void visitTypeVar(TypeVar source, Type target) throws AdaptFailure {
  3969             // Check to see if there is
  3970             // already a mapping for $source$, in which case
  3971             // the old mapping will be merged with the new
  3972             Type val = mapping.get(source.tsym);
  3973             if (val != null) {
  3974                 if (val.isSuperBound() && target.isSuperBound()) {
  3975                     val = isSubtype(lowerBound(val), lowerBound(target))
  3976                         ? target : val;
  3977                 } else if (val.isExtendsBound() && target.isExtendsBound()) {
  3978                     val = isSubtype(upperBound(val), upperBound(target))
  3979                         ? val : target;
  3980                 } else if (!isSameType(val, target)) {
  3981                     throw new AdaptFailure();
  3983             } else {
  3984                 val = target;
  3985                 from.append(source);
  3986                 to.append(target);
  3988             mapping.put(source.tsym, val);
  3989             return null;
  3992         @Override
  3993         public Void visitType(Type source, Type target) {
  3994             return null;
  3997         private Set<TypePair> cache = new HashSet<TypePair>();
  3999         private void adaptRecursive(Type source, Type target) {
  4000             TypePair pair = new TypePair(source, target);
  4001             if (cache.add(pair)) {
  4002                 try {
  4003                     visit(source, target);
  4004                 } finally {
  4005                     cache.remove(pair);
  4010         private void adaptRecursive(List<Type> source, List<Type> target) {
  4011             if (source.length() == target.length()) {
  4012                 while (source.nonEmpty()) {
  4013                     adaptRecursive(source.head, target.head);
  4014                     source = source.tail;
  4015                     target = target.tail;
  4021     public static class AdaptFailure extends RuntimeException {
  4022         static final long serialVersionUID = -7490231548272701566L;
  4025     private void adaptSelf(Type t,
  4026                            ListBuffer<Type> from,
  4027                            ListBuffer<Type> to) {
  4028         try {
  4029             //if (t.tsym.type != t)
  4030                 adapt(t.tsym.type, t, from, to);
  4031         } catch (AdaptFailure ex) {
  4032             // Adapt should never fail calculating a mapping from
  4033             // t.tsym.type to t as there can be no merge problem.
  4034             throw new AssertionError(ex);
  4037     // </editor-fold>
  4039     /**
  4040      * Rewrite all type variables (universal quantifiers) in the given
  4041      * type to wildcards (existential quantifiers).  This is used to
  4042      * determine if a cast is allowed.  For example, if high is true
  4043      * and {@code T <: Number}, then {@code List<T>} is rewritten to
  4044      * {@code List<?  extends Number>}.  Since {@code List<Integer> <:
  4045      * List<? extends Number>} a {@code List<T>} can be cast to {@code
  4046      * List<Integer>} with a warning.
  4047      * @param t a type
  4048      * @param high if true return an upper bound; otherwise a lower
  4049      * bound
  4050      * @param rewriteTypeVars only rewrite captured wildcards if false;
  4051      * otherwise rewrite all type variables
  4052      * @return the type rewritten with wildcards (existential
  4053      * quantifiers) only
  4054      */
  4055     private Type rewriteQuantifiers(Type t, boolean high, boolean rewriteTypeVars) {
  4056         return new Rewriter(high, rewriteTypeVars).visit(t);
  4059     class Rewriter extends UnaryVisitor<Type> {
  4061         boolean high;
  4062         boolean rewriteTypeVars;
  4064         Rewriter(boolean high, boolean rewriteTypeVars) {
  4065             this.high = high;
  4066             this.rewriteTypeVars = rewriteTypeVars;
  4069         @Override
  4070         public Type visitClassType(ClassType t, Void s) {
  4071             ListBuffer<Type> rewritten = new ListBuffer<Type>();
  4072             boolean changed = false;
  4073             for (Type arg : t.allparams()) {
  4074                 Type bound = visit(arg);
  4075                 if (arg != bound) {
  4076                     changed = true;
  4078                 rewritten.append(bound);
  4080             if (changed)
  4081                 return subst(t.tsym.type,
  4082                         t.tsym.type.allparams(),
  4083                         rewritten.toList());
  4084             else
  4085                 return t;
  4088         public Type visitType(Type t, Void s) {
  4089             return high ? upperBound(t) : lowerBound(t);
  4092         @Override
  4093         public Type visitCapturedType(CapturedType t, Void s) {
  4094             Type w_bound = t.wildcard.type;
  4095             Type bound = w_bound.contains(t) ?
  4096                         erasure(w_bound) :
  4097                         visit(w_bound);
  4098             return rewriteAsWildcardType(visit(bound), t.wildcard.bound, t.wildcard.kind);
  4101         @Override
  4102         public Type visitTypeVar(TypeVar t, Void s) {
  4103             if (rewriteTypeVars) {
  4104                 Type bound = t.bound.contains(t) ?
  4105                         erasure(t.bound) :
  4106                         visit(t.bound);
  4107                 return rewriteAsWildcardType(bound, t, EXTENDS);
  4108             } else {
  4109                 return t;
  4113         @Override
  4114         public Type visitWildcardType(WildcardType t, Void s) {
  4115             Type bound2 = visit(t.type);
  4116             return t.type == bound2 ? t : rewriteAsWildcardType(bound2, t.bound, t.kind);
  4119         private Type rewriteAsWildcardType(Type bound, TypeVar formal, BoundKind bk) {
  4120             switch (bk) {
  4121                case EXTENDS: return high ?
  4122                        makeExtendsWildcard(B(bound), formal) :
  4123                        makeExtendsWildcard(syms.objectType, formal);
  4124                case SUPER: return high ?
  4125                        makeSuperWildcard(syms.botType, formal) :
  4126                        makeSuperWildcard(B(bound), formal);
  4127                case UNBOUND: return makeExtendsWildcard(syms.objectType, formal);
  4128                default:
  4129                    Assert.error("Invalid bound kind " + bk);
  4130                    return null;
  4134         Type B(Type t) {
  4135             while (t.tag == WILDCARD) {
  4136                 WildcardType w = (WildcardType)t;
  4137                 t = high ?
  4138                     w.getExtendsBound() :
  4139                     w.getSuperBound();
  4140                 if (t == null) {
  4141                     t = high ? syms.objectType : syms.botType;
  4144             return t;
  4149     /**
  4150      * Create a wildcard with the given upper (extends) bound; create
  4151      * an unbounded wildcard if bound is Object.
  4153      * @param bound the upper bound
  4154      * @param formal the formal type parameter that will be
  4155      * substituted by the wildcard
  4156      */
  4157     private WildcardType makeExtendsWildcard(Type bound, TypeVar formal) {
  4158         if (bound == syms.objectType) {
  4159             return new WildcardType(syms.objectType,
  4160                                     BoundKind.UNBOUND,
  4161                                     syms.boundClass,
  4162                                     formal);
  4163         } else {
  4164             return new WildcardType(bound,
  4165                                     BoundKind.EXTENDS,
  4166                                     syms.boundClass,
  4167                                     formal);
  4171     /**
  4172      * Create a wildcard with the given lower (super) bound; create an
  4173      * unbounded wildcard if bound is bottom (type of {@code null}).
  4175      * @param bound the lower bound
  4176      * @param formal the formal type parameter that will be
  4177      * substituted by the wildcard
  4178      */
  4179     private WildcardType makeSuperWildcard(Type bound, TypeVar formal) {
  4180         if (bound.tag == BOT) {
  4181             return new WildcardType(syms.objectType,
  4182                                     BoundKind.UNBOUND,
  4183                                     syms.boundClass,
  4184                                     formal);
  4185         } else {
  4186             return new WildcardType(bound,
  4187                                     BoundKind.SUPER,
  4188                                     syms.boundClass,
  4189                                     formal);
  4193     /**
  4194      * A wrapper for a type that allows use in sets.
  4195      */
  4196     public static class UniqueType {
  4197         public final Type type;
  4198         final Types types;
  4200         public UniqueType(Type type, Types types) {
  4201             this.type = type;
  4202             this.types = types;
  4205         public int hashCode() {
  4206             return types.hashCode(type);
  4209         public boolean equals(Object obj) {
  4210             return (obj instanceof UniqueType) &&
  4211                 types.isSameType(type, ((UniqueType)obj).type);
  4214         public String toString() {
  4215             return type.toString();
  4219     // </editor-fold>
  4221     // <editor-fold defaultstate="collapsed" desc="Visitors">
  4222     /**
  4223      * A default visitor for types.  All visitor methods except
  4224      * visitType are implemented by delegating to visitType.  Concrete
  4225      * subclasses must provide an implementation of visitType and can
  4226      * override other methods as needed.
  4228      * @param <R> the return type of the operation implemented by this
  4229      * visitor; use Void if no return type is needed.
  4230      * @param <S> the type of the second argument (the first being the
  4231      * type itself) of the operation implemented by this visitor; use
  4232      * Void if a second argument is not needed.
  4233      */
  4234     public static abstract class DefaultTypeVisitor<R,S> implements Type.Visitor<R,S> {
  4235         final public R visit(Type t, S s)               { return t.accept(this, s); }
  4236         public R visitClassType(ClassType t, S s)       { return visitType(t, s); }
  4237         public R visitWildcardType(WildcardType t, S s) { return visitType(t, s); }
  4238         public R visitArrayType(ArrayType t, S s)       { return visitType(t, s); }
  4239         public R visitMethodType(MethodType t, S s)     { return visitType(t, s); }
  4240         public R visitPackageType(PackageType t, S s)   { return visitType(t, s); }
  4241         public R visitTypeVar(TypeVar t, S s)           { return visitType(t, s); }
  4242         public R visitCapturedType(CapturedType t, S s) { return visitType(t, s); }
  4243         public R visitForAll(ForAll t, S s)             { return visitType(t, s); }
  4244         public R visitUndetVar(UndetVar t, S s)         { return visitType(t, s); }
  4245         public R visitErrorType(ErrorType t, S s)       { return visitType(t, s); }
  4246         // Pretend annotations don't exist
  4247         public R visitAnnotatedType(AnnotatedType t, S s) { return visit(t.underlyingType, s); }
  4250     /**
  4251      * A default visitor for symbols.  All visitor methods except
  4252      * visitSymbol are implemented by delegating to visitSymbol.  Concrete
  4253      * subclasses must provide an implementation of visitSymbol and can
  4254      * override other methods as needed.
  4256      * @param <R> the return type of the operation implemented by this
  4257      * visitor; use Void if no return type is needed.
  4258      * @param <S> the type of the second argument (the first being the
  4259      * symbol itself) of the operation implemented by this visitor; use
  4260      * Void if a second argument is not needed.
  4261      */
  4262     public static abstract class DefaultSymbolVisitor<R,S> implements Symbol.Visitor<R,S> {
  4263         final public R visit(Symbol s, S arg)                   { return s.accept(this, arg); }
  4264         public R visitClassSymbol(ClassSymbol s, S arg)         { return visitSymbol(s, arg); }
  4265         public R visitMethodSymbol(MethodSymbol s, S arg)       { return visitSymbol(s, arg); }
  4266         public R visitOperatorSymbol(OperatorSymbol s, S arg)   { return visitSymbol(s, arg); }
  4267         public R visitPackageSymbol(PackageSymbol s, S arg)     { return visitSymbol(s, arg); }
  4268         public R visitTypeSymbol(TypeSymbol s, S arg)           { return visitSymbol(s, arg); }
  4269         public R visitVarSymbol(VarSymbol s, S arg)             { return visitSymbol(s, arg); }
  4272     /**
  4273      * A <em>simple</em> visitor for types.  This visitor is simple as
  4274      * captured wildcards, for-all types (generic methods), and
  4275      * undetermined type variables (part of inference) are hidden.
  4276      * Captured wildcards are hidden by treating them as type
  4277      * variables and the rest are hidden by visiting their qtypes.
  4279      * @param <R> the return type of the operation implemented by this
  4280      * visitor; use Void if no return type is needed.
  4281      * @param <S> the type of the second argument (the first being the
  4282      * type itself) of the operation implemented by this visitor; use
  4283      * Void if a second argument is not needed.
  4284      */
  4285     public static abstract class SimpleVisitor<R,S> extends DefaultTypeVisitor<R,S> {
  4286         @Override
  4287         public R visitCapturedType(CapturedType t, S s) {
  4288             return visitTypeVar(t, s);
  4290         @Override
  4291         public R visitForAll(ForAll t, S s) {
  4292             return visit(t.qtype, s);
  4294         @Override
  4295         public R visitUndetVar(UndetVar t, S s) {
  4296             return visit(t.qtype, s);
  4300     /**
  4301      * A plain relation on types.  That is a 2-ary function on the
  4302      * form Type&nbsp;&times;&nbsp;Type&nbsp;&rarr;&nbsp;Boolean.
  4303      * <!-- In plain text: Type x Type -> Boolean -->
  4304      */
  4305     public static abstract class TypeRelation extends SimpleVisitor<Boolean,Type> {}
  4307     /**
  4308      * A convenience visitor for implementing operations that only
  4309      * require one argument (the type itself), that is, unary
  4310      * operations.
  4312      * @param <R> the return type of the operation implemented by this
  4313      * visitor; use Void if no return type is needed.
  4314      */
  4315     public static abstract class UnaryVisitor<R> extends SimpleVisitor<R,Void> {
  4316         final public R visit(Type t) { return t.accept(this, null); }
  4319     /**
  4320      * A visitor for implementing a mapping from types to types.  The
  4321      * default behavior of this class is to implement the identity
  4322      * mapping (mapping a type to itself).  This can be overridden in
  4323      * subclasses.
  4325      * @param <S> the type of the second argument (the first being the
  4326      * type itself) of this mapping; use Void if a second argument is
  4327      * not needed.
  4328      */
  4329     public static class MapVisitor<S> extends DefaultTypeVisitor<Type,S> {
  4330         final public Type visit(Type t) { return t.accept(this, null); }
  4331         public Type visitType(Type t, S s) { return t; }
  4333     // </editor-fold>
  4336     // <editor-fold defaultstate="collapsed" desc="Annotation support">
  4338     public RetentionPolicy getRetention(Attribute.Compound a) {
  4339         return getRetention(a.type.tsym);
  4342     public RetentionPolicy getRetention(Symbol sym) {
  4343         RetentionPolicy vis = RetentionPolicy.CLASS; // the default
  4344         Attribute.Compound c = sym.attribute(syms.retentionType.tsym);
  4345         if (c != null) {
  4346             Attribute value = c.member(names.value);
  4347             if (value != null && value instanceof Attribute.Enum) {
  4348                 Name levelName = ((Attribute.Enum)value).value.name;
  4349                 if (levelName == names.SOURCE) vis = RetentionPolicy.SOURCE;
  4350                 else if (levelName == names.CLASS) vis = RetentionPolicy.CLASS;
  4351                 else if (levelName == names.RUNTIME) vis = RetentionPolicy.RUNTIME;
  4352                 else ;// /* fail soft */ throw new AssertionError(levelName);
  4355         return vis;
  4357     // </editor-fold>
  4359     // <editor-fold defaultstate="collapsed" desc="Signature Generation">
  4361     public static abstract class SignatureGenerator {
  4363         private final Types types;
  4365         protected abstract void append(char ch);
  4366         protected abstract void append(byte[] ba);
  4367         protected abstract void append(Name name);
  4368         protected void classReference(ClassSymbol c) { /* by default: no-op */ }
  4370         protected SignatureGenerator(Types types) {
  4371             this.types = types;
  4374         /**
  4375          * Assemble signature of given type in string buffer.
  4376          */
  4377         public void assembleSig(Type type) {
  4378             type = type.unannotatedType();
  4379             switch (type.getTag()) {
  4380                 case BYTE:
  4381                     append('B');
  4382                     break;
  4383                 case SHORT:
  4384                     append('S');
  4385                     break;
  4386                 case CHAR:
  4387                     append('C');
  4388                     break;
  4389                 case INT:
  4390                     append('I');
  4391                     break;
  4392                 case LONG:
  4393                     append('J');
  4394                     break;
  4395                 case FLOAT:
  4396                     append('F');
  4397                     break;
  4398                 case DOUBLE:
  4399                     append('D');
  4400                     break;
  4401                 case BOOLEAN:
  4402                     append('Z');
  4403                     break;
  4404                 case VOID:
  4405                     append('V');
  4406                     break;
  4407                 case CLASS:
  4408                     append('L');
  4409                     assembleClassSig(type);
  4410                     append(';');
  4411                     break;
  4412                 case ARRAY:
  4413                     ArrayType at = (ArrayType) type;
  4414                     append('[');
  4415                     assembleSig(at.elemtype);
  4416                     break;
  4417                 case METHOD:
  4418                     MethodType mt = (MethodType) type;
  4419                     append('(');
  4420                     assembleSig(mt.argtypes);
  4421                     append(')');
  4422                     assembleSig(mt.restype);
  4423                     if (hasTypeVar(mt.thrown)) {
  4424                         for (List<Type> l = mt.thrown; l.nonEmpty(); l = l.tail) {
  4425                             append('^');
  4426                             assembleSig(l.head);
  4429                     break;
  4430                 case WILDCARD: {
  4431                     Type.WildcardType ta = (Type.WildcardType) type;
  4432                     switch (ta.kind) {
  4433                         case SUPER:
  4434                             append('-');
  4435                             assembleSig(ta.type);
  4436                             break;
  4437                         case EXTENDS:
  4438                             append('+');
  4439                             assembleSig(ta.type);
  4440                             break;
  4441                         case UNBOUND:
  4442                             append('*');
  4443                             break;
  4444                         default:
  4445                             throw new AssertionError(ta.kind);
  4447                     break;
  4449                 case TYPEVAR:
  4450                     append('T');
  4451                     append(type.tsym.name);
  4452                     append(';');
  4453                     break;
  4454                 case FORALL:
  4455                     Type.ForAll ft = (Type.ForAll) type;
  4456                     assembleParamsSig(ft.tvars);
  4457                     assembleSig(ft.qtype);
  4458                     break;
  4459                 default:
  4460                     throw new AssertionError("typeSig " + type.getTag());
  4464         public boolean hasTypeVar(List<Type> l) {
  4465             while (l.nonEmpty()) {
  4466                 if (l.head.hasTag(TypeTag.TYPEVAR)) {
  4467                     return true;
  4469                 l = l.tail;
  4471             return false;
  4474         public void assembleClassSig(Type type) {
  4475             type = type.unannotatedType();
  4476             ClassType ct = (ClassType) type;
  4477             ClassSymbol c = (ClassSymbol) ct.tsym;
  4478             classReference(c);
  4479             Type outer = ct.getEnclosingType();
  4480             if (outer.allparams().nonEmpty()) {
  4481                 boolean rawOuter =
  4482                         c.owner.kind == Kinds.MTH || // either a local class
  4483                         c.name == types.names.empty; // or anonymous
  4484                 assembleClassSig(rawOuter
  4485                         ? types.erasure(outer)
  4486                         : outer);
  4487                 append('.');
  4488                 Assert.check(c.flatname.startsWith(c.owner.enclClass().flatname));
  4489                 append(rawOuter
  4490                         ? c.flatname.subName(c.owner.enclClass().flatname.getByteLength() + 1, c.flatname.getByteLength())
  4491                         : c.name);
  4492             } else {
  4493                 append(externalize(c.flatname));
  4495             if (ct.getTypeArguments().nonEmpty()) {
  4496                 append('<');
  4497                 assembleSig(ct.getTypeArguments());
  4498                 append('>');
  4502         public void assembleParamsSig(List<Type> typarams) {
  4503             append('<');
  4504             for (List<Type> ts = typarams; ts.nonEmpty(); ts = ts.tail) {
  4505                 Type.TypeVar tvar = (Type.TypeVar) ts.head;
  4506                 append(tvar.tsym.name);
  4507                 List<Type> bounds = types.getBounds(tvar);
  4508                 if ((bounds.head.tsym.flags() & INTERFACE) != 0) {
  4509                     append(':');
  4511                 for (List<Type> l = bounds; l.nonEmpty(); l = l.tail) {
  4512                     append(':');
  4513                     assembleSig(l.head);
  4516             append('>');
  4519         private void assembleSig(List<Type> types) {
  4520             for (List<Type> ts = types; ts.nonEmpty(); ts = ts.tail) {
  4521                 assembleSig(ts.head);
  4525     // </editor-fold>

mercurial