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

Fri, 23 May 2014 16:27:22 +0100

author
pgovereau
date
Fri, 23 May 2014 16:27:22 +0100
changeset 2398
7c925f35f81c
parent 2385
856d94394294
child 2400
0e026d3f2786
permissions
-rw-r--r--

8033437: javac, inconsistent generic types behaviour when compiling together vs. separate
Reviewed-by: jjg
Contributed-by: vicente.romero@oracle.com, paul.govereau@oracle.com

     1 /*
     2  * Copyright (c) 2003, 2014, 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.HashSet;
    30 import java.util.HashMap;
    31 import java.util.Locale;
    32 import java.util.Map;
    33 import java.util.Set;
    34 import java.util.WeakHashMap;
    36 import javax.tools.JavaFileObject;
    38 import com.sun.tools.javac.code.Attribute.RetentionPolicy;
    39 import com.sun.tools.javac.code.Lint.LintCategory;
    40 import com.sun.tools.javac.code.Type.UndetVar.InferenceBound;
    41 import com.sun.tools.javac.comp.AttrContext;
    42 import com.sun.tools.javac.comp.Check;
    43 import com.sun.tools.javac.comp.Enter;
    44 import com.sun.tools.javac.comp.Env;
    45 import com.sun.tools.javac.jvm.ClassReader;
    46 import com.sun.tools.javac.tree.JCTree;
    47 import com.sun.tools.javac.util.*;
    48 import static com.sun.tools.javac.code.BoundKind.*;
    49 import static com.sun.tools.javac.code.Flags.*;
    50 import static com.sun.tools.javac.code.Scope.*;
    51 import static com.sun.tools.javac.code.Symbol.*;
    52 import static com.sun.tools.javac.code.Type.*;
    53 import static com.sun.tools.javac.code.TypeTag.*;
    54 import static com.sun.tools.javac.jvm.ClassFile.externalize;
    56 /**
    57  * Utility class containing various operations on types.
    58  *
    59  * <p>Unless other names are more illustrative, the following naming
    60  * conventions should be observed in this file:
    61  *
    62  * <dl>
    63  * <dt>t</dt>
    64  * <dd>If the first argument to an operation is a type, it should be named t.</dd>
    65  * <dt>s</dt>
    66  * <dd>Similarly, if the second argument to an operation is a type, it should be named s.</dd>
    67  * <dt>ts</dt>
    68  * <dd>If an operations takes a list of types, the first should be named ts.</dd>
    69  * <dt>ss</dt>
    70  * <dd>A second list of types should be named ss.</dd>
    71  * </dl>
    72  *
    73  * <p><b>This is NOT part of any supported API.
    74  * If you write code that depends on this, you do so at your own risk.
    75  * This code and its internal interfaces are subject to change or
    76  * deletion without notice.</b>
    77  */
    78 public class Types {
    79     protected static final Context.Key<Types> typesKey =
    80         new Context.Key<Types>();
    82     final Symtab syms;
    83     final JavacMessages messages;
    84     final Names names;
    85     final boolean allowBoxing;
    86     final boolean allowCovariantReturns;
    87     final boolean allowObjectToPrimitiveCast;
    88     final ClassReader reader;
    89     final Check chk;
    90     final Enter enter;
    91     JCDiagnostic.Factory diags;
    92     List<Warner> warnStack = List.nil();
    93     final Name capturedName;
    94     private final FunctionDescriptorLookupError functionDescriptorLookupError;
    96     public final Warner noWarnings;
    98     // <editor-fold defaultstate="collapsed" desc="Instantiating">
    99     public static Types instance(Context context) {
   100         Types instance = context.get(typesKey);
   101         if (instance == null)
   102             instance = new Types(context);
   103         return instance;
   104     }
   106     protected Types(Context context) {
   107         context.put(typesKey, this);
   108         syms = Symtab.instance(context);
   109         names = Names.instance(context);
   110         Source source = Source.instance(context);
   111         allowBoxing = source.allowBoxing();
   112         allowCovariantReturns = source.allowCovariantReturns();
   113         allowObjectToPrimitiveCast = source.allowObjectToPrimitiveCast();
   114         reader = ClassReader.instance(context);
   115         chk = Check.instance(context);
   116         enter = Enter.instance(context);
   117         capturedName = names.fromString("<captured wildcard>");
   118         messages = JavacMessages.instance(context);
   119         diags = JCDiagnostic.Factory.instance(context);
   120         functionDescriptorLookupError = new FunctionDescriptorLookupError();
   121         noWarnings = new Warner(null);
   122     }
   123     // </editor-fold>
   125     // <editor-fold defaultstate="collapsed" desc="upperBound">
   126     /**
   127      * The "rvalue conversion".<br>
   128      * The upper bound of most types is the type
   129      * itself.  Wildcards, on the other hand have upper
   130      * and lower bounds.
   131      * @param t a type
   132      * @return the upper bound of the given type
   133      */
   134     public Type upperBound(Type t) {
   135         return upperBound.visit(t).unannotatedType();
   136     }
   137     // where
   138         private final MapVisitor<Void> upperBound = new MapVisitor<Void>() {
   140             @Override
   141             public Type visitWildcardType(WildcardType t, Void ignored) {
   142                 if (t.isSuperBound())
   143                     return t.bound == null ? syms.objectType : t.bound.bound;
   144                 else
   145                     return visit(t.type);
   146             }
   148             @Override
   149             public Type visitCapturedType(CapturedType t, Void ignored) {
   150                 return visit(t.bound);
   151             }
   152         };
   153     // </editor-fold>
   155     // <editor-fold defaultstate="collapsed" desc="wildLowerBound">
   156     /**
   157      * Get a wildcard's lower bound, returning non-wildcards unchanged.
   158      * @param t a type argument, either a wildcard or a type
   159      */
   160     public Type wildLowerBound(Type t) {
   161         if (t.hasTag(WILDCARD)) {
   162             WildcardType w = (WildcardType) t;
   163             return w.isExtendsBound() ? syms.botType : wildLowerBound(w.type);
   164         }
   165         else return t;
   166     }
   167     // </editor-fold>
   169     // <editor-fold defaultstate="collapsed" desc="cvarLowerBound">
   170     /**
   171      * Get a capture variable's lower bound, returning other types unchanged.
   172      * @param t a type
   173      */
   174     public Type cvarLowerBound(Type t) {
   175         if (t.hasTag(TYPEVAR) && ((TypeVar) t).isCaptured()) {
   176             return cvarLowerBound(t.getLowerBound());
   177         }
   178         else return t;
   179     }
   180     // </editor-fold>
   182     // <editor-fold defaultstate="collapsed" desc="isUnbounded">
   183     /**
   184      * Checks that all the arguments to a class are unbounded
   185      * wildcards or something else that doesn't make any restrictions
   186      * on the arguments. If a class isUnbounded, a raw super- or
   187      * subclass can be cast to it without a warning.
   188      * @param t a type
   189      * @return true iff the given type is unbounded or raw
   190      */
   191     public boolean isUnbounded(Type t) {
   192         return isUnbounded.visit(t);
   193     }
   194     // where
   195         private final UnaryVisitor<Boolean> isUnbounded = new UnaryVisitor<Boolean>() {
   197             public Boolean visitType(Type t, Void ignored) {
   198                 return true;
   199             }
   201             @Override
   202             public Boolean visitClassType(ClassType t, Void ignored) {
   203                 List<Type> parms = t.tsym.type.allparams();
   204                 List<Type> args = t.allparams();
   205                 while (parms.nonEmpty()) {
   206                     WildcardType unb = new WildcardType(syms.objectType,
   207                                                         BoundKind.UNBOUND,
   208                                                         syms.boundClass,
   209                                                         (TypeVar)parms.head.unannotatedType());
   210                     if (!containsType(args.head, unb))
   211                         return false;
   212                     parms = parms.tail;
   213                     args = args.tail;
   214                 }
   215                 return true;
   216             }
   217         };
   218     // </editor-fold>
   220     // <editor-fold defaultstate="collapsed" desc="asSub">
   221     /**
   222      * Return the least specific subtype of t that starts with symbol
   223      * sym.  If none exists, return null.  The least specific subtype
   224      * is determined as follows:
   225      *
   226      * <p>If there is exactly one parameterized instance of sym that is a
   227      * subtype of t, that parameterized instance is returned.<br>
   228      * Otherwise, if the plain type or raw type `sym' is a subtype of
   229      * type t, the type `sym' itself is returned.  Otherwise, null is
   230      * returned.
   231      */
   232     public Type asSub(Type t, Symbol sym) {
   233         return asSub.visit(t, sym);
   234     }
   235     // where
   236         private final SimpleVisitor<Type,Symbol> asSub = new SimpleVisitor<Type,Symbol>() {
   238             public Type visitType(Type t, Symbol sym) {
   239                 return null;
   240             }
   242             @Override
   243             public Type visitClassType(ClassType t, Symbol sym) {
   244                 if (t.tsym == sym)
   245                     return t;
   246                 Type base = asSuper(sym.type, t.tsym);
   247                 if (base == null)
   248                     return null;
   249                 ListBuffer<Type> from = new ListBuffer<Type>();
   250                 ListBuffer<Type> to = new ListBuffer<Type>();
   251                 try {
   252                     adapt(base, t, from, to);
   253                 } catch (AdaptFailure ex) {
   254                     return null;
   255                 }
   256                 Type res = subst(sym.type, from.toList(), to.toList());
   257                 if (!isSubtype(res, t))
   258                     return null;
   259                 ListBuffer<Type> openVars = new ListBuffer<Type>();
   260                 for (List<Type> l = sym.type.allparams();
   261                      l.nonEmpty(); l = l.tail)
   262                     if (res.contains(l.head) && !t.contains(l.head))
   263                         openVars.append(l.head);
   264                 if (openVars.nonEmpty()) {
   265                     if (t.isRaw()) {
   266                         // The subtype of a raw type is raw
   267                         res = erasure(res);
   268                     } else {
   269                         // Unbound type arguments default to ?
   270                         List<Type> opens = openVars.toList();
   271                         ListBuffer<Type> qs = new ListBuffer<Type>();
   272                         for (List<Type> iter = opens; iter.nonEmpty(); iter = iter.tail) {
   273                             qs.append(new WildcardType(syms.objectType, BoundKind.UNBOUND, syms.boundClass, (TypeVar) iter.head.unannotatedType()));
   274                         }
   275                         res = subst(res, opens, qs.toList());
   276                     }
   277                 }
   278                 return res;
   279             }
   281             @Override
   282             public Type visitErrorType(ErrorType t, Symbol sym) {
   283                 return t;
   284             }
   285         };
   286     // </editor-fold>
   288     // <editor-fold defaultstate="collapsed" desc="isConvertible">
   289     /**
   290      * Is t a subtype of or convertible via boxing/unboxing
   291      * conversion to s?
   292      */
   293     public boolean isConvertible(Type t, Type s, Warner warn) {
   294         if (t.hasTag(ERROR)) {
   295             return true;
   296         }
   297         boolean tPrimitive = t.isPrimitive();
   298         boolean sPrimitive = s.isPrimitive();
   299         if (tPrimitive == sPrimitive) {
   300             return isSubtypeUnchecked(t, s, warn);
   301         }
   302         if (!allowBoxing) return false;
   303         return tPrimitive
   304             ? isSubtype(boxedClass(t).type, s)
   305             : isSubtype(unboxedType(t), s);
   306     }
   308     /**
   309      * Is t a subtype of or convertible via boxing/unboxing
   310      * conversions to s?
   311      */
   312     public boolean isConvertible(Type t, Type s) {
   313         return isConvertible(t, s, noWarnings);
   314     }
   315     // </editor-fold>
   317     // <editor-fold defaultstate="collapsed" desc="findSam">
   319     /**
   320      * Exception used to report a function descriptor lookup failure. The exception
   321      * wraps a diagnostic that can be used to generate more details error
   322      * messages.
   323      */
   324     public static class FunctionDescriptorLookupError extends RuntimeException {
   325         private static final long serialVersionUID = 0;
   327         JCDiagnostic diagnostic;
   329         FunctionDescriptorLookupError() {
   330             this.diagnostic = null;
   331         }
   333         FunctionDescriptorLookupError setMessage(JCDiagnostic diag) {
   334             this.diagnostic = diag;
   335             return this;
   336         }
   338         public JCDiagnostic getDiagnostic() {
   339             return diagnostic;
   340         }
   341     }
   343     /**
   344      * A cache that keeps track of function descriptors associated with given
   345      * functional interfaces.
   346      */
   347     class DescriptorCache {
   349         private WeakHashMap<TypeSymbol, Entry> _map = new WeakHashMap<TypeSymbol, Entry>();
   351         class FunctionDescriptor {
   352             Symbol descSym;
   354             FunctionDescriptor(Symbol descSym) {
   355                 this.descSym = descSym;
   356             }
   358             public Symbol getSymbol() {
   359                 return descSym;
   360             }
   362             public Type getType(Type site) {
   363                 site = removeWildcards(site);
   364                 if (!chk.checkValidGenericType(site)) {
   365                     //if the inferred functional interface type is not well-formed,
   366                     //or if it's not a subtype of the original target, issue an error
   367                     throw failure(diags.fragment("no.suitable.functional.intf.inst", site));
   368                 }
   369                 return memberType(site, descSym);
   370             }
   371         }
   373         class Entry {
   374             final FunctionDescriptor cachedDescRes;
   375             final int prevMark;
   377             public Entry(FunctionDescriptor cachedDescRes,
   378                     int prevMark) {
   379                 this.cachedDescRes = cachedDescRes;
   380                 this.prevMark = prevMark;
   381             }
   383             boolean matches(int mark) {
   384                 return  this.prevMark == mark;
   385             }
   386         }
   388         FunctionDescriptor get(TypeSymbol origin) throws FunctionDescriptorLookupError {
   389             Entry e = _map.get(origin);
   390             CompoundScope members = membersClosure(origin.type, false);
   391             if (e == null ||
   392                     !e.matches(members.getMark())) {
   393                 FunctionDescriptor descRes = findDescriptorInternal(origin, members);
   394                 _map.put(origin, new Entry(descRes, members.getMark()));
   395                 return descRes;
   396             }
   397             else {
   398                 return e.cachedDescRes;
   399             }
   400         }
   402         /**
   403          * Compute the function descriptor associated with a given functional interface
   404          */
   405         public FunctionDescriptor findDescriptorInternal(TypeSymbol origin,
   406                 CompoundScope membersCache) throws FunctionDescriptorLookupError {
   407             if (!origin.isInterface() || (origin.flags() & ANNOTATION) != 0) {
   408                 //t must be an interface
   409                 throw failure("not.a.functional.intf", origin);
   410             }
   412             final ListBuffer<Symbol> abstracts = new ListBuffer<>();
   413             for (Symbol sym : membersCache.getElements(new DescriptorFilter(origin))) {
   414                 Type mtype = memberType(origin.type, sym);
   415                 if (abstracts.isEmpty() ||
   416                         (sym.name == abstracts.first().name &&
   417                         overrideEquivalent(mtype, memberType(origin.type, abstracts.first())))) {
   418                     abstracts.append(sym);
   419                 } else {
   420                     //the target method(s) should be the only abstract members of t
   421                     throw failure("not.a.functional.intf.1",  origin,
   422                             diags.fragment("incompatible.abstracts", Kinds.kindName(origin), origin));
   423                 }
   424             }
   425             if (abstracts.isEmpty()) {
   426                 //t must define a suitable non-generic method
   427                 throw failure("not.a.functional.intf.1", origin,
   428                             diags.fragment("no.abstracts", Kinds.kindName(origin), origin));
   429             } else if (abstracts.size() == 1) {
   430                 return new FunctionDescriptor(abstracts.first());
   431             } else { // size > 1
   432                 FunctionDescriptor descRes = mergeDescriptors(origin, abstracts.toList());
   433                 if (descRes == null) {
   434                     //we can get here if the functional interface is ill-formed
   435                     ListBuffer<JCDiagnostic> descriptors = new ListBuffer<>();
   436                     for (Symbol desc : abstracts) {
   437                         String key = desc.type.getThrownTypes().nonEmpty() ?
   438                                 "descriptor.throws" : "descriptor";
   439                         descriptors.append(diags.fragment(key, desc.name,
   440                                 desc.type.getParameterTypes(),
   441                                 desc.type.getReturnType(),
   442                                 desc.type.getThrownTypes()));
   443                     }
   444                     JCDiagnostic.MultilineDiagnostic incompatibleDescriptors =
   445                             new JCDiagnostic.MultilineDiagnostic(diags.fragment("incompatible.descs.in.functional.intf",
   446                             Kinds.kindName(origin), origin), descriptors.toList());
   447                     throw failure(incompatibleDescriptors);
   448                 }
   449                 return descRes;
   450             }
   451         }
   453         /**
   454          * Compute a synthetic type for the target descriptor given a list
   455          * of override-equivalent methods in the functional interface type.
   456          * The resulting method type is a method type that is override-equivalent
   457          * and return-type substitutable with each method in the original list.
   458          */
   459         private FunctionDescriptor mergeDescriptors(TypeSymbol origin, List<Symbol> methodSyms) {
   460             //pick argument types - simply take the signature that is a
   461             //subsignature of all other signatures in the list (as per JLS 8.4.2)
   462             List<Symbol> mostSpecific = List.nil();
   463             outer: for (Symbol msym1 : methodSyms) {
   464                 Type mt1 = memberType(origin.type, msym1);
   465                 for (Symbol msym2 : methodSyms) {
   466                     Type mt2 = memberType(origin.type, msym2);
   467                     if (!isSubSignature(mt1, mt2)) {
   468                         continue outer;
   469                     }
   470                 }
   471                 mostSpecific = mostSpecific.prepend(msym1);
   472             }
   473             if (mostSpecific.isEmpty()) {
   474                 return null;
   475             }
   478             //pick return types - this is done in two phases: (i) first, the most
   479             //specific return type is chosen using strict subtyping; if this fails,
   480             //a second attempt is made using return type substitutability (see JLS 8.4.5)
   481             boolean phase2 = false;
   482             Symbol bestSoFar = null;
   483             while (bestSoFar == null) {
   484                 outer: for (Symbol msym1 : mostSpecific) {
   485                     Type mt1 = memberType(origin.type, msym1);
   486                     for (Symbol msym2 : methodSyms) {
   487                         Type mt2 = memberType(origin.type, msym2);
   488                         if (phase2 ?
   489                                 !returnTypeSubstitutable(mt1, mt2) :
   490                                 !isSubtypeInternal(mt1.getReturnType(), mt2.getReturnType())) {
   491                             continue outer;
   492                         }
   493                     }
   494                     bestSoFar = msym1;
   495                 }
   496                 if (phase2) {
   497                     break;
   498                 } else {
   499                     phase2 = true;
   500                 }
   501             }
   502             if (bestSoFar == null) return null;
   504             //merge thrown types - form the intersection of all the thrown types in
   505             //all the signatures in the list
   506             boolean toErase = !bestSoFar.type.hasTag(FORALL);
   507             List<Type> thrown = null;
   508             Type mt1 = memberType(origin.type, bestSoFar);
   509             for (Symbol msym2 : methodSyms) {
   510                 Type mt2 = memberType(origin.type, msym2);
   511                 List<Type> thrown_mt2 = mt2.getThrownTypes();
   512                 if (toErase) {
   513                     thrown_mt2 = erasure(thrown_mt2);
   514                 } else {
   515                     /* If bestSoFar is generic then all the methods are generic.
   516                      * The opposite is not true: a non generic method can override
   517                      * a generic method (raw override) so it's safe to cast mt1 and
   518                      * mt2 to ForAll.
   519                      */
   520                     ForAll fa1 = (ForAll)mt1;
   521                     ForAll fa2 = (ForAll)mt2;
   522                     thrown_mt2 = subst(thrown_mt2, fa2.tvars, fa1.tvars);
   523                 }
   524                 thrown = (thrown == null) ?
   525                     thrown_mt2 :
   526                     chk.intersect(thrown_mt2, thrown);
   527             }
   529             final List<Type> thrown1 = thrown;
   530             return new FunctionDescriptor(bestSoFar) {
   531                 @Override
   532                 public Type getType(Type origin) {
   533                     Type mt = memberType(origin, getSymbol());
   534                     return createMethodTypeWithThrown(mt, thrown1);
   535                 }
   536             };
   537         }
   539         boolean isSubtypeInternal(Type s, Type t) {
   540             return (s.isPrimitive() && t.isPrimitive()) ?
   541                     isSameType(t, s) :
   542                     isSubtype(s, t);
   543         }
   545         FunctionDescriptorLookupError failure(String msg, Object... args) {
   546             return failure(diags.fragment(msg, args));
   547         }
   549         FunctionDescriptorLookupError failure(JCDiagnostic diag) {
   550             return functionDescriptorLookupError.setMessage(diag);
   551         }
   552     }
   554     private DescriptorCache descCache = new DescriptorCache();
   556     /**
   557      * Find the method descriptor associated to this class symbol - if the
   558      * symbol 'origin' is not a functional interface, an exception is thrown.
   559      */
   560     public Symbol findDescriptorSymbol(TypeSymbol origin) throws FunctionDescriptorLookupError {
   561         return descCache.get(origin).getSymbol();
   562     }
   564     /**
   565      * Find the type of the method descriptor associated to this class symbol -
   566      * if the symbol 'origin' is not a functional interface, an exception is thrown.
   567      */
   568     public Type findDescriptorType(Type origin) throws FunctionDescriptorLookupError {
   569         return descCache.get(origin.tsym).getType(origin);
   570     }
   572     /**
   573      * Is given type a functional interface?
   574      */
   575     public boolean isFunctionalInterface(TypeSymbol tsym) {
   576         try {
   577             findDescriptorSymbol(tsym);
   578             return true;
   579         } catch (FunctionDescriptorLookupError ex) {
   580             return false;
   581         }
   582     }
   584     public boolean isFunctionalInterface(Type site) {
   585         try {
   586             findDescriptorType(site);
   587             return true;
   588         } catch (FunctionDescriptorLookupError ex) {
   589             return false;
   590         }
   591     }
   593     public Type removeWildcards(Type site) {
   594         Type capturedSite = capture(site);
   595         if (capturedSite != site) {
   596             Type formalInterface = site.tsym.type;
   597             ListBuffer<Type> typeargs = new ListBuffer<>();
   598             List<Type> actualTypeargs = site.getTypeArguments();
   599             List<Type> capturedTypeargs = capturedSite.getTypeArguments();
   600             //simply replace the wildcards with its bound
   601             for (Type t : formalInterface.getTypeArguments()) {
   602                 if (actualTypeargs.head.hasTag(WILDCARD)) {
   603                     WildcardType wt = (WildcardType)actualTypeargs.head.unannotatedType();
   604                     Type bound;
   605                     switch (wt.kind) {
   606                         case EXTENDS:
   607                         case UNBOUND:
   608                             CapturedType capVar = (CapturedType)capturedTypeargs.head.unannotatedType();
   609                             //use declared bound if it doesn't depend on formal type-args
   610                             bound = capVar.bound.containsAny(capturedSite.getTypeArguments()) ?
   611                                     wt.type : capVar.bound;
   612                             break;
   613                         default:
   614                             bound = wt.type;
   615                     }
   616                     typeargs.append(bound);
   617                 } else {
   618                     typeargs.append(actualTypeargs.head);
   619                 }
   620                 actualTypeargs = actualTypeargs.tail;
   621                 capturedTypeargs = capturedTypeargs.tail;
   622             }
   623             return subst(formalInterface, formalInterface.getTypeArguments(), typeargs.toList());
   624         } else {
   625             return site;
   626         }
   627     }
   629     /**
   630      * Create a symbol for a class that implements a given functional interface
   631      * and overrides its functional descriptor. This routine is used for two
   632      * main purposes: (i) checking well-formedness of a functional interface;
   633      * (ii) perform functional interface bridge calculation.
   634      */
   635     public ClassSymbol makeFunctionalInterfaceClass(Env<AttrContext> env, Name name, List<Type> targets, long cflags) {
   636         if (targets.isEmpty() || !isFunctionalInterface(targets.head)) {
   637             return null;
   638         }
   639         Symbol descSym = findDescriptorSymbol(targets.head.tsym);
   640         Type descType = findDescriptorType(targets.head);
   641         ClassSymbol csym = new ClassSymbol(cflags, name, env.enclClass.sym.outermostClass());
   642         csym.completer = null;
   643         csym.members_field = new Scope(csym);
   644         MethodSymbol instDescSym = new MethodSymbol(descSym.flags(), descSym.name, descType, csym);
   645         csym.members_field.enter(instDescSym);
   646         Type.ClassType ctype = new Type.ClassType(Type.noType, List.<Type>nil(), csym);
   647         ctype.supertype_field = syms.objectType;
   648         ctype.interfaces_field = targets;
   649         csym.type = ctype;
   650         csym.sourcefile = ((ClassSymbol)csym.owner).sourcefile;
   651         return csym;
   652     }
   654     /**
   655      * Find the minimal set of methods that are overridden by the functional
   656      * descriptor in 'origin'. All returned methods are assumed to have different
   657      * erased signatures.
   658      */
   659     public List<Symbol> functionalInterfaceBridges(TypeSymbol origin) {
   660         Assert.check(isFunctionalInterface(origin));
   661         Symbol descSym = findDescriptorSymbol(origin);
   662         CompoundScope members = membersClosure(origin.type, false);
   663         ListBuffer<Symbol> overridden = new ListBuffer<>();
   664         outer: for (Symbol m2 : members.getElementsByName(descSym.name, bridgeFilter)) {
   665             if (m2 == descSym) continue;
   666             else if (descSym.overrides(m2, origin, Types.this, false)) {
   667                 for (Symbol m3 : overridden) {
   668                     if (isSameType(m3.erasure(Types.this), m2.erasure(Types.this)) ||
   669                             (m3.overrides(m2, origin, Types.this, false) &&
   670                             (pendingBridges((ClassSymbol)origin, m3.enclClass()) ||
   671                             (((MethodSymbol)m2).binaryImplementation((ClassSymbol)m3.owner, Types.this) != null)))) {
   672                         continue outer;
   673                     }
   674                 }
   675                 overridden.add(m2);
   676             }
   677         }
   678         return overridden.toList();
   679     }
   680     //where
   681         private Filter<Symbol> bridgeFilter = new Filter<Symbol>() {
   682             public boolean accepts(Symbol t) {
   683                 return t.kind == Kinds.MTH &&
   684                         t.name != names.init &&
   685                         t.name != names.clinit &&
   686                         (t.flags() & SYNTHETIC) == 0;
   687             }
   688         };
   689         private boolean pendingBridges(ClassSymbol origin, TypeSymbol s) {
   690             //a symbol will be completed from a classfile if (a) symbol has
   691             //an associated file object with CLASS kind and (b) the symbol has
   692             //not been entered
   693             if (origin.classfile != null &&
   694                     origin.classfile.getKind() == JavaFileObject.Kind.CLASS &&
   695                     enter.getEnv(origin) == null) {
   696                 return false;
   697             }
   698             if (origin == s) {
   699                 return true;
   700             }
   701             for (Type t : interfaces(origin.type)) {
   702                 if (pendingBridges((ClassSymbol)t.tsym, s)) {
   703                     return true;
   704                 }
   705             }
   706             return false;
   707         }
   708     // </editor-fold>
   710    /**
   711     * Scope filter used to skip methods that should be ignored (such as methods
   712     * overridden by j.l.Object) during function interface conversion interface check
   713     */
   714     class DescriptorFilter implements Filter<Symbol> {
   716        TypeSymbol origin;
   718        DescriptorFilter(TypeSymbol origin) {
   719            this.origin = origin;
   720        }
   722        @Override
   723        public boolean accepts(Symbol sym) {
   724            return sym.kind == Kinds.MTH &&
   725                    (sym.flags() & (ABSTRACT | DEFAULT)) == ABSTRACT &&
   726                    !overridesObjectMethod(origin, sym) &&
   727                    (interfaceCandidates(origin.type, (MethodSymbol)sym).head.flags() & DEFAULT) == 0;
   728        }
   729     };
   731     // <editor-fold defaultstate="collapsed" desc="isSubtype">
   732     /**
   733      * Is t an unchecked subtype of s?
   734      */
   735     public boolean isSubtypeUnchecked(Type t, Type s) {
   736         return isSubtypeUnchecked(t, s, noWarnings);
   737     }
   738     /**
   739      * Is t an unchecked subtype of s?
   740      */
   741     public boolean isSubtypeUnchecked(Type t, Type s, Warner warn) {
   742         boolean result = isSubtypeUncheckedInternal(t, s, warn);
   743         if (result) {
   744             checkUnsafeVarargsConversion(t, s, warn);
   745         }
   746         return result;
   747     }
   748     //where
   749         private boolean isSubtypeUncheckedInternal(Type t, Type s, Warner warn) {
   750             if (t.hasTag(ARRAY) && s.hasTag(ARRAY)) {
   751                 t = t.unannotatedType();
   752                 s = s.unannotatedType();
   753                 if (((ArrayType)t).elemtype.isPrimitive()) {
   754                     return isSameType(elemtype(t), elemtype(s));
   755                 } else {
   756                     return isSubtypeUnchecked(elemtype(t), elemtype(s), warn);
   757                 }
   758             } else if (isSubtype(t, s)) {
   759                 return true;
   760             } else if (t.hasTag(TYPEVAR)) {
   761                 return isSubtypeUnchecked(t.getUpperBound(), s, warn);
   762             } else if (!s.isRaw()) {
   763                 Type t2 = asSuper(t, s.tsym);
   764                 if (t2 != null && t2.isRaw()) {
   765                     if (isReifiable(s)) {
   766                         warn.silentWarn(LintCategory.UNCHECKED);
   767                     } else {
   768                         warn.warn(LintCategory.UNCHECKED);
   769                     }
   770                     return true;
   771                 }
   772             }
   773             return false;
   774         }
   776         private void checkUnsafeVarargsConversion(Type t, Type s, Warner warn) {
   777             if (!t.hasTag(ARRAY) || isReifiable(t)) {
   778                 return;
   779             }
   780             t = t.unannotatedType();
   781             s = s.unannotatedType();
   782             ArrayType from = (ArrayType)t;
   783             boolean shouldWarn = false;
   784             switch (s.getTag()) {
   785                 case ARRAY:
   786                     ArrayType to = (ArrayType)s;
   787                     shouldWarn = from.isVarargs() &&
   788                             !to.isVarargs() &&
   789                             !isReifiable(from);
   790                     break;
   791                 case CLASS:
   792                     shouldWarn = from.isVarargs();
   793                     break;
   794             }
   795             if (shouldWarn) {
   796                 warn.warn(LintCategory.VARARGS);
   797             }
   798         }
   800     /**
   801      * Is t a subtype of s?<br>
   802      * (not defined for Method and ForAll types)
   803      */
   804     final public boolean isSubtype(Type t, Type s) {
   805         return isSubtype(t, s, true);
   806     }
   807     final public boolean isSubtypeNoCapture(Type t, Type s) {
   808         return isSubtype(t, s, false);
   809     }
   810     public boolean isSubtype(Type t, Type s, boolean capture) {
   811         if (t == s)
   812             return true;
   814         t = t.unannotatedType();
   815         s = s.unannotatedType();
   817         if (t == s)
   818             return true;
   820         if (s.isPartial())
   821             return isSuperType(s, t);
   823         if (s.isCompound()) {
   824             for (Type s2 : interfaces(s).prepend(supertype(s))) {
   825                 if (!isSubtype(t, s2, capture))
   826                     return false;
   827             }
   828             return true;
   829         }
   831         // Generally, if 's' is a type variable, recur on lower bound; but
   832         // for inference variables and intersections, we need to keep 's'
   833         // (see JLS 4.10.2 for intersections and 18.2.3 for inference vars)
   834         if (!t.hasTag(UNDETVAR) && !t.isCompound()) {
   835             // TODO: JDK-8039198, bounds checking sometimes passes in a wildcard as s
   836             Type lower = cvarLowerBound(wildLowerBound(s));
   837             if (s != lower)
   838                 return isSubtype(capture ? capture(t) : t, lower, false);
   839         }
   841         return isSubtype.visit(capture ? capture(t) : t, s);
   842     }
   843     // where
   844         private TypeRelation isSubtype = new TypeRelation()
   845         {
   846             @Override
   847             public Boolean visitType(Type t, Type s) {
   848                 switch (t.getTag()) {
   849                  case BYTE:
   850                      return (!s.hasTag(CHAR) && t.getTag().isSubRangeOf(s.getTag()));
   851                  case CHAR:
   852                      return (!s.hasTag(SHORT) && t.getTag().isSubRangeOf(s.getTag()));
   853                  case SHORT: case INT: case LONG:
   854                  case FLOAT: case DOUBLE:
   855                      return t.getTag().isSubRangeOf(s.getTag());
   856                  case BOOLEAN: case VOID:
   857                      return t.hasTag(s.getTag());
   858                  case TYPEVAR:
   859                      return isSubtypeNoCapture(t.getUpperBound(), s);
   860                  case BOT:
   861                      return
   862                          s.hasTag(BOT) || s.hasTag(CLASS) ||
   863                          s.hasTag(ARRAY) || s.hasTag(TYPEVAR);
   864                  case WILDCARD: //we shouldn't be here - avoids crash (see 7034495)
   865                  case NONE:
   866                      return false;
   867                  default:
   868                      throw new AssertionError("isSubtype " + t.getTag());
   869                  }
   870             }
   872             private Set<TypePair> cache = new HashSet<TypePair>();
   874             private boolean containsTypeRecursive(Type t, Type s) {
   875                 TypePair pair = new TypePair(t, s);
   876                 if (cache.add(pair)) {
   877                     try {
   878                         return containsType(t.getTypeArguments(),
   879                                             s.getTypeArguments());
   880                     } finally {
   881                         cache.remove(pair);
   882                     }
   883                 } else {
   884                     return containsType(t.getTypeArguments(),
   885                                         rewriteSupers(s).getTypeArguments());
   886                 }
   887             }
   889             private Type rewriteSupers(Type t) {
   890                 if (!t.isParameterized())
   891                     return t;
   892                 ListBuffer<Type> from = new ListBuffer<>();
   893                 ListBuffer<Type> to = new ListBuffer<>();
   894                 adaptSelf(t, from, to);
   895                 if (from.isEmpty())
   896                     return t;
   897                 ListBuffer<Type> rewrite = new ListBuffer<>();
   898                 boolean changed = false;
   899                 for (Type orig : to.toList()) {
   900                     Type s = rewriteSupers(orig);
   901                     if (s.isSuperBound() && !s.isExtendsBound()) {
   902                         s = new WildcardType(syms.objectType,
   903                                              BoundKind.UNBOUND,
   904                                              syms.boundClass);
   905                         changed = true;
   906                     } else if (s != orig) {
   907                         s = new WildcardType(upperBound(s),
   908                                              BoundKind.EXTENDS,
   909                                              syms.boundClass);
   910                         changed = true;
   911                     }
   912                     rewrite.append(s);
   913                 }
   914                 if (changed)
   915                     return subst(t.tsym.type, from.toList(), rewrite.toList());
   916                 else
   917                     return t;
   918             }
   920             @Override
   921             public Boolean visitClassType(ClassType t, Type s) {
   922                 Type sup = asSuper(t, s.tsym);
   923                 if (sup == null) return false;
   924                 // If t is an intersection, sup might not be a class type
   925                 if (!sup.hasTag(CLASS)) return isSubtypeNoCapture(sup, s);
   926                 return sup.tsym == s.tsym
   927                      // Check type variable containment
   928                     && (!s.isParameterized() || containsTypeRecursive(s, sup))
   929                     && isSubtypeNoCapture(sup.getEnclosingType(),
   930                                           s.getEnclosingType());
   931             }
   933             @Override
   934             public Boolean visitArrayType(ArrayType t, Type s) {
   935                 if (s.hasTag(ARRAY)) {
   936                     if (t.elemtype.isPrimitive())
   937                         return isSameType(t.elemtype, elemtype(s));
   938                     else
   939                         return isSubtypeNoCapture(t.elemtype, elemtype(s));
   940                 }
   942                 if (s.hasTag(CLASS)) {
   943                     Name sname = s.tsym.getQualifiedName();
   944                     return sname == names.java_lang_Object
   945                         || sname == names.java_lang_Cloneable
   946                         || sname == names.java_io_Serializable;
   947                 }
   949                 return false;
   950             }
   952             @Override
   953             public Boolean visitUndetVar(UndetVar t, Type s) {
   954                 //todo: test against origin needed? or replace with substitution?
   955                 if (t == s || t.qtype == s || s.hasTag(ERROR) || s.hasTag(UNKNOWN)) {
   956                     return true;
   957                 } else if (s.hasTag(BOT)) {
   958                     //if 's' is 'null' there's no instantiated type U for which
   959                     //U <: s (but 'null' itself, which is not a valid type)
   960                     return false;
   961                 }
   963                 t.addBound(InferenceBound.UPPER, s, Types.this);
   964                 return true;
   965             }
   967             @Override
   968             public Boolean visitErrorType(ErrorType t, Type s) {
   969                 return true;
   970             }
   971         };
   973     /**
   974      * Is t a subtype of every type in given list `ts'?<br>
   975      * (not defined for Method and ForAll types)<br>
   976      * Allows unchecked conversions.
   977      */
   978     public boolean isSubtypeUnchecked(Type t, List<Type> ts, Warner warn) {
   979         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
   980             if (!isSubtypeUnchecked(t, l.head, warn))
   981                 return false;
   982         return true;
   983     }
   985     /**
   986      * Are corresponding elements of ts subtypes of ss?  If lists are
   987      * of different length, return false.
   988      */
   989     public boolean isSubtypes(List<Type> ts, List<Type> ss) {
   990         while (ts.tail != null && ss.tail != null
   991                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   992                isSubtype(ts.head, ss.head)) {
   993             ts = ts.tail;
   994             ss = ss.tail;
   995         }
   996         return ts.tail == null && ss.tail == null;
   997         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   998     }
  1000     /**
  1001      * Are corresponding elements of ts subtypes of ss, allowing
  1002      * unchecked conversions?  If lists are of different length,
  1003      * return false.
  1004      **/
  1005     public boolean isSubtypesUnchecked(List<Type> ts, List<Type> ss, Warner warn) {
  1006         while (ts.tail != null && ss.tail != null
  1007                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
  1008                isSubtypeUnchecked(ts.head, ss.head, warn)) {
  1009             ts = ts.tail;
  1010             ss = ss.tail;
  1012         return ts.tail == null && ss.tail == null;
  1013         /*inlined: ts.isEmpty() && ss.isEmpty();*/
  1015     // </editor-fold>
  1017     // <editor-fold defaultstate="collapsed" desc="isSuperType">
  1018     /**
  1019      * Is t a supertype of s?
  1020      */
  1021     public boolean isSuperType(Type t, Type s) {
  1022         switch (t.getTag()) {
  1023         case ERROR:
  1024             return true;
  1025         case UNDETVAR: {
  1026             UndetVar undet = (UndetVar)t;
  1027             if (t == s ||
  1028                 undet.qtype == s ||
  1029                 s.hasTag(ERROR) ||
  1030                 s.hasTag(BOT)) {
  1031                 return true;
  1033             undet.addBound(InferenceBound.LOWER, s, this);
  1034             return true;
  1036         default:
  1037             return isSubtype(s, t);
  1040     // </editor-fold>
  1042     // <editor-fold defaultstate="collapsed" desc="isSameType">
  1043     /**
  1044      * Are corresponding elements of the lists the same type?  If
  1045      * lists are of different length, return false.
  1046      */
  1047     public boolean isSameTypes(List<Type> ts, List<Type> ss) {
  1048         return isSameTypes(ts, ss, false);
  1050     public boolean isSameTypes(List<Type> ts, List<Type> ss, boolean strict) {
  1051         while (ts.tail != null && ss.tail != null
  1052                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
  1053                isSameType(ts.head, ss.head, strict)) {
  1054             ts = ts.tail;
  1055             ss = ss.tail;
  1057         return ts.tail == null && ss.tail == null;
  1058         /*inlined: ts.isEmpty() && ss.isEmpty();*/
  1061     /**
  1062     * A polymorphic signature method (JLS SE 7, 8.4.1) is a method that
  1063     * (i) is declared in the java.lang.invoke.MethodHandle class, (ii) takes
  1064     * a single variable arity parameter (iii) whose declared type is Object[],
  1065     * (iv) has a return type of Object and (v) is native.
  1066     */
  1067    public boolean isSignaturePolymorphic(MethodSymbol msym) {
  1068        List<Type> argtypes = msym.type.getParameterTypes();
  1069        return (msym.flags_field & NATIVE) != 0 &&
  1070                msym.owner == syms.methodHandleType.tsym &&
  1071                argtypes.tail.tail == null &&
  1072                argtypes.head.hasTag(TypeTag.ARRAY) &&
  1073                msym.type.getReturnType().tsym == syms.objectType.tsym &&
  1074                ((ArrayType)argtypes.head).elemtype.tsym == syms.objectType.tsym;
  1077     /**
  1078      * Is t the same type as s?
  1079      */
  1080     public boolean isSameType(Type t, Type s) {
  1081         return isSameType(t, s, false);
  1083     public boolean isSameType(Type t, Type s, boolean strict) {
  1084         return strict ?
  1085                 isSameTypeStrict.visit(t, s) :
  1086                 isSameTypeLoose.visit(t, s);
  1088     public boolean isSameAnnotatedType(Type t, Type s) {
  1089         return isSameAnnotatedType.visit(t, s);
  1091     // where
  1092         abstract class SameTypeVisitor extends TypeRelation {
  1094             public Boolean visitType(Type t, Type s) {
  1095                 if (t == s)
  1096                     return true;
  1098                 if (s.isPartial())
  1099                     return visit(s, t);
  1101                 switch (t.getTag()) {
  1102                 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
  1103                 case DOUBLE: case BOOLEAN: case VOID: case BOT: case NONE:
  1104                     return t.hasTag(s.getTag());
  1105                 case TYPEVAR: {
  1106                     if (s.hasTag(TYPEVAR)) {
  1107                         //type-substitution does not preserve type-var types
  1108                         //check that type var symbols and bounds are indeed the same
  1109                         return sameTypeVars((TypeVar)t.unannotatedType(), (TypeVar)s.unannotatedType());
  1111                     else {
  1112                         //special case for s == ? super X, where upper(s) = u
  1113                         //check that u == t, where u has been set by Type.withTypeVar
  1114                         return s.isSuperBound() &&
  1115                                 !s.isExtendsBound() &&
  1116                                 visit(t, upperBound(s));
  1119                 default:
  1120                     throw new AssertionError("isSameType " + t.getTag());
  1124             abstract boolean sameTypeVars(TypeVar tv1, TypeVar tv2);
  1126             @Override
  1127             public Boolean visitWildcardType(WildcardType t, Type s) {
  1128                 if (s.isPartial())
  1129                     return visit(s, t);
  1130                 else
  1131                     return false;
  1134             @Override
  1135             public Boolean visitClassType(ClassType t, Type s) {
  1136                 if (t == s)
  1137                     return true;
  1139                 if (s.isPartial())
  1140                     return visit(s, t);
  1142                 if (s.isSuperBound() && !s.isExtendsBound())
  1143                     return visit(t, upperBound(s)) && visit(t, wildLowerBound(s));
  1145                 if (t.isCompound() && s.isCompound()) {
  1146                     if (!visit(supertype(t), supertype(s)))
  1147                         return false;
  1149                     HashSet<UniqueType> set = new HashSet<UniqueType>();
  1150                     for (Type x : interfaces(t))
  1151                         set.add(new UniqueType(x.unannotatedType(), Types.this));
  1152                     for (Type x : interfaces(s)) {
  1153                         if (!set.remove(new UniqueType(x.unannotatedType(), Types.this)))
  1154                             return false;
  1156                     return (set.isEmpty());
  1158                 return t.tsym == s.tsym
  1159                     && visit(t.getEnclosingType(), s.getEnclosingType())
  1160                     && containsTypes(t.getTypeArguments(), s.getTypeArguments());
  1163             abstract protected boolean containsTypes(List<Type> ts1, List<Type> ts2);
  1165             @Override
  1166             public Boolean visitArrayType(ArrayType t, Type s) {
  1167                 if (t == s)
  1168                     return true;
  1170                 if (s.isPartial())
  1171                     return visit(s, t);
  1173                 return s.hasTag(ARRAY)
  1174                     && containsTypeEquivalent(t.elemtype, elemtype(s));
  1177             @Override
  1178             public Boolean visitMethodType(MethodType t, Type s) {
  1179                 // isSameType for methods does not take thrown
  1180                 // exceptions into account!
  1181                 return hasSameArgs(t, s) && visit(t.getReturnType(), s.getReturnType());
  1184             @Override
  1185             public Boolean visitPackageType(PackageType t, Type s) {
  1186                 return t == s;
  1189             @Override
  1190             public Boolean visitForAll(ForAll t, Type s) {
  1191                 if (!s.hasTag(FORALL)) {
  1192                     return false;
  1195                 ForAll forAll = (ForAll)s;
  1196                 return hasSameBounds(t, forAll)
  1197                     && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
  1200             @Override
  1201             public Boolean visitUndetVar(UndetVar t, Type s) {
  1202                 if (s.hasTag(WILDCARD)) {
  1203                     // FIXME, this might be leftovers from before capture conversion
  1204                     return false;
  1207                 if (t == s || t.qtype == s || s.hasTag(ERROR) || s.hasTag(UNKNOWN)) {
  1208                     return true;
  1211                 t.addBound(InferenceBound.EQ, s, Types.this);
  1213                 return true;
  1216             @Override
  1217             public Boolean visitErrorType(ErrorType t, Type s) {
  1218                 return true;
  1222         /**
  1223          * Standard type-equality relation - type variables are considered
  1224          * equals if they share the same type symbol.
  1225          */
  1226         TypeRelation isSameTypeLoose = new LooseSameTypeVisitor();
  1228         private class LooseSameTypeVisitor extends SameTypeVisitor {
  1229             @Override
  1230             boolean sameTypeVars(TypeVar tv1, TypeVar tv2) {
  1231                 return tv1.tsym == tv2.tsym && visit(tv1.getUpperBound(), tv2.getUpperBound());
  1233             @Override
  1234             protected boolean containsTypes(List<Type> ts1, List<Type> ts2) {
  1235                 return containsTypeEquivalent(ts1, ts2);
  1237         };
  1239         /**
  1240          * Strict type-equality relation - type variables are considered
  1241          * equals if they share the same object identity.
  1242          */
  1243         TypeRelation isSameTypeStrict = new SameTypeVisitor() {
  1244             @Override
  1245             boolean sameTypeVars(TypeVar tv1, TypeVar tv2) {
  1246                 return tv1 == tv2;
  1248             @Override
  1249             protected boolean containsTypes(List<Type> ts1, List<Type> ts2) {
  1250                 return isSameTypes(ts1, ts2, true);
  1253             @Override
  1254             public Boolean visitWildcardType(WildcardType t, Type s) {
  1255                 if (!s.hasTag(WILDCARD)) {
  1256                     return false;
  1257                 } else {
  1258                     WildcardType t2 = (WildcardType)s.unannotatedType();
  1259                     return t.kind == t2.kind &&
  1260                             isSameType(t.type, t2.type, true);
  1263         };
  1265         /**
  1266          * A version of LooseSameTypeVisitor that takes AnnotatedTypes
  1267          * into account.
  1268          */
  1269         TypeRelation isSameAnnotatedType = new LooseSameTypeVisitor() {
  1270             @Override
  1271             public Boolean visitAnnotatedType(AnnotatedType t, Type s) {
  1272                 if (!s.isAnnotated())
  1273                     return false;
  1274                 if (!t.getAnnotationMirrors().containsAll(s.getAnnotationMirrors()))
  1275                     return false;
  1276                 if (!s.getAnnotationMirrors().containsAll(t.getAnnotationMirrors()))
  1277                     return false;
  1278                 return visit(t.unannotatedType(), s);
  1280         };
  1281     // </editor-fold>
  1283     // <editor-fold defaultstate="collapsed" desc="Contains Type">
  1284     public boolean containedBy(Type t, Type s) {
  1285         switch (t.getTag()) {
  1286         case UNDETVAR:
  1287             if (s.hasTag(WILDCARD)) {
  1288                 UndetVar undetvar = (UndetVar)t;
  1289                 WildcardType wt = (WildcardType)s.unannotatedType();
  1290                 switch(wt.kind) {
  1291                     case UNBOUND: //similar to ? extends Object
  1292                     case EXTENDS: {
  1293                         Type bound = upperBound(s);
  1294                         undetvar.addBound(InferenceBound.UPPER, bound, this);
  1295                         break;
  1297                     case SUPER: {
  1298                         Type bound = wildLowerBound(s);
  1299                         undetvar.addBound(InferenceBound.LOWER, bound, this);
  1300                         break;
  1303                 return true;
  1304             } else {
  1305                 return isSameType(t, s);
  1307         case ERROR:
  1308             return true;
  1309         default:
  1310             return containsType(s, t);
  1314     boolean containsType(List<Type> ts, List<Type> ss) {
  1315         while (ts.nonEmpty() && ss.nonEmpty()
  1316                && containsType(ts.head, ss.head)) {
  1317             ts = ts.tail;
  1318             ss = ss.tail;
  1320         return ts.isEmpty() && ss.isEmpty();
  1323     /**
  1324      * Check if t contains s.
  1326      * <p>T contains S if:
  1328      * <p>{@code L(T) <: L(S) && U(S) <: U(T)}
  1330      * <p>This relation is only used by ClassType.isSubtype(), that
  1331      * is,
  1333      * <p>{@code C<S> <: C<T> if T contains S.}
  1335      * <p>Because of F-bounds, this relation can lead to infinite
  1336      * recursion.  Thus we must somehow break that recursion.  Notice
  1337      * that containsType() is only called from ClassType.isSubtype().
  1338      * Since the arguments have already been checked against their
  1339      * bounds, we know:
  1341      * <p>{@code U(S) <: U(T) if T is "super" bound (U(T) *is* the bound)}
  1343      * <p>{@code L(T) <: L(S) if T is "extends" bound (L(T) is bottom)}
  1345      * @param t a type
  1346      * @param s a type
  1347      */
  1348     public boolean containsType(Type t, Type s) {
  1349         return containsType.visit(t, s);
  1351     // where
  1352         private TypeRelation containsType = new TypeRelation() {
  1354             private Type U(Type t) {
  1355                 while (t.hasTag(WILDCARD)) {
  1356                     WildcardType w = (WildcardType)t.unannotatedType();
  1357                     if (w.isSuperBound())
  1358                         return w.bound == null ? syms.objectType : w.bound.bound;
  1359                     else
  1360                         t = w.type;
  1362                 return t;
  1365             private Type L(Type t) {
  1366                 while (t.hasTag(WILDCARD)) {
  1367                     WildcardType w = (WildcardType)t.unannotatedType();
  1368                     if (w.isExtendsBound())
  1369                         return syms.botType;
  1370                     else
  1371                         t = w.type;
  1373                 return t;
  1376             public Boolean visitType(Type t, Type s) {
  1377                 if (s.isPartial())
  1378                     return containedBy(s, t);
  1379                 else
  1380                     return isSameType(t, s);
  1383 //            void debugContainsType(WildcardType t, Type s) {
  1384 //                System.err.println();
  1385 //                System.err.format(" does %s contain %s?%n", t, s);
  1386 //                System.err.format(" %s U(%s) <: U(%s) %s = %s%n",
  1387 //                                  upperBound(s), s, t, U(t),
  1388 //                                  t.isSuperBound()
  1389 //                                  || isSubtypeNoCapture(upperBound(s), U(t)));
  1390 //                System.err.format(" %s L(%s) <: L(%s) %s = %s%n",
  1391 //                                  L(t), t, s, wildLowerBound(s),
  1392 //                                  t.isExtendsBound()
  1393 //                                  || isSubtypeNoCapture(L(t), wildLowerBound(s)));
  1394 //                System.err.println();
  1395 //            }
  1397             @Override
  1398             public Boolean visitWildcardType(WildcardType t, Type s) {
  1399                 if (s.isPartial())
  1400                     return containedBy(s, t);
  1401                 else {
  1402 //                    debugContainsType(t, s);
  1403                     return isSameWildcard(t, s)
  1404                         || isCaptureOf(s, t)
  1405                         || ((t.isExtendsBound() || isSubtypeNoCapture(L(t), wildLowerBound(s))) &&
  1406                             (t.isSuperBound() || isSubtypeNoCapture(upperBound(s), U(t))));
  1410             @Override
  1411             public Boolean visitUndetVar(UndetVar t, Type s) {
  1412                 if (!s.hasTag(WILDCARD)) {
  1413                     return isSameType(t, s);
  1414                 } else {
  1415                     return false;
  1419             @Override
  1420             public Boolean visitErrorType(ErrorType t, Type s) {
  1421                 return true;
  1423         };
  1425     public boolean isCaptureOf(Type s, WildcardType t) {
  1426         if (!s.hasTag(TYPEVAR) || !((TypeVar)s.unannotatedType()).isCaptured())
  1427             return false;
  1428         return isSameWildcard(t, ((CapturedType)s.unannotatedType()).wildcard);
  1431     public boolean isSameWildcard(WildcardType t, Type s) {
  1432         if (!s.hasTag(WILDCARD))
  1433             return false;
  1434         WildcardType w = (WildcardType)s.unannotatedType();
  1435         return w.kind == t.kind && w.type == t.type;
  1438     public boolean containsTypeEquivalent(List<Type> ts, List<Type> ss) {
  1439         while (ts.nonEmpty() && ss.nonEmpty()
  1440                && containsTypeEquivalent(ts.head, ss.head)) {
  1441             ts = ts.tail;
  1442             ss = ss.tail;
  1444         return ts.isEmpty() && ss.isEmpty();
  1446     // </editor-fold>
  1448     /**
  1449      * Can t and s be compared for equality?  Any primitive ==
  1450      * primitive or primitive == object comparisons here are an error.
  1451      * Unboxing and correct primitive == primitive comparisons are
  1452      * already dealt with in Attr.visitBinary.
  1454      */
  1455     public boolean isEqualityComparable(Type s, Type t, Warner warn) {
  1456         if (t.isNumeric() && s.isNumeric())
  1457             return true;
  1459         boolean tPrimitive = t.isPrimitive();
  1460         boolean sPrimitive = s.isPrimitive();
  1461         if (!tPrimitive && !sPrimitive) {
  1462             return isCastable(s, t, warn) || isCastable(t, s, warn);
  1463         } else {
  1464             return false;
  1468     // <editor-fold defaultstate="collapsed" desc="isCastable">
  1469     public boolean isCastable(Type t, Type s) {
  1470         return isCastable(t, s, noWarnings);
  1473     /**
  1474      * Is t is castable to s?<br>
  1475      * s is assumed to be an erased type.<br>
  1476      * (not defined for Method and ForAll types).
  1477      */
  1478     public boolean isCastable(Type t, Type s, Warner warn) {
  1479         if (t == s)
  1480             return true;
  1482         if (t.isPrimitive() != s.isPrimitive())
  1483             return allowBoxing && (
  1484                     isConvertible(t, s, warn)
  1485                     || (allowObjectToPrimitiveCast &&
  1486                         s.isPrimitive() &&
  1487                         isSubtype(boxedClass(s).type, t)));
  1488         if (warn != warnStack.head) {
  1489             try {
  1490                 warnStack = warnStack.prepend(warn);
  1491                 checkUnsafeVarargsConversion(t, s, warn);
  1492                 return isCastable.visit(t,s);
  1493             } finally {
  1494                 warnStack = warnStack.tail;
  1496         } else {
  1497             return isCastable.visit(t,s);
  1500     // where
  1501         private TypeRelation isCastable = new TypeRelation() {
  1503             public Boolean visitType(Type t, Type s) {
  1504                 if (s.hasTag(ERROR))
  1505                     return true;
  1507                 switch (t.getTag()) {
  1508                 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
  1509                 case DOUBLE:
  1510                     return s.isNumeric();
  1511                 case BOOLEAN:
  1512                     return s.hasTag(BOOLEAN);
  1513                 case VOID:
  1514                     return false;
  1515                 case BOT:
  1516                     return isSubtype(t, s);
  1517                 default:
  1518                     throw new AssertionError();
  1522             @Override
  1523             public Boolean visitWildcardType(WildcardType t, Type s) {
  1524                 return isCastable(upperBound(t), s, warnStack.head);
  1527             @Override
  1528             public Boolean visitClassType(ClassType t, Type s) {
  1529                 if (s.hasTag(ERROR) || s.hasTag(BOT))
  1530                     return true;
  1532                 if (s.hasTag(TYPEVAR)) {
  1533                     if (isCastable(t, s.getUpperBound(), noWarnings)) {
  1534                         warnStack.head.warn(LintCategory.UNCHECKED);
  1535                         return true;
  1536                     } else {
  1537                         return false;
  1541                 if (t.isCompound() || s.isCompound()) {
  1542                     return !t.isCompound() ?
  1543                             visitIntersectionType((IntersectionClassType)s.unannotatedType(), t, true) :
  1544                             visitIntersectionType((IntersectionClassType)t.unannotatedType(), s, false);
  1547                 if (s.hasTag(CLASS) || s.hasTag(ARRAY)) {
  1548                     boolean upcast;
  1549                     if ((upcast = isSubtype(erasure(t), erasure(s)))
  1550                         || isSubtype(erasure(s), erasure(t))) {
  1551                         if (!upcast && s.hasTag(ARRAY)) {
  1552                             if (!isReifiable(s))
  1553                                 warnStack.head.warn(LintCategory.UNCHECKED);
  1554                             return true;
  1555                         } else if (s.isRaw()) {
  1556                             return true;
  1557                         } else if (t.isRaw()) {
  1558                             if (!isUnbounded(s))
  1559                                 warnStack.head.warn(LintCategory.UNCHECKED);
  1560                             return true;
  1562                         // Assume |a| <: |b|
  1563                         final Type a = upcast ? t : s;
  1564                         final Type b = upcast ? s : t;
  1565                         final boolean HIGH = true;
  1566                         final boolean LOW = false;
  1567                         final boolean DONT_REWRITE_TYPEVARS = false;
  1568                         Type aHigh = rewriteQuantifiers(a, HIGH, DONT_REWRITE_TYPEVARS);
  1569                         Type aLow  = rewriteQuantifiers(a, LOW,  DONT_REWRITE_TYPEVARS);
  1570                         Type bHigh = rewriteQuantifiers(b, HIGH, DONT_REWRITE_TYPEVARS);
  1571                         Type bLow  = rewriteQuantifiers(b, LOW,  DONT_REWRITE_TYPEVARS);
  1572                         Type lowSub = asSub(bLow, aLow.tsym);
  1573                         Type highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
  1574                         if (highSub == null) {
  1575                             final boolean REWRITE_TYPEVARS = true;
  1576                             aHigh = rewriteQuantifiers(a, HIGH, REWRITE_TYPEVARS);
  1577                             aLow  = rewriteQuantifiers(a, LOW,  REWRITE_TYPEVARS);
  1578                             bHigh = rewriteQuantifiers(b, HIGH, REWRITE_TYPEVARS);
  1579                             bLow  = rewriteQuantifiers(b, LOW,  REWRITE_TYPEVARS);
  1580                             lowSub = asSub(bLow, aLow.tsym);
  1581                             highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
  1583                         if (highSub != null) {
  1584                             if (!(a.tsym == highSub.tsym && a.tsym == lowSub.tsym)) {
  1585                                 Assert.error(a.tsym + " != " + highSub.tsym + " != " + lowSub.tsym);
  1587                             if (!disjointTypes(aHigh.allparams(), highSub.allparams())
  1588                                 && !disjointTypes(aHigh.allparams(), lowSub.allparams())
  1589                                 && !disjointTypes(aLow.allparams(), highSub.allparams())
  1590                                 && !disjointTypes(aLow.allparams(), lowSub.allparams())) {
  1591                                 if (upcast ? giveWarning(a, b) :
  1592                                     giveWarning(b, a))
  1593                                     warnStack.head.warn(LintCategory.UNCHECKED);
  1594                                 return true;
  1597                         if (isReifiable(s))
  1598                             return isSubtypeUnchecked(a, b);
  1599                         else
  1600                             return isSubtypeUnchecked(a, b, warnStack.head);
  1603                     // Sidecast
  1604                     if (s.hasTag(CLASS)) {
  1605                         if ((s.tsym.flags() & INTERFACE) != 0) {
  1606                             return ((t.tsym.flags() & FINAL) == 0)
  1607                                 ? sideCast(t, s, warnStack.head)
  1608                                 : sideCastFinal(t, s, warnStack.head);
  1609                         } else if ((t.tsym.flags() & INTERFACE) != 0) {
  1610                             return ((s.tsym.flags() & FINAL) == 0)
  1611                                 ? sideCast(t, s, warnStack.head)
  1612                                 : sideCastFinal(t, s, warnStack.head);
  1613                         } else {
  1614                             // unrelated class types
  1615                             return false;
  1619                 return false;
  1622             boolean visitIntersectionType(IntersectionClassType ict, Type s, boolean reverse) {
  1623                 Warner warn = noWarnings;
  1624                 for (Type c : ict.getComponents()) {
  1625                     warn.clear();
  1626                     if (reverse ? !isCastable(s, c, warn) : !isCastable(c, s, warn))
  1627                         return false;
  1629                 if (warn.hasLint(LintCategory.UNCHECKED))
  1630                     warnStack.head.warn(LintCategory.UNCHECKED);
  1631                 return true;
  1634             @Override
  1635             public Boolean visitArrayType(ArrayType t, Type s) {
  1636                 switch (s.getTag()) {
  1637                 case ERROR:
  1638                 case BOT:
  1639                     return true;
  1640                 case TYPEVAR:
  1641                     if (isCastable(s, t, noWarnings)) {
  1642                         warnStack.head.warn(LintCategory.UNCHECKED);
  1643                         return true;
  1644                     } else {
  1645                         return false;
  1647                 case CLASS:
  1648                     return isSubtype(t, s);
  1649                 case ARRAY:
  1650                     if (elemtype(t).isPrimitive() || elemtype(s).isPrimitive()) {
  1651                         return elemtype(t).hasTag(elemtype(s).getTag());
  1652                     } else {
  1653                         return visit(elemtype(t), elemtype(s));
  1655                 default:
  1656                     return false;
  1660             @Override
  1661             public Boolean visitTypeVar(TypeVar t, Type s) {
  1662                 switch (s.getTag()) {
  1663                 case ERROR:
  1664                 case BOT:
  1665                     return true;
  1666                 case TYPEVAR:
  1667                     if (isSubtype(t, s)) {
  1668                         return true;
  1669                     } else if (isCastable(t.bound, s, noWarnings)) {
  1670                         warnStack.head.warn(LintCategory.UNCHECKED);
  1671                         return true;
  1672                     } else {
  1673                         return false;
  1675                 default:
  1676                     return isCastable(t.bound, s, warnStack.head);
  1680             @Override
  1681             public Boolean visitErrorType(ErrorType t, Type s) {
  1682                 return true;
  1684         };
  1685     // </editor-fold>
  1687     // <editor-fold defaultstate="collapsed" desc="disjointTypes">
  1688     public boolean disjointTypes(List<Type> ts, List<Type> ss) {
  1689         while (ts.tail != null && ss.tail != null) {
  1690             if (disjointType(ts.head, ss.head)) return true;
  1691             ts = ts.tail;
  1692             ss = ss.tail;
  1694         return false;
  1697     /**
  1698      * Two types or wildcards are considered disjoint if it can be
  1699      * proven that no type can be contained in both. It is
  1700      * conservative in that it is allowed to say that two types are
  1701      * not disjoint, even though they actually are.
  1703      * The type {@code C<X>} is castable to {@code C<Y>} exactly if
  1704      * {@code X} and {@code Y} are not disjoint.
  1705      */
  1706     public boolean disjointType(Type t, Type s) {
  1707         return disjointType.visit(t, s);
  1709     // where
  1710         private TypeRelation disjointType = new TypeRelation() {
  1712             private Set<TypePair> cache = new HashSet<TypePair>();
  1714             @Override
  1715             public Boolean visitType(Type t, Type s) {
  1716                 if (s.hasTag(WILDCARD))
  1717                     return visit(s, t);
  1718                 else
  1719                     return notSoftSubtypeRecursive(t, s) || notSoftSubtypeRecursive(s, t);
  1722             private boolean isCastableRecursive(Type t, Type s) {
  1723                 TypePair pair = new TypePair(t, s);
  1724                 if (cache.add(pair)) {
  1725                     try {
  1726                         return Types.this.isCastable(t, s);
  1727                     } finally {
  1728                         cache.remove(pair);
  1730                 } else {
  1731                     return true;
  1735             private boolean notSoftSubtypeRecursive(Type t, Type s) {
  1736                 TypePair pair = new TypePair(t, s);
  1737                 if (cache.add(pair)) {
  1738                     try {
  1739                         return Types.this.notSoftSubtype(t, s);
  1740                     } finally {
  1741                         cache.remove(pair);
  1743                 } else {
  1744                     return false;
  1748             @Override
  1749             public Boolean visitWildcardType(WildcardType t, Type s) {
  1750                 if (t.isUnbound())
  1751                     return false;
  1753                 if (!s.hasTag(WILDCARD)) {
  1754                     if (t.isExtendsBound())
  1755                         return notSoftSubtypeRecursive(s, t.type);
  1756                     else
  1757                         return notSoftSubtypeRecursive(t.type, s);
  1760                 if (s.isUnbound())
  1761                     return false;
  1763                 if (t.isExtendsBound()) {
  1764                     if (s.isExtendsBound())
  1765                         return !isCastableRecursive(t.type, upperBound(s));
  1766                     else if (s.isSuperBound())
  1767                         return notSoftSubtypeRecursive(wildLowerBound(s), t.type);
  1768                 } else if (t.isSuperBound()) {
  1769                     if (s.isExtendsBound())
  1770                         return notSoftSubtypeRecursive(t.type, upperBound(s));
  1772                 return false;
  1774         };
  1775     // </editor-fold>
  1777     // <editor-fold defaultstate="collapsed" desc="cvarLowerBounds">
  1778     public List<Type> cvarLowerBounds(List<Type> ts) {
  1779         return map(ts, cvarLowerBoundMapping);
  1781     private final Mapping cvarLowerBoundMapping = new Mapping("cvarLowerBound") {
  1782             public Type apply(Type t) {
  1783                 return cvarLowerBound(t);
  1785         };
  1786     // </editor-fold>
  1788     // <editor-fold defaultstate="collapsed" desc="notSoftSubtype">
  1789     /**
  1790      * This relation answers the question: is impossible that
  1791      * something of type `t' can be a subtype of `s'? This is
  1792      * different from the question "is `t' not a subtype of `s'?"
  1793      * when type variables are involved: Integer is not a subtype of T
  1794      * where {@code <T extends Number>} but it is not true that Integer cannot
  1795      * possibly be a subtype of T.
  1796      */
  1797     public boolean notSoftSubtype(Type t, Type s) {
  1798         if (t == s) return false;
  1799         if (t.hasTag(TYPEVAR)) {
  1800             TypeVar tv = (TypeVar) t;
  1801             return !isCastable(tv.bound,
  1802                                relaxBound(s),
  1803                                noWarnings);
  1805         if (!s.hasTag(WILDCARD))
  1806             s = upperBound(s);
  1808         return !isSubtype(t, relaxBound(s));
  1811     private Type relaxBound(Type t) {
  1812         if (t.hasTag(TYPEVAR)) {
  1813             while (t.hasTag(TYPEVAR))
  1814                 t = t.getUpperBound();
  1815             t = rewriteQuantifiers(t, true, true);
  1817         return t;
  1819     // </editor-fold>
  1821     // <editor-fold defaultstate="collapsed" desc="isReifiable">
  1822     public boolean isReifiable(Type t) {
  1823         return isReifiable.visit(t);
  1825     // where
  1826         private UnaryVisitor<Boolean> isReifiable = new UnaryVisitor<Boolean>() {
  1828             public Boolean visitType(Type t, Void ignored) {
  1829                 return true;
  1832             @Override
  1833             public Boolean visitClassType(ClassType t, Void ignored) {
  1834                 if (t.isCompound())
  1835                     return false;
  1836                 else {
  1837                     if (!t.isParameterized())
  1838                         return true;
  1840                     for (Type param : t.allparams()) {
  1841                         if (!param.isUnbound())
  1842                             return false;
  1844                     return true;
  1848             @Override
  1849             public Boolean visitArrayType(ArrayType t, Void ignored) {
  1850                 return visit(t.elemtype);
  1853             @Override
  1854             public Boolean visitTypeVar(TypeVar t, Void ignored) {
  1855                 return false;
  1857         };
  1858     // </editor-fold>
  1860     // <editor-fold defaultstate="collapsed" desc="Array Utils">
  1861     public boolean isArray(Type t) {
  1862         while (t.hasTag(WILDCARD))
  1863             t = upperBound(t);
  1864         return t.hasTag(ARRAY);
  1867     /**
  1868      * The element type of an array.
  1869      */
  1870     public Type elemtype(Type t) {
  1871         switch (t.getTag()) {
  1872         case WILDCARD:
  1873             return elemtype(upperBound(t));
  1874         case ARRAY:
  1875             t = t.unannotatedType();
  1876             return ((ArrayType)t).elemtype;
  1877         case FORALL:
  1878             return elemtype(((ForAll)t).qtype);
  1879         case ERROR:
  1880             return t;
  1881         default:
  1882             return null;
  1886     public Type elemtypeOrType(Type t) {
  1887         Type elemtype = elemtype(t);
  1888         return elemtype != null ?
  1889             elemtype :
  1890             t;
  1893     /**
  1894      * Mapping to take element type of an arraytype
  1895      */
  1896     private Mapping elemTypeFun = new Mapping ("elemTypeFun") {
  1897         public Type apply(Type t) { return elemtype(t); }
  1898     };
  1900     /**
  1901      * The number of dimensions of an array type.
  1902      */
  1903     public int dimensions(Type t) {
  1904         int result = 0;
  1905         while (t.hasTag(ARRAY)) {
  1906             result++;
  1907             t = elemtype(t);
  1909         return result;
  1912     /**
  1913      * Returns an ArrayType with the component type t
  1915      * @param t The component type of the ArrayType
  1916      * @return the ArrayType for the given component
  1917      */
  1918     public ArrayType makeArrayType(Type t) {
  1919         if (t.hasTag(VOID) || t.hasTag(PACKAGE)) {
  1920             Assert.error("Type t must not be a VOID or PACKAGE type, " + t.toString());
  1922         return new ArrayType(t, syms.arrayClass);
  1924     // </editor-fold>
  1926     // <editor-fold defaultstate="collapsed" desc="asSuper">
  1927     /**
  1928      * Return the (most specific) base type of t that starts with the
  1929      * given symbol.  If none exists, return null.
  1931      * @param t a type
  1932      * @param sym a symbol
  1933      */
  1934     public Type asSuper(Type t, Symbol sym) {
  1935         /* Some examples:
  1937          * (Enum<E>, Comparable) => Comparable<E>
  1938          * (c.s.s.d.AttributeTree.ValueKind, Enum) => Enum<c.s.s.d.AttributeTree.ValueKind>
  1939          * (c.s.s.t.ExpressionTree, c.s.s.t.Tree) => c.s.s.t.Tree
  1940          * (j.u.List<capture#160 of ? extends c.s.s.d.DocTree>, Iterable) =>
  1941          *     Iterable<capture#160 of ? extends c.s.s.d.DocTree>
  1942          */
  1943         if (sym.type == syms.objectType) { //optimization
  1944             return syms.objectType;
  1946         return asSuper.visit(t, sym);
  1948     // where
  1949         private SimpleVisitor<Type,Symbol> asSuper = new SimpleVisitor<Type,Symbol>() {
  1951             public Type visitType(Type t, Symbol sym) {
  1952                 return null;
  1955             @Override
  1956             public Type visitClassType(ClassType t, Symbol sym) {
  1957                 if (t.tsym == sym)
  1958                     return t;
  1960                 Type st = supertype(t);
  1961                 if (st.hasTag(CLASS) || st.hasTag(TYPEVAR)) {
  1962                     Type x = asSuper(st, sym);
  1963                     if (x != null)
  1964                         return x;
  1966                 if ((sym.flags() & INTERFACE) != 0) {
  1967                     for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
  1968                         if (!l.head.hasTag(ERROR)) {
  1969                             Type x = asSuper(l.head, sym);
  1970                             if (x != null)
  1971                                 return x;
  1975                 return null;
  1978             @Override
  1979             public Type visitArrayType(ArrayType t, Symbol sym) {
  1980                 return isSubtype(t, sym.type) ? sym.type : null;
  1983             @Override
  1984             public Type visitTypeVar(TypeVar t, Symbol sym) {
  1985                 if (t.tsym == sym)
  1986                     return t;
  1987                 else
  1988                     return asSuper(t.bound, sym);
  1991             @Override
  1992             public Type visitErrorType(ErrorType t, Symbol sym) {
  1993                 return t;
  1995         };
  1997     /**
  1998      * Return the base type of t or any of its outer types that starts
  1999      * with the given symbol.  If none exists, return null.
  2001      * @param t a type
  2002      * @param sym a symbol
  2003      */
  2004     public Type asOuterSuper(Type t, Symbol sym) {
  2005         switch (t.getTag()) {
  2006         case CLASS:
  2007             do {
  2008                 Type s = asSuper(t, sym);
  2009                 if (s != null) return s;
  2010                 t = t.getEnclosingType();
  2011             } while (t.hasTag(CLASS));
  2012             return null;
  2013         case ARRAY:
  2014             return isSubtype(t, sym.type) ? sym.type : null;
  2015         case TYPEVAR:
  2016             return asSuper(t, sym);
  2017         case ERROR:
  2018             return t;
  2019         default:
  2020             return null;
  2024     /**
  2025      * Return the base type of t or any of its enclosing types that
  2026      * starts with the given symbol.  If none exists, return null.
  2028      * @param t a type
  2029      * @param sym a symbol
  2030      */
  2031     public Type asEnclosingSuper(Type t, Symbol sym) {
  2032         switch (t.getTag()) {
  2033         case CLASS:
  2034             do {
  2035                 Type s = asSuper(t, sym);
  2036                 if (s != null) return s;
  2037                 Type outer = t.getEnclosingType();
  2038                 t = (outer.hasTag(CLASS)) ? outer :
  2039                     (t.tsym.owner.enclClass() != null) ? t.tsym.owner.enclClass().type :
  2040                     Type.noType;
  2041             } while (t.hasTag(CLASS));
  2042             return null;
  2043         case ARRAY:
  2044             return isSubtype(t, sym.type) ? sym.type : null;
  2045         case TYPEVAR:
  2046             return asSuper(t, sym);
  2047         case ERROR:
  2048             return t;
  2049         default:
  2050             return null;
  2053     // </editor-fold>
  2055     // <editor-fold defaultstate="collapsed" desc="memberType">
  2056     /**
  2057      * The type of given symbol, seen as a member of t.
  2059      * @param t a type
  2060      * @param sym a symbol
  2061      */
  2062     public Type memberType(Type t, Symbol sym) {
  2063         return (sym.flags() & STATIC) != 0
  2064             ? sym.type
  2065             : memberType.visit(t, sym);
  2067     // where
  2068         private SimpleVisitor<Type,Symbol> memberType = new SimpleVisitor<Type,Symbol>() {
  2070             public Type visitType(Type t, Symbol sym) {
  2071                 return sym.type;
  2074             @Override
  2075             public Type visitWildcardType(WildcardType t, Symbol sym) {
  2076                 return memberType(upperBound(t), sym);
  2079             @Override
  2080             public Type visitClassType(ClassType t, Symbol sym) {
  2081                 Symbol owner = sym.owner;
  2082                 long flags = sym.flags();
  2083                 if (((flags & STATIC) == 0) && owner.type.isParameterized()) {
  2084                     Type base = asOuterSuper(t, owner);
  2085                     //if t is an intersection type T = CT & I1 & I2 ... & In
  2086                     //its supertypes CT, I1, ... In might contain wildcards
  2087                     //so we need to go through capture conversion
  2088                     base = t.isCompound() ? capture(base) : base;
  2089                     if (base != null) {
  2090                         List<Type> ownerParams = owner.type.allparams();
  2091                         List<Type> baseParams = base.allparams();
  2092                         if (ownerParams.nonEmpty()) {
  2093                             if (baseParams.isEmpty()) {
  2094                                 // then base is a raw type
  2095                                 return erasure(sym.type);
  2096                             } else {
  2097                                 return subst(sym.type, ownerParams, baseParams);
  2102                 return sym.type;
  2105             @Override
  2106             public Type visitTypeVar(TypeVar t, Symbol sym) {
  2107                 return memberType(t.bound, sym);
  2110             @Override
  2111             public Type visitErrorType(ErrorType t, Symbol sym) {
  2112                 return t;
  2114         };
  2115     // </editor-fold>
  2117     // <editor-fold defaultstate="collapsed" desc="isAssignable">
  2118     public boolean isAssignable(Type t, Type s) {
  2119         return isAssignable(t, s, noWarnings);
  2122     /**
  2123      * Is t assignable to s?<br>
  2124      * Equivalent to subtype except for constant values and raw
  2125      * types.<br>
  2126      * (not defined for Method and ForAll types)
  2127      */
  2128     public boolean isAssignable(Type t, Type s, Warner warn) {
  2129         if (t.hasTag(ERROR))
  2130             return true;
  2131         if (t.getTag().isSubRangeOf(INT) && t.constValue() != null) {
  2132             int value = ((Number)t.constValue()).intValue();
  2133             switch (s.getTag()) {
  2134             case BYTE:
  2135                 if (Byte.MIN_VALUE <= value && value <= Byte.MAX_VALUE)
  2136                     return true;
  2137                 break;
  2138             case CHAR:
  2139                 if (Character.MIN_VALUE <= value && value <= Character.MAX_VALUE)
  2140                     return true;
  2141                 break;
  2142             case SHORT:
  2143                 if (Short.MIN_VALUE <= value && value <= Short.MAX_VALUE)
  2144                     return true;
  2145                 break;
  2146             case INT:
  2147                 return true;
  2148             case CLASS:
  2149                 switch (unboxedType(s).getTag()) {
  2150                 case BYTE:
  2151                 case CHAR:
  2152                 case SHORT:
  2153                     return isAssignable(t, unboxedType(s), warn);
  2155                 break;
  2158         return isConvertible(t, s, warn);
  2160     // </editor-fold>
  2162     // <editor-fold defaultstate="collapsed" desc="erasure">
  2163     /**
  2164      * The erasure of t {@code |t|} -- the type that results when all
  2165      * type parameters in t are deleted.
  2166      */
  2167     public Type erasure(Type t) {
  2168         return eraseNotNeeded(t)? t : erasure(t, false);
  2170     //where
  2171     private boolean eraseNotNeeded(Type t) {
  2172         // We don't want to erase primitive types and String type as that
  2173         // operation is idempotent. Also, erasing these could result in loss
  2174         // of information such as constant values attached to such types.
  2175         return (t.isPrimitive()) || (syms.stringType.tsym == t.tsym);
  2178     private Type erasure(Type t, boolean recurse) {
  2179         if (t.isPrimitive())
  2180             return t; /* fast special case */
  2181         else
  2182             return erasure.visit(t, recurse);
  2184     // where
  2185         private SimpleVisitor<Type, Boolean> erasure = new SimpleVisitor<Type, Boolean>() {
  2186             public Type visitType(Type t, Boolean recurse) {
  2187                 if (t.isPrimitive())
  2188                     return t; /*fast special case*/
  2189                 else
  2190                     return t.map(recurse ? erasureRecFun : erasureFun);
  2193             @Override
  2194             public Type visitWildcardType(WildcardType t, Boolean recurse) {
  2195                 return erasure(upperBound(t), recurse);
  2198             @Override
  2199             public Type visitClassType(ClassType t, Boolean recurse) {
  2200                 Type erased = t.tsym.erasure(Types.this);
  2201                 if (recurse) {
  2202                     erased = new ErasedClassType(erased.getEnclosingType(),erased.tsym);
  2204                 return erased;
  2207             @Override
  2208             public Type visitTypeVar(TypeVar t, Boolean recurse) {
  2209                 return erasure(t.bound, recurse);
  2212             @Override
  2213             public Type visitErrorType(ErrorType t, Boolean recurse) {
  2214                 return t;
  2217             @Override
  2218             public Type visitAnnotatedType(AnnotatedType t, Boolean recurse) {
  2219                 Type erased = erasure(t.unannotatedType(), recurse);
  2220                 if (erased.isAnnotated()) {
  2221                     // This can only happen when the underlying type is a
  2222                     // type variable and the upper bound of it is annotated.
  2223                     // The annotation on the type variable overrides the one
  2224                     // on the bound.
  2225                     erased = ((AnnotatedType)erased).unannotatedType();
  2227                 return erased.annotatedType(t.getAnnotationMirrors());
  2229         };
  2231     private Mapping erasureFun = new Mapping ("erasure") {
  2232             public Type apply(Type t) { return erasure(t); }
  2233         };
  2235     private Mapping erasureRecFun = new Mapping ("erasureRecursive") {
  2236         public Type apply(Type t) { return erasureRecursive(t); }
  2237     };
  2239     public List<Type> erasure(List<Type> ts) {
  2240         return Type.map(ts, erasureFun);
  2243     public Type erasureRecursive(Type t) {
  2244         return erasure(t, true);
  2247     public List<Type> erasureRecursive(List<Type> ts) {
  2248         return Type.map(ts, erasureRecFun);
  2250     // </editor-fold>
  2252     // <editor-fold defaultstate="collapsed" desc="makeCompoundType">
  2253     /**
  2254      * Make a compound type from non-empty list of types.  The list should be
  2255      * ordered according to {@link Symbol#precedes(TypeSymbol,Types)}.
  2257      * @param bounds            the types from which the compound type is formed
  2258      * @param supertype         is objectType if all bounds are interfaces,
  2259      *                          null otherwise.
  2260      */
  2261     public Type makeCompoundType(List<Type> bounds) {
  2262         return makeCompoundType(bounds, bounds.head.tsym.isInterface());
  2264     public Type makeCompoundType(List<Type> bounds, boolean allInterfaces) {
  2265         Assert.check(bounds.nonEmpty());
  2266         Type firstExplicitBound = bounds.head;
  2267         if (allInterfaces) {
  2268             bounds = bounds.prepend(syms.objectType);
  2270         ClassSymbol bc =
  2271             new ClassSymbol(ABSTRACT|PUBLIC|SYNTHETIC|COMPOUND|ACYCLIC,
  2272                             Type.moreInfo
  2273                                 ? names.fromString(bounds.toString())
  2274                                 : names.empty,
  2275                             null,
  2276                             syms.noSymbol);
  2277         bc.type = new IntersectionClassType(bounds, bc, allInterfaces);
  2278         bc.erasure_field = (bounds.head.hasTag(TYPEVAR)) ?
  2279                 syms.objectType : // error condition, recover
  2280                 erasure(firstExplicitBound);
  2281         bc.members_field = new Scope(bc);
  2282         return bc.type;
  2285     /**
  2286      * A convenience wrapper for {@link #makeCompoundType(List)}; the
  2287      * arguments are converted to a list and passed to the other
  2288      * method.  Note that this might cause a symbol completion.
  2289      * Hence, this version of makeCompoundType may not be called
  2290      * during a classfile read.
  2291      */
  2292     public Type makeCompoundType(Type bound1, Type bound2) {
  2293         return makeCompoundType(List.of(bound1, bound2));
  2295     // </editor-fold>
  2297     // <editor-fold defaultstate="collapsed" desc="supertype">
  2298     public Type supertype(Type t) {
  2299         return supertype.visit(t);
  2301     // where
  2302         private UnaryVisitor<Type> supertype = new UnaryVisitor<Type>() {
  2304             public Type visitType(Type t, Void ignored) {
  2305                 // A note on wildcards: there is no good way to
  2306                 // determine a supertype for a super bounded wildcard.
  2307                 return null;
  2310             @Override
  2311             public Type visitClassType(ClassType t, Void ignored) {
  2312                 if (t.supertype_field == null) {
  2313                     Type supertype = ((ClassSymbol)t.tsym).getSuperclass();
  2314                     // An interface has no superclass; its supertype is Object.
  2315                     if (t.isInterface())
  2316                         supertype = ((ClassType)t.tsym.type).supertype_field;
  2317                     if (t.supertype_field == null) {
  2318                         List<Type> actuals = classBound(t).allparams();
  2319                         List<Type> formals = t.tsym.type.allparams();
  2320                         if (t.hasErasedSupertypes()) {
  2321                             t.supertype_field = erasureRecursive(supertype);
  2322                         } else if (formals.nonEmpty()) {
  2323                             t.supertype_field = subst(supertype, formals, actuals);
  2325                         else {
  2326                             t.supertype_field = supertype;
  2330                 return t.supertype_field;
  2333             /**
  2334              * The supertype is always a class type. If the type
  2335              * variable's bounds start with a class type, this is also
  2336              * the supertype.  Otherwise, the supertype is
  2337              * java.lang.Object.
  2338              */
  2339             @Override
  2340             public Type visitTypeVar(TypeVar t, Void ignored) {
  2341                 if (t.bound.hasTag(TYPEVAR) ||
  2342                     (!t.bound.isCompound() && !t.bound.isInterface())) {
  2343                     return t.bound;
  2344                 } else {
  2345                     return supertype(t.bound);
  2349             @Override
  2350             public Type visitArrayType(ArrayType t, Void ignored) {
  2351                 if (t.elemtype.isPrimitive() || isSameType(t.elemtype, syms.objectType))
  2352                     return arraySuperType();
  2353                 else
  2354                     return new ArrayType(supertype(t.elemtype), t.tsym);
  2357             @Override
  2358             public Type visitErrorType(ErrorType t, Void ignored) {
  2359                 return Type.noType;
  2361         };
  2362     // </editor-fold>
  2364     // <editor-fold defaultstate="collapsed" desc="interfaces">
  2365     /**
  2366      * Return the interfaces implemented by this class.
  2367      */
  2368     public List<Type> interfaces(Type t) {
  2369         return interfaces.visit(t);
  2371     // where
  2372         private UnaryVisitor<List<Type>> interfaces = new UnaryVisitor<List<Type>>() {
  2374             public List<Type> visitType(Type t, Void ignored) {
  2375                 return List.nil();
  2378             @Override
  2379             public List<Type> visitClassType(ClassType t, Void ignored) {
  2380                 if (t.interfaces_field == null) {
  2381                     List<Type> interfaces = ((ClassSymbol)t.tsym).getInterfaces();
  2382                     if (t.interfaces_field == null) {
  2383                         // If t.interfaces_field is null, then t must
  2384                         // be a parameterized type (not to be confused
  2385                         // with a generic type declaration).
  2386                         // Terminology:
  2387                         //    Parameterized type: List<String>
  2388                         //    Generic type declaration: class List<E> { ... }
  2389                         // So t corresponds to List<String> and
  2390                         // t.tsym.type corresponds to List<E>.
  2391                         // The reason t must be parameterized type is
  2392                         // that completion will happen as a side
  2393                         // effect of calling
  2394                         // ClassSymbol.getInterfaces.  Since
  2395                         // t.interfaces_field is null after
  2396                         // completion, we can assume that t is not the
  2397                         // type of a class/interface declaration.
  2398                         Assert.check(t != t.tsym.type, t);
  2399                         List<Type> actuals = t.allparams();
  2400                         List<Type> formals = t.tsym.type.allparams();
  2401                         if (t.hasErasedSupertypes()) {
  2402                             t.interfaces_field = erasureRecursive(interfaces);
  2403                         } else if (formals.nonEmpty()) {
  2404                             t.interfaces_field =
  2405                                 upperBounds(subst(interfaces, formals, actuals));
  2407                         else {
  2408                             t.interfaces_field = interfaces;
  2412                 return t.interfaces_field;
  2415             @Override
  2416             public List<Type> visitTypeVar(TypeVar t, Void ignored) {
  2417                 if (t.bound.isCompound())
  2418                     return interfaces(t.bound);
  2420                 if (t.bound.isInterface())
  2421                     return List.of(t.bound);
  2423                 return List.nil();
  2425         };
  2427     public List<Type> directSupertypes(Type t) {
  2428         return directSupertypes.visit(t);
  2430     // where
  2431         private final UnaryVisitor<List<Type>> directSupertypes = new UnaryVisitor<List<Type>>() {
  2433             public List<Type> visitType(final Type type, final Void ignored) {
  2434                 if (!type.isCompound()) {
  2435                     final Type sup = supertype(type);
  2436                     return (sup == Type.noType || sup == type || sup == null)
  2437                         ? interfaces(type)
  2438                         : interfaces(type).prepend(sup);
  2439                 } else {
  2440                     return visitIntersectionType((IntersectionClassType) type);
  2444             private List<Type> visitIntersectionType(final IntersectionClassType it) {
  2445                 return it.getExplicitComponents();
  2448         };
  2450     public boolean isDirectSuperInterface(TypeSymbol isym, TypeSymbol origin) {
  2451         for (Type i2 : interfaces(origin.type)) {
  2452             if (isym == i2.tsym) return true;
  2454         return false;
  2456     // </editor-fold>
  2458     // <editor-fold defaultstate="collapsed" desc="isDerivedRaw">
  2459     Map<Type,Boolean> isDerivedRawCache = new HashMap<Type,Boolean>();
  2461     public boolean isDerivedRaw(Type t) {
  2462         Boolean result = isDerivedRawCache.get(t);
  2463         if (result == null) {
  2464             result = isDerivedRawInternal(t);
  2465             isDerivedRawCache.put(t, result);
  2467         return result;
  2470     public boolean isDerivedRawInternal(Type t) {
  2471         if (t.isErroneous())
  2472             return false;
  2473         return
  2474             t.isRaw() ||
  2475             supertype(t) != null && isDerivedRaw(supertype(t)) ||
  2476             isDerivedRaw(interfaces(t));
  2479     public boolean isDerivedRaw(List<Type> ts) {
  2480         List<Type> l = ts;
  2481         while (l.nonEmpty() && !isDerivedRaw(l.head)) l = l.tail;
  2482         return l.nonEmpty();
  2484     // </editor-fold>
  2486     // <editor-fold defaultstate="collapsed" desc="setBounds">
  2487     /**
  2488      * Set the bounds field of the given type variable to reflect a
  2489      * (possibly multiple) list of bounds.
  2490      * @param t                 a type variable
  2491      * @param bounds            the bounds, must be nonempty
  2492      * @param supertype         is objectType if all bounds are interfaces,
  2493      *                          null otherwise.
  2494      */
  2495     public void setBounds(TypeVar t, List<Type> bounds) {
  2496         setBounds(t, bounds, bounds.head.tsym.isInterface());
  2499     /**
  2500      * Same as {@link #setBounds(Type.TypeVar,List,Type)}, except that
  2501      * third parameter is computed directly, as follows: if all
  2502      * all bounds are interface types, the computed supertype is Object,
  2503      * otherwise the supertype is simply left null (in this case, the supertype
  2504      * is assumed to be the head of the bound list passed as second argument).
  2505      * Note that this check might cause a symbol completion. Hence, this version of
  2506      * setBounds may not be called during a classfile read.
  2507      */
  2508     public void setBounds(TypeVar t, List<Type> bounds, boolean allInterfaces) {
  2509         t.bound = bounds.tail.isEmpty() ?
  2510                 bounds.head :
  2511                 makeCompoundType(bounds, allInterfaces);
  2512         t.rank_field = -1;
  2514     // </editor-fold>
  2516     // <editor-fold defaultstate="collapsed" desc="getBounds">
  2517     /**
  2518      * Return list of bounds of the given type variable.
  2519      */
  2520     public List<Type> getBounds(TypeVar t) {
  2521         if (t.bound.hasTag(NONE))
  2522             return List.nil();
  2523         else if (t.bound.isErroneous() || !t.bound.isCompound())
  2524             return List.of(t.bound);
  2525         else if ((erasure(t).tsym.flags() & INTERFACE) == 0)
  2526             return interfaces(t).prepend(supertype(t));
  2527         else
  2528             // No superclass was given in bounds.
  2529             // In this case, supertype is Object, erasure is first interface.
  2530             return interfaces(t);
  2532     // </editor-fold>
  2534     // <editor-fold defaultstate="collapsed" desc="classBound">
  2535     /**
  2536      * If the given type is a (possibly selected) type variable,
  2537      * return the bounding class of this type, otherwise return the
  2538      * type itself.
  2539      */
  2540     public Type classBound(Type t) {
  2541         return classBound.visit(t);
  2543     // where
  2544         private UnaryVisitor<Type> classBound = new UnaryVisitor<Type>() {
  2546             public Type visitType(Type t, Void ignored) {
  2547                 return t;
  2550             @Override
  2551             public Type visitClassType(ClassType t, Void ignored) {
  2552                 Type outer1 = classBound(t.getEnclosingType());
  2553                 if (outer1 != t.getEnclosingType())
  2554                     return new ClassType(outer1, t.getTypeArguments(), t.tsym);
  2555                 else
  2556                     return t;
  2559             @Override
  2560             public Type visitTypeVar(TypeVar t, Void ignored) {
  2561                 return classBound(supertype(t));
  2564             @Override
  2565             public Type visitErrorType(ErrorType t, Void ignored) {
  2566                 return t;
  2568         };
  2569     // </editor-fold>
  2571     // <editor-fold defaultstate="collapsed" desc="sub signature / override equivalence">
  2572     /**
  2573      * Returns true iff the first signature is a <em>sub
  2574      * signature</em> of the other.  This is <b>not</b> an equivalence
  2575      * relation.
  2577      * @jls section 8.4.2.
  2578      * @see #overrideEquivalent(Type t, Type s)
  2579      * @param t first signature (possibly raw).
  2580      * @param s second signature (could be subjected to erasure).
  2581      * @return true if t is a sub signature of s.
  2582      */
  2583     public boolean isSubSignature(Type t, Type s) {
  2584         return isSubSignature(t, s, true);
  2587     public boolean isSubSignature(Type t, Type s, boolean strict) {
  2588         return hasSameArgs(t, s, strict) || hasSameArgs(t, erasure(s), strict);
  2591     /**
  2592      * Returns true iff these signatures are related by <em>override
  2593      * equivalence</em>.  This is the natural extension of
  2594      * isSubSignature to an equivalence relation.
  2596      * @jls section 8.4.2.
  2597      * @see #isSubSignature(Type t, Type s)
  2598      * @param t a signature (possible raw, could be subjected to
  2599      * erasure).
  2600      * @param s a signature (possible raw, could be subjected to
  2601      * erasure).
  2602      * @return true if either argument is a sub signature of the other.
  2603      */
  2604     public boolean overrideEquivalent(Type t, Type s) {
  2605         return hasSameArgs(t, s) ||
  2606             hasSameArgs(t, erasure(s)) || hasSameArgs(erasure(t), s);
  2609     public boolean overridesObjectMethod(TypeSymbol origin, Symbol msym) {
  2610         for (Scope.Entry e = syms.objectType.tsym.members().lookup(msym.name) ; e.scope != null ; e = e.next()) {
  2611             if (msym.overrides(e.sym, origin, Types.this, true)) {
  2612                 return true;
  2615         return false;
  2618     // <editor-fold defaultstate="collapsed" desc="Determining method implementation in given site">
  2619     class ImplementationCache {
  2621         private WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>> _map =
  2622                 new WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>>();
  2624         class Entry {
  2625             final MethodSymbol cachedImpl;
  2626             final Filter<Symbol> implFilter;
  2627             final boolean checkResult;
  2628             final int prevMark;
  2630             public Entry(MethodSymbol cachedImpl,
  2631                     Filter<Symbol> scopeFilter,
  2632                     boolean checkResult,
  2633                     int prevMark) {
  2634                 this.cachedImpl = cachedImpl;
  2635                 this.implFilter = scopeFilter;
  2636                 this.checkResult = checkResult;
  2637                 this.prevMark = prevMark;
  2640             boolean matches(Filter<Symbol> scopeFilter, boolean checkResult, int mark) {
  2641                 return this.implFilter == scopeFilter &&
  2642                         this.checkResult == checkResult &&
  2643                         this.prevMark == mark;
  2647         MethodSymbol get(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
  2648             SoftReference<Map<TypeSymbol, Entry>> ref_cache = _map.get(ms);
  2649             Map<TypeSymbol, Entry> cache = ref_cache != null ? ref_cache.get() : null;
  2650             if (cache == null) {
  2651                 cache = new HashMap<TypeSymbol, Entry>();
  2652                 _map.put(ms, new SoftReference<Map<TypeSymbol, Entry>>(cache));
  2654             Entry e = cache.get(origin);
  2655             CompoundScope members = membersClosure(origin.type, true);
  2656             if (e == null ||
  2657                     !e.matches(implFilter, checkResult, members.getMark())) {
  2658                 MethodSymbol impl = implementationInternal(ms, origin, checkResult, implFilter);
  2659                 cache.put(origin, new Entry(impl, implFilter, checkResult, members.getMark()));
  2660                 return impl;
  2662             else {
  2663                 return e.cachedImpl;
  2667         private MethodSymbol implementationInternal(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
  2668             for (Type t = origin.type; t.hasTag(CLASS) || t.hasTag(TYPEVAR); t = supertype(t)) {
  2669                 while (t.hasTag(TYPEVAR))
  2670                     t = t.getUpperBound();
  2671                 TypeSymbol c = t.tsym;
  2672                 for (Scope.Entry e = c.members().lookup(ms.name, implFilter);
  2673                      e.scope != null;
  2674                      e = e.next(implFilter)) {
  2675                     if (e.sym != null &&
  2676                              e.sym.overrides(ms, origin, Types.this, checkResult))
  2677                         return (MethodSymbol)e.sym;
  2680             return null;
  2684     private ImplementationCache implCache = new ImplementationCache();
  2686     public MethodSymbol implementation(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
  2687         return implCache.get(ms, origin, checkResult, implFilter);
  2689     // </editor-fold>
  2691     // <editor-fold defaultstate="collapsed" desc="compute transitive closure of all members in given site">
  2692     class MembersClosureCache extends SimpleVisitor<CompoundScope, Boolean> {
  2694         private WeakHashMap<TypeSymbol, Entry> _map =
  2695                 new WeakHashMap<TypeSymbol, Entry>();
  2697         class Entry {
  2698             final boolean skipInterfaces;
  2699             final CompoundScope compoundScope;
  2701             public Entry(boolean skipInterfaces, CompoundScope compoundScope) {
  2702                 this.skipInterfaces = skipInterfaces;
  2703                 this.compoundScope = compoundScope;
  2706             boolean matches(boolean skipInterfaces) {
  2707                 return this.skipInterfaces == skipInterfaces;
  2711         List<TypeSymbol> seenTypes = List.nil();
  2713         /** members closure visitor methods **/
  2715         public CompoundScope visitType(Type t, Boolean skipInterface) {
  2716             return null;
  2719         @Override
  2720         public CompoundScope visitClassType(ClassType t, Boolean skipInterface) {
  2721             if (seenTypes.contains(t.tsym)) {
  2722                 //this is possible when an interface is implemented in multiple
  2723                 //superclasses, or when a classs hierarchy is circular - in such
  2724                 //cases we don't need to recurse (empty scope is returned)
  2725                 return new CompoundScope(t.tsym);
  2727             try {
  2728                 seenTypes = seenTypes.prepend(t.tsym);
  2729                 ClassSymbol csym = (ClassSymbol)t.tsym;
  2730                 Entry e = _map.get(csym);
  2731                 if (e == null || !e.matches(skipInterface)) {
  2732                     CompoundScope membersClosure = new CompoundScope(csym);
  2733                     if (!skipInterface) {
  2734                         for (Type i : interfaces(t)) {
  2735                             membersClosure.addSubScope(visit(i, skipInterface));
  2738                     membersClosure.addSubScope(visit(supertype(t), skipInterface));
  2739                     membersClosure.addSubScope(csym.members());
  2740                     e = new Entry(skipInterface, membersClosure);
  2741                     _map.put(csym, e);
  2743                 return e.compoundScope;
  2745             finally {
  2746                 seenTypes = seenTypes.tail;
  2750         @Override
  2751         public CompoundScope visitTypeVar(TypeVar t, Boolean skipInterface) {
  2752             return visit(t.getUpperBound(), skipInterface);
  2756     private MembersClosureCache membersCache = new MembersClosureCache();
  2758     public CompoundScope membersClosure(Type site, boolean skipInterface) {
  2759         return membersCache.visit(site, skipInterface);
  2761     // </editor-fold>
  2764     //where
  2765     public List<MethodSymbol> interfaceCandidates(Type site, MethodSymbol ms) {
  2766         Filter<Symbol> filter = new MethodFilter(ms, site);
  2767         List<MethodSymbol> candidates = List.nil();
  2768             for (Symbol s : membersClosure(site, false).getElements(filter)) {
  2769                 if (!site.tsym.isInterface() && !s.owner.isInterface()) {
  2770                     return List.of((MethodSymbol)s);
  2771                 } else if (!candidates.contains(s)) {
  2772                     candidates = candidates.prepend((MethodSymbol)s);
  2775             return prune(candidates);
  2778     public List<MethodSymbol> prune(List<MethodSymbol> methods) {
  2779         ListBuffer<MethodSymbol> methodsMin = new ListBuffer<>();
  2780         for (MethodSymbol m1 : methods) {
  2781             boolean isMin_m1 = true;
  2782             for (MethodSymbol m2 : methods) {
  2783                 if (m1 == m2) continue;
  2784                 if (m2.owner != m1.owner &&
  2785                         asSuper(m2.owner.type, m1.owner) != null) {
  2786                     isMin_m1 = false;
  2787                     break;
  2790             if (isMin_m1)
  2791                 methodsMin.append(m1);
  2793         return methodsMin.toList();
  2795     // where
  2796             private class MethodFilter implements Filter<Symbol> {
  2798                 Symbol msym;
  2799                 Type site;
  2801                 MethodFilter(Symbol msym, Type site) {
  2802                     this.msym = msym;
  2803                     this.site = site;
  2806                 public boolean accepts(Symbol s) {
  2807                     return s.kind == Kinds.MTH &&
  2808                             s.name == msym.name &&
  2809                             (s.flags() & SYNTHETIC) == 0 &&
  2810                             s.isInheritedIn(site.tsym, Types.this) &&
  2811                             overrideEquivalent(memberType(site, s), memberType(site, msym));
  2813             };
  2814     // </editor-fold>
  2816     /**
  2817      * Does t have the same arguments as s?  It is assumed that both
  2818      * types are (possibly polymorphic) method types.  Monomorphic
  2819      * method types "have the same arguments", if their argument lists
  2820      * are equal.  Polymorphic method types "have the same arguments",
  2821      * if they have the same arguments after renaming all type
  2822      * variables of one to corresponding type variables in the other,
  2823      * where correspondence is by position in the type parameter list.
  2824      */
  2825     public boolean hasSameArgs(Type t, Type s) {
  2826         return hasSameArgs(t, s, true);
  2829     public boolean hasSameArgs(Type t, Type s, boolean strict) {
  2830         return hasSameArgs(t, s, strict ? hasSameArgs_strict : hasSameArgs_nonstrict);
  2833     private boolean hasSameArgs(Type t, Type s, TypeRelation hasSameArgs) {
  2834         return hasSameArgs.visit(t, s);
  2836     // where
  2837         private class HasSameArgs extends TypeRelation {
  2839             boolean strict;
  2841             public HasSameArgs(boolean strict) {
  2842                 this.strict = strict;
  2845             public Boolean visitType(Type t, Type s) {
  2846                 throw new AssertionError();
  2849             @Override
  2850             public Boolean visitMethodType(MethodType t, Type s) {
  2851                 return s.hasTag(METHOD)
  2852                     && containsTypeEquivalent(t.argtypes, s.getParameterTypes());
  2855             @Override
  2856             public Boolean visitForAll(ForAll t, Type s) {
  2857                 if (!s.hasTag(FORALL))
  2858                     return strict ? false : visitMethodType(t.asMethodType(), s);
  2860                 ForAll forAll = (ForAll)s;
  2861                 return hasSameBounds(t, forAll)
  2862                     && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
  2865             @Override
  2866             public Boolean visitErrorType(ErrorType t, Type s) {
  2867                 return false;
  2869         };
  2871         TypeRelation hasSameArgs_strict = new HasSameArgs(true);
  2872         TypeRelation hasSameArgs_nonstrict = new HasSameArgs(false);
  2874     // </editor-fold>
  2876     // <editor-fold defaultstate="collapsed" desc="subst">
  2877     public List<Type> subst(List<Type> ts,
  2878                             List<Type> from,
  2879                             List<Type> to) {
  2880         return new Subst(from, to).subst(ts);
  2883     /**
  2884      * Substitute all occurrences of a type in `from' with the
  2885      * corresponding type in `to' in 't'. Match lists `from' and `to'
  2886      * from the right: If lists have different length, discard leading
  2887      * elements of the longer list.
  2888      */
  2889     public Type subst(Type t, List<Type> from, List<Type> to) {
  2890         return new Subst(from, to).subst(t);
  2893     private class Subst extends UnaryVisitor<Type> {
  2894         List<Type> from;
  2895         List<Type> to;
  2897         public Subst(List<Type> from, List<Type> to) {
  2898             int fromLength = from.length();
  2899             int toLength = to.length();
  2900             while (fromLength > toLength) {
  2901                 fromLength--;
  2902                 from = from.tail;
  2904             while (fromLength < toLength) {
  2905                 toLength--;
  2906                 to = to.tail;
  2908             this.from = from;
  2909             this.to = to;
  2912         Type subst(Type t) {
  2913             if (from.tail == null)
  2914                 return t;
  2915             else
  2916                 return visit(t);
  2919         List<Type> subst(List<Type> ts) {
  2920             if (from.tail == null)
  2921                 return ts;
  2922             boolean wild = false;
  2923             if (ts.nonEmpty() && from.nonEmpty()) {
  2924                 Type head1 = subst(ts.head);
  2925                 List<Type> tail1 = subst(ts.tail);
  2926                 if (head1 != ts.head || tail1 != ts.tail)
  2927                     return tail1.prepend(head1);
  2929             return ts;
  2932         public Type visitType(Type t, Void ignored) {
  2933             return t;
  2936         @Override
  2937         public Type visitMethodType(MethodType t, Void ignored) {
  2938             List<Type> argtypes = subst(t.argtypes);
  2939             Type restype = subst(t.restype);
  2940             List<Type> thrown = subst(t.thrown);
  2941             if (argtypes == t.argtypes &&
  2942                 restype == t.restype &&
  2943                 thrown == t.thrown)
  2944                 return t;
  2945             else
  2946                 return new MethodType(argtypes, restype, thrown, t.tsym);
  2949         @Override
  2950         public Type visitTypeVar(TypeVar t, Void ignored) {
  2951             for (List<Type> from = this.from, to = this.to;
  2952                  from.nonEmpty();
  2953                  from = from.tail, to = to.tail) {
  2954                 if (t == from.head) {
  2955                     return to.head.withTypeVar(t);
  2958             return t;
  2961         @Override
  2962         public Type visitClassType(ClassType t, Void ignored) {
  2963             if (!t.isCompound()) {
  2964                 List<Type> typarams = t.getTypeArguments();
  2965                 List<Type> typarams1 = subst(typarams);
  2966                 Type outer = t.getEnclosingType();
  2967                 Type outer1 = subst(outer);
  2968                 if (typarams1 == typarams && outer1 == outer)
  2969                     return t;
  2970                 else
  2971                     return new ClassType(outer1, typarams1, t.tsym);
  2972             } else {
  2973                 Type st = subst(supertype(t));
  2974                 List<Type> is = upperBounds(subst(interfaces(t)));
  2975                 if (st == supertype(t) && is == interfaces(t))
  2976                     return t;
  2977                 else
  2978                     return makeCompoundType(is.prepend(st));
  2982         @Override
  2983         public Type visitWildcardType(WildcardType t, Void ignored) {
  2984             Type bound = t.type;
  2985             if (t.kind != BoundKind.UNBOUND)
  2986                 bound = subst(bound);
  2987             if (bound == t.type) {
  2988                 return t;
  2989             } else {
  2990                 if (t.isExtendsBound() && bound.isExtendsBound())
  2991                     bound = upperBound(bound);
  2992                 return new WildcardType(bound, t.kind, syms.boundClass, t.bound);
  2996         @Override
  2997         public Type visitArrayType(ArrayType t, Void ignored) {
  2998             Type elemtype = subst(t.elemtype);
  2999             if (elemtype == t.elemtype)
  3000                 return t;
  3001             else
  3002                 return new ArrayType(elemtype, t.tsym);
  3005         @Override
  3006         public Type visitForAll(ForAll t, Void ignored) {
  3007             if (Type.containsAny(to, t.tvars)) {
  3008                 //perform alpha-renaming of free-variables in 't'
  3009                 //if 'to' types contain variables that are free in 't'
  3010                 List<Type> freevars = newInstances(t.tvars);
  3011                 t = new ForAll(freevars,
  3012                         Types.this.subst(t.qtype, t.tvars, freevars));
  3014             List<Type> tvars1 = substBounds(t.tvars, from, to);
  3015             Type qtype1 = subst(t.qtype);
  3016             if (tvars1 == t.tvars && qtype1 == t.qtype) {
  3017                 return t;
  3018             } else if (tvars1 == t.tvars) {
  3019                 return new ForAll(tvars1, qtype1);
  3020             } else {
  3021                 return new ForAll(tvars1, Types.this.subst(qtype1, t.tvars, tvars1));
  3025         @Override
  3026         public Type visitErrorType(ErrorType t, Void ignored) {
  3027             return t;
  3031     public List<Type> substBounds(List<Type> tvars,
  3032                                   List<Type> from,
  3033                                   List<Type> to) {
  3034         if (tvars.isEmpty())
  3035             return tvars;
  3036         ListBuffer<Type> newBoundsBuf = new ListBuffer<>();
  3037         boolean changed = false;
  3038         // calculate new bounds
  3039         for (Type t : tvars) {
  3040             TypeVar tv = (TypeVar) t;
  3041             Type bound = subst(tv.bound, from, to);
  3042             if (bound != tv.bound)
  3043                 changed = true;
  3044             newBoundsBuf.append(bound);
  3046         if (!changed)
  3047             return tvars;
  3048         ListBuffer<Type> newTvars = new ListBuffer<>();
  3049         // create new type variables without bounds
  3050         for (Type t : tvars) {
  3051             newTvars.append(new TypeVar(t.tsym, null, syms.botType));
  3053         // the new bounds should use the new type variables in place
  3054         // of the old
  3055         List<Type> newBounds = newBoundsBuf.toList();
  3056         from = tvars;
  3057         to = newTvars.toList();
  3058         for (; !newBounds.isEmpty(); newBounds = newBounds.tail) {
  3059             newBounds.head = subst(newBounds.head, from, to);
  3061         newBounds = newBoundsBuf.toList();
  3062         // set the bounds of new type variables to the new bounds
  3063         for (Type t : newTvars.toList()) {
  3064             TypeVar tv = (TypeVar) t;
  3065             tv.bound = newBounds.head;
  3066             newBounds = newBounds.tail;
  3068         return newTvars.toList();
  3071     public TypeVar substBound(TypeVar t, List<Type> from, List<Type> to) {
  3072         Type bound1 = subst(t.bound, from, to);
  3073         if (bound1 == t.bound)
  3074             return t;
  3075         else {
  3076             // create new type variable without bounds
  3077             TypeVar tv = new TypeVar(t.tsym, null, syms.botType);
  3078             // the new bound should use the new type variable in place
  3079             // of the old
  3080             tv.bound = subst(bound1, List.<Type>of(t), List.<Type>of(tv));
  3081             return tv;
  3084     // </editor-fold>
  3086     // <editor-fold defaultstate="collapsed" desc="hasSameBounds">
  3087     /**
  3088      * Does t have the same bounds for quantified variables as s?
  3089      */
  3090     public boolean hasSameBounds(ForAll t, ForAll s) {
  3091         List<Type> l1 = t.tvars;
  3092         List<Type> l2 = s.tvars;
  3093         while (l1.nonEmpty() && l2.nonEmpty() &&
  3094                isSameType(l1.head.getUpperBound(),
  3095                           subst(l2.head.getUpperBound(),
  3096                                 s.tvars,
  3097                                 t.tvars))) {
  3098             l1 = l1.tail;
  3099             l2 = l2.tail;
  3101         return l1.isEmpty() && l2.isEmpty();
  3103     // </editor-fold>
  3105     // <editor-fold defaultstate="collapsed" desc="newInstances">
  3106     /** Create new vector of type variables from list of variables
  3107      *  changing all recursive bounds from old to new list.
  3108      */
  3109     public List<Type> newInstances(List<Type> tvars) {
  3110         List<Type> tvars1 = Type.map(tvars, newInstanceFun);
  3111         for (List<Type> l = tvars1; l.nonEmpty(); l = l.tail) {
  3112             TypeVar tv = (TypeVar) l.head;
  3113             tv.bound = subst(tv.bound, tvars, tvars1);
  3115         return tvars1;
  3117     private static final Mapping newInstanceFun = new Mapping("newInstanceFun") {
  3118             public Type apply(Type t) { return new TypeVar(t.tsym, t.getUpperBound(), t.getLowerBound()); }
  3119         };
  3120     // </editor-fold>
  3122     public Type createMethodTypeWithParameters(Type original, List<Type> newParams) {
  3123         return original.accept(methodWithParameters, newParams);
  3125     // where
  3126         private final MapVisitor<List<Type>> methodWithParameters = new MapVisitor<List<Type>>() {
  3127             public Type visitType(Type t, List<Type> newParams) {
  3128                 throw new IllegalArgumentException("Not a method type: " + t);
  3130             public Type visitMethodType(MethodType t, List<Type> newParams) {
  3131                 return new MethodType(newParams, t.restype, t.thrown, t.tsym);
  3133             public Type visitForAll(ForAll t, List<Type> newParams) {
  3134                 return new ForAll(t.tvars, t.qtype.accept(this, newParams));
  3136         };
  3138     public Type createMethodTypeWithThrown(Type original, List<Type> newThrown) {
  3139         return original.accept(methodWithThrown, newThrown);
  3141     // where
  3142         private final MapVisitor<List<Type>> methodWithThrown = new MapVisitor<List<Type>>() {
  3143             public Type visitType(Type t, List<Type> newThrown) {
  3144                 throw new IllegalArgumentException("Not a method type: " + t);
  3146             public Type visitMethodType(MethodType t, List<Type> newThrown) {
  3147                 return new MethodType(t.argtypes, t.restype, newThrown, t.tsym);
  3149             public Type visitForAll(ForAll t, List<Type> newThrown) {
  3150                 return new ForAll(t.tvars, t.qtype.accept(this, newThrown));
  3152         };
  3154     public Type createMethodTypeWithReturn(Type original, Type newReturn) {
  3155         return original.accept(methodWithReturn, newReturn);
  3157     // where
  3158         private final MapVisitor<Type> methodWithReturn = new MapVisitor<Type>() {
  3159             public Type visitType(Type t, Type newReturn) {
  3160                 throw new IllegalArgumentException("Not a method type: " + t);
  3162             public Type visitMethodType(MethodType t, Type newReturn) {
  3163                 return new MethodType(t.argtypes, newReturn, t.thrown, t.tsym);
  3165             public Type visitForAll(ForAll t, Type newReturn) {
  3166                 return new ForAll(t.tvars, t.qtype.accept(this, newReturn));
  3168         };
  3170     // <editor-fold defaultstate="collapsed" desc="createErrorType">
  3171     public Type createErrorType(Type originalType) {
  3172         return new ErrorType(originalType, syms.errSymbol);
  3175     public Type createErrorType(ClassSymbol c, Type originalType) {
  3176         return new ErrorType(c, originalType);
  3179     public Type createErrorType(Name name, TypeSymbol container, Type originalType) {
  3180         return new ErrorType(name, container, originalType);
  3182     // </editor-fold>
  3184     // <editor-fold defaultstate="collapsed" desc="rank">
  3185     /**
  3186      * The rank of a class is the length of the longest path between
  3187      * the class and java.lang.Object in the class inheritance
  3188      * graph. Undefined for all but reference types.
  3189      */
  3190     public int rank(Type t) {
  3191         t = t.unannotatedType();
  3192         switch(t.getTag()) {
  3193         case CLASS: {
  3194             ClassType cls = (ClassType)t;
  3195             if (cls.rank_field < 0) {
  3196                 Name fullname = cls.tsym.getQualifiedName();
  3197                 if (fullname == names.java_lang_Object)
  3198                     cls.rank_field = 0;
  3199                 else {
  3200                     int r = rank(supertype(cls));
  3201                     for (List<Type> l = interfaces(cls);
  3202                          l.nonEmpty();
  3203                          l = l.tail) {
  3204                         if (rank(l.head) > r)
  3205                             r = rank(l.head);
  3207                     cls.rank_field = r + 1;
  3210             return cls.rank_field;
  3212         case TYPEVAR: {
  3213             TypeVar tvar = (TypeVar)t;
  3214             if (tvar.rank_field < 0) {
  3215                 int r = rank(supertype(tvar));
  3216                 for (List<Type> l = interfaces(tvar);
  3217                      l.nonEmpty();
  3218                      l = l.tail) {
  3219                     if (rank(l.head) > r) r = rank(l.head);
  3221                 tvar.rank_field = r + 1;
  3223             return tvar.rank_field;
  3225         case ERROR:
  3226             return 0;
  3227         default:
  3228             throw new AssertionError();
  3231     // </editor-fold>
  3233     /**
  3234      * Helper method for generating a string representation of a given type
  3235      * accordingly to a given locale
  3236      */
  3237     public String toString(Type t, Locale locale) {
  3238         return Printer.createStandardPrinter(messages).visit(t, locale);
  3241     /**
  3242      * Helper method for generating a string representation of a given type
  3243      * accordingly to a given locale
  3244      */
  3245     public String toString(Symbol t, Locale locale) {
  3246         return Printer.createStandardPrinter(messages).visit(t, locale);
  3249     // <editor-fold defaultstate="collapsed" desc="toString">
  3250     /**
  3251      * This toString is slightly more descriptive than the one on Type.
  3253      * @deprecated Types.toString(Type t, Locale l) provides better support
  3254      * for localization
  3255      */
  3256     @Deprecated
  3257     public String toString(Type t) {
  3258         if (t.hasTag(FORALL)) {
  3259             ForAll forAll = (ForAll)t;
  3260             return typaramsString(forAll.tvars) + forAll.qtype;
  3262         return "" + t;
  3264     // where
  3265         private String typaramsString(List<Type> tvars) {
  3266             StringBuilder s = new StringBuilder();
  3267             s.append('<');
  3268             boolean first = true;
  3269             for (Type t : tvars) {
  3270                 if (!first) s.append(", ");
  3271                 first = false;
  3272                 appendTyparamString(((TypeVar)t.unannotatedType()), s);
  3274             s.append('>');
  3275             return s.toString();
  3277         private void appendTyparamString(TypeVar t, StringBuilder buf) {
  3278             buf.append(t);
  3279             if (t.bound == null ||
  3280                 t.bound.tsym.getQualifiedName() == names.java_lang_Object)
  3281                 return;
  3282             buf.append(" extends "); // Java syntax; no need for i18n
  3283             Type bound = t.bound;
  3284             if (!bound.isCompound()) {
  3285                 buf.append(bound);
  3286             } else if ((erasure(t).tsym.flags() & INTERFACE) == 0) {
  3287                 buf.append(supertype(t));
  3288                 for (Type intf : interfaces(t)) {
  3289                     buf.append('&');
  3290                     buf.append(intf);
  3292             } else {
  3293                 // No superclass was given in bounds.
  3294                 // In this case, supertype is Object, erasure is first interface.
  3295                 boolean first = true;
  3296                 for (Type intf : interfaces(t)) {
  3297                     if (!first) buf.append('&');
  3298                     first = false;
  3299                     buf.append(intf);
  3303     // </editor-fold>
  3305     // <editor-fold defaultstate="collapsed" desc="Determining least upper bounds of types">
  3306     /**
  3307      * A cache for closures.
  3309      * <p>A closure is a list of all the supertypes and interfaces of
  3310      * a class or interface type, ordered by ClassSymbol.precedes
  3311      * (that is, subclasses come first, arbitrary but fixed
  3312      * otherwise).
  3313      */
  3314     private Map<Type,List<Type>> closureCache = new HashMap<Type,List<Type>>();
  3316     /**
  3317      * Returns the closure of a class or interface type.
  3318      */
  3319     public List<Type> closure(Type t) {
  3320         List<Type> cl = closureCache.get(t);
  3321         if (cl == null) {
  3322             Type st = supertype(t);
  3323             if (!t.isCompound()) {
  3324                 if (st.hasTag(CLASS)) {
  3325                     cl = insert(closure(st), t);
  3326                 } else if (st.hasTag(TYPEVAR)) {
  3327                     cl = closure(st).prepend(t);
  3328                 } else {
  3329                     cl = List.of(t);
  3331             } else {
  3332                 cl = closure(supertype(t));
  3334             for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail)
  3335                 cl = union(cl, closure(l.head));
  3336             closureCache.put(t, cl);
  3338         return cl;
  3341     /**
  3342      * Insert a type in a closure
  3343      */
  3344     public List<Type> insert(List<Type> cl, Type t) {
  3345         if (cl.isEmpty()) {
  3346             return cl.prepend(t);
  3347         } else if (t.tsym == cl.head.tsym) {
  3348             return cl;
  3349         } else if (t.tsym.precedes(cl.head.tsym, this)) {
  3350             return cl.prepend(t);
  3351         } else {
  3352             // t comes after head, or the two are unrelated
  3353             return insert(cl.tail, t).prepend(cl.head);
  3357     /**
  3358      * Form the union of two closures
  3359      */
  3360     public List<Type> union(List<Type> cl1, List<Type> cl2) {
  3361         if (cl1.isEmpty()) {
  3362             return cl2;
  3363         } else if (cl2.isEmpty()) {
  3364             return cl1;
  3365         } else if (cl1.head.tsym == cl2.head.tsym) {
  3366             return union(cl1.tail, cl2.tail).prepend(cl1.head);
  3367         } else if (cl1.head.tsym.precedes(cl2.head.tsym, this)) {
  3368             return union(cl1.tail, cl2).prepend(cl1.head);
  3369         } else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) {
  3370             return union(cl1, cl2.tail).prepend(cl2.head);
  3371         } else {
  3372             // unrelated types
  3373             return union(cl1.tail, cl2).prepend(cl1.head);
  3377     /**
  3378      * Intersect two closures
  3379      */
  3380     public List<Type> intersect(List<Type> cl1, List<Type> cl2) {
  3381         if (cl1 == cl2)
  3382             return cl1;
  3383         if (cl1.isEmpty() || cl2.isEmpty())
  3384             return List.nil();
  3385         if (cl1.head.tsym.precedes(cl2.head.tsym, this))
  3386             return intersect(cl1.tail, cl2);
  3387         if (cl2.head.tsym.precedes(cl1.head.tsym, this))
  3388             return intersect(cl1, cl2.tail);
  3389         if (isSameType(cl1.head, cl2.head))
  3390             return intersect(cl1.tail, cl2.tail).prepend(cl1.head);
  3391         if (cl1.head.tsym == cl2.head.tsym &&
  3392             cl1.head.hasTag(CLASS) && cl2.head.hasTag(CLASS)) {
  3393             if (cl1.head.isParameterized() && cl2.head.isParameterized()) {
  3394                 Type merge = merge(cl1.head,cl2.head);
  3395                 return intersect(cl1.tail, cl2.tail).prepend(merge);
  3397             if (cl1.head.isRaw() || cl2.head.isRaw())
  3398                 return intersect(cl1.tail, cl2.tail).prepend(erasure(cl1.head));
  3400         return intersect(cl1.tail, cl2.tail);
  3402     // where
  3403         class TypePair {
  3404             final Type t1;
  3405             final Type t2;
  3406             TypePair(Type t1, Type t2) {
  3407                 this.t1 = t1;
  3408                 this.t2 = t2;
  3410             @Override
  3411             public int hashCode() {
  3412                 return 127 * Types.this.hashCode(t1) + Types.this.hashCode(t2);
  3414             @Override
  3415             public boolean equals(Object obj) {
  3416                 if (!(obj instanceof TypePair))
  3417                     return false;
  3418                 TypePair typePair = (TypePair)obj;
  3419                 return isSameType(t1, typePair.t1)
  3420                     && isSameType(t2, typePair.t2);
  3423         Set<TypePair> mergeCache = new HashSet<TypePair>();
  3424         private Type merge(Type c1, Type c2) {
  3425             ClassType class1 = (ClassType) c1;
  3426             List<Type> act1 = class1.getTypeArguments();
  3427             ClassType class2 = (ClassType) c2;
  3428             List<Type> act2 = class2.getTypeArguments();
  3429             ListBuffer<Type> merged = new ListBuffer<Type>();
  3430             List<Type> typarams = class1.tsym.type.getTypeArguments();
  3432             while (act1.nonEmpty() && act2.nonEmpty() && typarams.nonEmpty()) {
  3433                 if (containsType(act1.head, act2.head)) {
  3434                     merged.append(act1.head);
  3435                 } else if (containsType(act2.head, act1.head)) {
  3436                     merged.append(act2.head);
  3437                 } else {
  3438                     TypePair pair = new TypePair(c1, c2);
  3439                     Type m;
  3440                     if (mergeCache.add(pair)) {
  3441                         m = new WildcardType(lub(upperBound(act1.head),
  3442                                                  upperBound(act2.head)),
  3443                                              BoundKind.EXTENDS,
  3444                                              syms.boundClass);
  3445                         mergeCache.remove(pair);
  3446                     } else {
  3447                         m = new WildcardType(syms.objectType,
  3448                                              BoundKind.UNBOUND,
  3449                                              syms.boundClass);
  3451                     merged.append(m.withTypeVar(typarams.head));
  3453                 act1 = act1.tail;
  3454                 act2 = act2.tail;
  3455                 typarams = typarams.tail;
  3457             Assert.check(act1.isEmpty() && act2.isEmpty() && typarams.isEmpty());
  3458             return new ClassType(class1.getEnclosingType(), merged.toList(), class1.tsym);
  3461     /**
  3462      * Return the minimum type of a closure, a compound type if no
  3463      * unique minimum exists.
  3464      */
  3465     private Type compoundMin(List<Type> cl) {
  3466         if (cl.isEmpty()) return syms.objectType;
  3467         List<Type> compound = closureMin(cl);
  3468         if (compound.isEmpty())
  3469             return null;
  3470         else if (compound.tail.isEmpty())
  3471             return compound.head;
  3472         else
  3473             return makeCompoundType(compound);
  3476     /**
  3477      * Return the minimum types of a closure, suitable for computing
  3478      * compoundMin or glb.
  3479      */
  3480     private List<Type> closureMin(List<Type> cl) {
  3481         ListBuffer<Type> classes = new ListBuffer<>();
  3482         ListBuffer<Type> interfaces = new ListBuffer<>();
  3483         Set<Type> toSkip = new HashSet<>();
  3484         while (!cl.isEmpty()) {
  3485             Type current = cl.head;
  3486             boolean keep = !toSkip.contains(current);
  3487             if (keep && current.hasTag(TYPEVAR)) {
  3488                 // skip lower-bounded variables with a subtype in cl.tail
  3489                 for (Type t : cl.tail) {
  3490                     if (isSubtypeNoCapture(t, current)) {
  3491                         keep = false;
  3492                         break;
  3496             if (keep) {
  3497                 if (current.isInterface())
  3498                     interfaces.append(current);
  3499                 else
  3500                     classes.append(current);
  3501                 for (Type t : cl.tail) {
  3502                     // skip supertypes of 'current' in cl.tail
  3503                     if (isSubtypeNoCapture(current, t))
  3504                         toSkip.add(t);
  3507             cl = cl.tail;
  3509         return classes.appendList(interfaces).toList();
  3512     /**
  3513      * Return the least upper bound of pair of types.  if the lub does
  3514      * not exist return null.
  3515      */
  3516     public Type lub(Type t1, Type t2) {
  3517         return lub(List.of(t1, t2));
  3520     /**
  3521      * Return the least upper bound (lub) of set of types.  If the lub
  3522      * does not exist return the type of null (bottom).
  3523      */
  3524     public Type lub(List<Type> ts) {
  3525         final int ARRAY_BOUND = 1;
  3526         final int CLASS_BOUND = 2;
  3527         int boundkind = 0;
  3528         for (Type t : ts) {
  3529             switch (t.getTag()) {
  3530             case CLASS:
  3531                 boundkind |= CLASS_BOUND;
  3532                 break;
  3533             case ARRAY:
  3534                 boundkind |= ARRAY_BOUND;
  3535                 break;
  3536             case  TYPEVAR:
  3537                 do {
  3538                     t = t.getUpperBound();
  3539                 } while (t.hasTag(TYPEVAR));
  3540                 if (t.hasTag(ARRAY)) {
  3541                     boundkind |= ARRAY_BOUND;
  3542                 } else {
  3543                     boundkind |= CLASS_BOUND;
  3545                 break;
  3546             default:
  3547                 if (t.isPrimitive())
  3548                     return syms.errType;
  3551         switch (boundkind) {
  3552         case 0:
  3553             return syms.botType;
  3555         case ARRAY_BOUND:
  3556             // calculate lub(A[], B[])
  3557             List<Type> elements = Type.map(ts, elemTypeFun);
  3558             for (Type t : elements) {
  3559                 if (t.isPrimitive()) {
  3560                     // if a primitive type is found, then return
  3561                     // arraySuperType unless all the types are the
  3562                     // same
  3563                     Type first = ts.head;
  3564                     for (Type s : ts.tail) {
  3565                         if (!isSameType(first, s)) {
  3566                              // lub(int[], B[]) is Cloneable & Serializable
  3567                             return arraySuperType();
  3570                     // all the array types are the same, return one
  3571                     // lub(int[], int[]) is int[]
  3572                     return first;
  3575             // lub(A[], B[]) is lub(A, B)[]
  3576             return new ArrayType(lub(elements), syms.arrayClass);
  3578         case CLASS_BOUND:
  3579             // calculate lub(A, B)
  3580             while (!ts.head.hasTag(CLASS) && !ts.head.hasTag(TYPEVAR)) {
  3581                 ts = ts.tail;
  3583             Assert.check(!ts.isEmpty());
  3584             //step 1 - compute erased candidate set (EC)
  3585             List<Type> cl = erasedSupertypes(ts.head);
  3586             for (Type t : ts.tail) {
  3587                 if (t.hasTag(CLASS) || t.hasTag(TYPEVAR))
  3588                     cl = intersect(cl, erasedSupertypes(t));
  3590             //step 2 - compute minimal erased candidate set (MEC)
  3591             List<Type> mec = closureMin(cl);
  3592             //step 3 - for each element G in MEC, compute lci(Inv(G))
  3593             List<Type> candidates = List.nil();
  3594             for (Type erasedSupertype : mec) {
  3595                 List<Type> lci = List.of(asSuper(ts.head, erasedSupertype.tsym));
  3596                 for (Type t : ts) {
  3597                     lci = intersect(lci, List.of(asSuper(t, erasedSupertype.tsym)));
  3599                 candidates = candidates.appendList(lci);
  3601             //step 4 - let MEC be { G1, G2 ... Gn }, then we have that
  3602             //lub = lci(Inv(G1)) & lci(Inv(G2)) & ... & lci(Inv(Gn))
  3603             return compoundMin(candidates);
  3605         default:
  3606             // calculate lub(A, B[])
  3607             List<Type> classes = List.of(arraySuperType());
  3608             for (Type t : ts) {
  3609                 if (!t.hasTag(ARRAY)) // Filter out any arrays
  3610                     classes = classes.prepend(t);
  3612             // lub(A, B[]) is lub(A, arraySuperType)
  3613             return lub(classes);
  3616     // where
  3617         List<Type> erasedSupertypes(Type t) {
  3618             ListBuffer<Type> buf = new ListBuffer<>();
  3619             for (Type sup : closure(t)) {
  3620                 if (sup.hasTag(TYPEVAR)) {
  3621                     buf.append(sup);
  3622                 } else {
  3623                     buf.append(erasure(sup));
  3626             return buf.toList();
  3629         private Type arraySuperType = null;
  3630         private Type arraySuperType() {
  3631             // initialized lazily to avoid problems during compiler startup
  3632             if (arraySuperType == null) {
  3633                 synchronized (this) {
  3634                     if (arraySuperType == null) {
  3635                         // JLS 10.8: all arrays implement Cloneable and Serializable.
  3636                         arraySuperType = makeCompoundType(List.of(syms.serializableType,
  3637                                                                   syms.cloneableType), true);
  3641             return arraySuperType;
  3643     // </editor-fold>
  3645     // <editor-fold defaultstate="collapsed" desc="Greatest lower bound">
  3646     public Type glb(List<Type> ts) {
  3647         Type t1 = ts.head;
  3648         for (Type t2 : ts.tail) {
  3649             if (t1.isErroneous())
  3650                 return t1;
  3651             t1 = glb(t1, t2);
  3653         return t1;
  3655     //where
  3656     public Type glb(Type t, Type s) {
  3657         if (s == null)
  3658             return t;
  3659         else if (t.isPrimitive() || s.isPrimitive())
  3660             return syms.errType;
  3661         else if (isSubtypeNoCapture(t, s))
  3662             return t;
  3663         else if (isSubtypeNoCapture(s, t))
  3664             return s;
  3666         List<Type> closure = union(closure(t), closure(s));
  3667         return glbFlattened(closure, t);
  3669     //where
  3670     /**
  3671      * Perform glb for a list of non-primitive, non-error, non-compound types;
  3672      * redundant elements are removed.  Bounds should be ordered according to
  3673      * {@link Symbol#precedes(TypeSymbol,Types)}.
  3675      * @param flatBounds List of type to glb
  3676      * @param errT Original type to use if the result is an error type
  3677      */
  3678     private Type glbFlattened(List<Type> flatBounds, Type errT) {
  3679         List<Type> bounds = closureMin(flatBounds);
  3681         if (bounds.isEmpty()) {             // length == 0
  3682             return syms.objectType;
  3683         } else if (bounds.tail.isEmpty()) { // length == 1
  3684             return bounds.head;
  3685         } else {                            // length > 1
  3686             int classCount = 0;
  3687             List<Type> lowers = List.nil();
  3688             for (Type bound : bounds) {
  3689                 if (!bound.isInterface()) {
  3690                     classCount++;
  3691                     Type lower = cvarLowerBound(bound);
  3692                     if (bound != lower && !lower.hasTag(BOT))
  3693                         lowers = insert(lowers, lower);
  3696             if (classCount > 1) {
  3697                 if (lowers.isEmpty())
  3698                     return createErrorType(errT);
  3699                 else
  3700                     return glbFlattened(union(bounds, lowers), errT);
  3703         return makeCompoundType(bounds);
  3705     // </editor-fold>
  3707     // <editor-fold defaultstate="collapsed" desc="hashCode">
  3708     /**
  3709      * Compute a hash code on a type.
  3710      */
  3711     public int hashCode(Type t) {
  3712         return hashCode.visit(t);
  3714     // where
  3715         private static final UnaryVisitor<Integer> hashCode = new UnaryVisitor<Integer>() {
  3717             public Integer visitType(Type t, Void ignored) {
  3718                 return t.getTag().ordinal();
  3721             @Override
  3722             public Integer visitClassType(ClassType t, Void ignored) {
  3723                 int result = visit(t.getEnclosingType());
  3724                 result *= 127;
  3725                 result += t.tsym.flatName().hashCode();
  3726                 for (Type s : t.getTypeArguments()) {
  3727                     result *= 127;
  3728                     result += visit(s);
  3730                 return result;
  3733             @Override
  3734             public Integer visitMethodType(MethodType t, Void ignored) {
  3735                 int h = METHOD.ordinal();
  3736                 for (List<Type> thisargs = t.argtypes;
  3737                      thisargs.tail != null;
  3738                      thisargs = thisargs.tail)
  3739                     h = (h << 5) + visit(thisargs.head);
  3740                 return (h << 5) + visit(t.restype);
  3743             @Override
  3744             public Integer visitWildcardType(WildcardType t, Void ignored) {
  3745                 int result = t.kind.hashCode();
  3746                 if (t.type != null) {
  3747                     result *= 127;
  3748                     result += visit(t.type);
  3750                 return result;
  3753             @Override
  3754             public Integer visitArrayType(ArrayType t, Void ignored) {
  3755                 return visit(t.elemtype) + 12;
  3758             @Override
  3759             public Integer visitTypeVar(TypeVar t, Void ignored) {
  3760                 return System.identityHashCode(t.tsym);
  3763             @Override
  3764             public Integer visitUndetVar(UndetVar t, Void ignored) {
  3765                 return System.identityHashCode(t);
  3768             @Override
  3769             public Integer visitErrorType(ErrorType t, Void ignored) {
  3770                 return 0;
  3772         };
  3773     // </editor-fold>
  3775     // <editor-fold defaultstate="collapsed" desc="Return-Type-Substitutable">
  3776     /**
  3777      * Does t have a result that is a subtype of the result type of s,
  3778      * suitable for covariant returns?  It is assumed that both types
  3779      * are (possibly polymorphic) method types.  Monomorphic method
  3780      * types are handled in the obvious way.  Polymorphic method types
  3781      * require renaming all type variables of one to corresponding
  3782      * type variables in the other, where correspondence is by
  3783      * position in the type parameter list. */
  3784     public boolean resultSubtype(Type t, Type s, Warner warner) {
  3785         List<Type> tvars = t.getTypeArguments();
  3786         List<Type> svars = s.getTypeArguments();
  3787         Type tres = t.getReturnType();
  3788         Type sres = subst(s.getReturnType(), svars, tvars);
  3789         return covariantReturnType(tres, sres, warner);
  3792     /**
  3793      * Return-Type-Substitutable.
  3794      * @jls section 8.4.5
  3795      */
  3796     public boolean returnTypeSubstitutable(Type r1, Type r2) {
  3797         if (hasSameArgs(r1, r2))
  3798             return resultSubtype(r1, r2, noWarnings);
  3799         else
  3800             return covariantReturnType(r1.getReturnType(),
  3801                                        erasure(r2.getReturnType()),
  3802                                        noWarnings);
  3805     public boolean returnTypeSubstitutable(Type r1,
  3806                                            Type r2, Type r2res,
  3807                                            Warner warner) {
  3808         if (isSameType(r1.getReturnType(), r2res))
  3809             return true;
  3810         if (r1.getReturnType().isPrimitive() || r2res.isPrimitive())
  3811             return false;
  3813         if (hasSameArgs(r1, r2))
  3814             return covariantReturnType(r1.getReturnType(), r2res, warner);
  3815         if (!allowCovariantReturns)
  3816             return false;
  3817         if (isSubtypeUnchecked(r1.getReturnType(), r2res, warner))
  3818             return true;
  3819         if (!isSubtype(r1.getReturnType(), erasure(r2res)))
  3820             return false;
  3821         warner.warn(LintCategory.UNCHECKED);
  3822         return true;
  3825     /**
  3826      * Is t an appropriate return type in an overrider for a
  3827      * method that returns s?
  3828      */
  3829     public boolean covariantReturnType(Type t, Type s, Warner warner) {
  3830         return
  3831             isSameType(t, s) ||
  3832             allowCovariantReturns &&
  3833             !t.isPrimitive() &&
  3834             !s.isPrimitive() &&
  3835             isAssignable(t, s, warner);
  3837     // </editor-fold>
  3839     // <editor-fold defaultstate="collapsed" desc="Box/unbox support">
  3840     /**
  3841      * Return the class that boxes the given primitive.
  3842      */
  3843     public ClassSymbol boxedClass(Type t) {
  3844         return reader.enterClass(syms.boxedName[t.getTag().ordinal()]);
  3847     /**
  3848      * Return the boxed type if 't' is primitive, otherwise return 't' itself.
  3849      */
  3850     public Type boxedTypeOrType(Type t) {
  3851         return t.isPrimitive() ?
  3852             boxedClass(t).type :
  3853             t;
  3856     /**
  3857      * Return the primitive type corresponding to a boxed type.
  3858      */
  3859     public Type unboxedType(Type t) {
  3860         if (allowBoxing) {
  3861             for (int i=0; i<syms.boxedName.length; i++) {
  3862                 Name box = syms.boxedName[i];
  3863                 if (box != null &&
  3864                     asSuper(t, reader.enterClass(box)) != null)
  3865                     return syms.typeOfTag[i];
  3868         return Type.noType;
  3871     /**
  3872      * Return the unboxed type if 't' is a boxed class, otherwise return 't' itself.
  3873      */
  3874     public Type unboxedTypeOrType(Type t) {
  3875         Type unboxedType = unboxedType(t);
  3876         return unboxedType.hasTag(NONE) ? t : unboxedType;
  3878     // </editor-fold>
  3880     // <editor-fold defaultstate="collapsed" desc="Capture conversion">
  3881     /*
  3882      * JLS 5.1.10 Capture Conversion:
  3884      * Let G name a generic type declaration with n formal type
  3885      * parameters A1 ... An with corresponding bounds U1 ... Un. There
  3886      * exists a capture conversion from G<T1 ... Tn> to G<S1 ... Sn>,
  3887      * where, for 1 <= i <= n:
  3889      * + If Ti is a wildcard type argument (4.5.1) of the form ? then
  3890      *   Si is a fresh type variable whose upper bound is
  3891      *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is the null
  3892      *   type.
  3894      * + If Ti is a wildcard type argument of the form ? extends Bi,
  3895      *   then Si is a fresh type variable whose upper bound is
  3896      *   glb(Bi, Ui[A1 := S1, ..., An := Sn]) and whose lower bound is
  3897      *   the null type, where glb(V1,... ,Vm) is V1 & ... & Vm. It is
  3898      *   a compile-time error if for any two classes (not interfaces)
  3899      *   Vi and Vj,Vi is not a subclass of Vj or vice versa.
  3901      * + If Ti is a wildcard type argument of the form ? super Bi,
  3902      *   then Si is a fresh type variable whose upper bound is
  3903      *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is Bi.
  3905      * + Otherwise, Si = Ti.
  3907      * Capture conversion on any type other than a parameterized type
  3908      * (4.5) acts as an identity conversion (5.1.1). Capture
  3909      * conversions never require a special action at run time and
  3910      * therefore never throw an exception at run time.
  3912      * Capture conversion is not applied recursively.
  3913      */
  3914     /**
  3915      * Capture conversion as specified by the JLS.
  3916      */
  3918     public List<Type> capture(List<Type> ts) {
  3919         List<Type> buf = List.nil();
  3920         for (Type t : ts) {
  3921             buf = buf.prepend(capture(t));
  3923         return buf.reverse();
  3926     public Type capture(Type t) {
  3927         if (!t.hasTag(CLASS)) {
  3928             return t;
  3930         if (t.getEnclosingType() != Type.noType) {
  3931             Type capturedEncl = capture(t.getEnclosingType());
  3932             if (capturedEncl != t.getEnclosingType()) {
  3933                 Type type1 = memberType(capturedEncl, t.tsym);
  3934                 t = subst(type1, t.tsym.type.getTypeArguments(), t.getTypeArguments());
  3937         t = t.unannotatedType();
  3938         ClassType cls = (ClassType)t;
  3939         if (cls.isRaw() || !cls.isParameterized())
  3940             return cls;
  3942         ClassType G = (ClassType)cls.asElement().asType();
  3943         List<Type> A = G.getTypeArguments();
  3944         List<Type> T = cls.getTypeArguments();
  3945         List<Type> S = freshTypeVariables(T);
  3947         List<Type> currentA = A;
  3948         List<Type> currentT = T;
  3949         List<Type> currentS = S;
  3950         boolean captured = false;
  3951         while (!currentA.isEmpty() &&
  3952                !currentT.isEmpty() &&
  3953                !currentS.isEmpty()) {
  3954             if (currentS.head != currentT.head) {
  3955                 captured = true;
  3956                 WildcardType Ti = (WildcardType)currentT.head.unannotatedType();
  3957                 Type Ui = currentA.head.getUpperBound();
  3958                 CapturedType Si = (CapturedType)currentS.head.unannotatedType();
  3959                 if (Ui == null)
  3960                     Ui = syms.objectType;
  3961                 switch (Ti.kind) {
  3962                 case UNBOUND:
  3963                     Si.bound = subst(Ui, A, S);
  3964                     Si.lower = syms.botType;
  3965                     break;
  3966                 case EXTENDS:
  3967                     Si.bound = glb(Ti.getExtendsBound(), subst(Ui, A, S));
  3968                     Si.lower = syms.botType;
  3969                     break;
  3970                 case SUPER:
  3971                     Si.bound = subst(Ui, A, S);
  3972                     Si.lower = Ti.getSuperBound();
  3973                     break;
  3975                 Type tmpBound = Si.bound.hasTag(UNDETVAR) ? ((UndetVar)Si.bound).qtype : Si.bound;
  3976                 Type tmpLower = Si.lower.hasTag(UNDETVAR) ? ((UndetVar)Si.lower).qtype : Si.lower;
  3977                 if (!Si.bound.hasTag(ERROR) &&
  3978                     !Si.lower.hasTag(ERROR) &&
  3979                     isSameType(tmpBound, tmpLower, false)) {
  3980                     currentS.head = Si.bound;
  3983             currentA = currentA.tail;
  3984             currentT = currentT.tail;
  3985             currentS = currentS.tail;
  3987         if (!currentA.isEmpty() || !currentT.isEmpty() || !currentS.isEmpty())
  3988             return erasure(t); // some "rare" type involved
  3990         if (captured)
  3991             return new ClassType(cls.getEnclosingType(), S, cls.tsym);
  3992         else
  3993             return t;
  3995     // where
  3996         public List<Type> freshTypeVariables(List<Type> types) {
  3997             ListBuffer<Type> result = new ListBuffer<>();
  3998             for (Type t : types) {
  3999                 if (t.hasTag(WILDCARD)) {
  4000                     t = t.unannotatedType();
  4001                     Type bound = ((WildcardType)t).getExtendsBound();
  4002                     if (bound == null)
  4003                         bound = syms.objectType;
  4004                     result.append(new CapturedType(capturedName,
  4005                                                    syms.noSymbol,
  4006                                                    bound,
  4007                                                    syms.botType,
  4008                                                    (WildcardType)t));
  4009                 } else {
  4010                     result.append(t);
  4013             return result.toList();
  4015     // </editor-fold>
  4017     // <editor-fold defaultstate="collapsed" desc="Internal utility methods">
  4018     private List<Type> upperBounds(List<Type> ss) {
  4019         if (ss.isEmpty()) return ss;
  4020         Type head = upperBound(ss.head);
  4021         List<Type> tail = upperBounds(ss.tail);
  4022         if (head != ss.head || tail != ss.tail)
  4023             return tail.prepend(head);
  4024         else
  4025             return ss;
  4028     private boolean sideCast(Type from, Type to, Warner warn) {
  4029         // We are casting from type $from$ to type $to$, which are
  4030         // non-final unrelated types.  This method
  4031         // tries to reject a cast by transferring type parameters
  4032         // from $to$ to $from$ by common superinterfaces.
  4033         boolean reverse = false;
  4034         Type target = to;
  4035         if ((to.tsym.flags() & INTERFACE) == 0) {
  4036             Assert.check((from.tsym.flags() & INTERFACE) != 0);
  4037             reverse = true;
  4038             to = from;
  4039             from = target;
  4041         List<Type> commonSupers = superClosure(to, erasure(from));
  4042         boolean giveWarning = commonSupers.isEmpty();
  4043         // The arguments to the supers could be unified here to
  4044         // get a more accurate analysis
  4045         while (commonSupers.nonEmpty()) {
  4046             Type t1 = asSuper(from, commonSupers.head.tsym);
  4047             Type t2 = commonSupers.head; // same as asSuper(to, commonSupers.head.tsym);
  4048             if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
  4049                 return false;
  4050             giveWarning = giveWarning || (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2));
  4051             commonSupers = commonSupers.tail;
  4053         if (giveWarning && !isReifiable(reverse ? from : to))
  4054             warn.warn(LintCategory.UNCHECKED);
  4055         if (!allowCovariantReturns)
  4056             // reject if there is a common method signature with
  4057             // incompatible return types.
  4058             chk.checkCompatibleAbstracts(warn.pos(), from, to);
  4059         return true;
  4062     private boolean sideCastFinal(Type from, Type to, Warner warn) {
  4063         // We are casting from type $from$ to type $to$, which are
  4064         // unrelated types one of which is final and the other of
  4065         // which is an interface.  This method
  4066         // tries to reject a cast by transferring type parameters
  4067         // from the final class to the interface.
  4068         boolean reverse = false;
  4069         Type target = to;
  4070         if ((to.tsym.flags() & INTERFACE) == 0) {
  4071             Assert.check((from.tsym.flags() & INTERFACE) != 0);
  4072             reverse = true;
  4073             to = from;
  4074             from = target;
  4076         Assert.check((from.tsym.flags() & FINAL) != 0);
  4077         Type t1 = asSuper(from, to.tsym);
  4078         if (t1 == null) return false;
  4079         Type t2 = to;
  4080         if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
  4081             return false;
  4082         if (!allowCovariantReturns)
  4083             // reject if there is a common method signature with
  4084             // incompatible return types.
  4085             chk.checkCompatibleAbstracts(warn.pos(), from, to);
  4086         if (!isReifiable(target) &&
  4087             (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2)))
  4088             warn.warn(LintCategory.UNCHECKED);
  4089         return true;
  4092     private boolean giveWarning(Type from, Type to) {
  4093         List<Type> bounds = to.isCompound() ?
  4094                 ((IntersectionClassType)to.unannotatedType()).getComponents() : List.of(to);
  4095         for (Type b : bounds) {
  4096             Type subFrom = asSub(from, b.tsym);
  4097             if (b.isParameterized() &&
  4098                     (!(isUnbounded(b) ||
  4099                     isSubtype(from, b) ||
  4100                     ((subFrom != null) && containsType(b.allparams(), subFrom.allparams()))))) {
  4101                 return true;
  4104         return false;
  4107     private List<Type> superClosure(Type t, Type s) {
  4108         List<Type> cl = List.nil();
  4109         for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
  4110             if (isSubtype(s, erasure(l.head))) {
  4111                 cl = insert(cl, l.head);
  4112             } else {
  4113                 cl = union(cl, superClosure(l.head, s));
  4116         return cl;
  4119     private boolean containsTypeEquivalent(Type t, Type s) {
  4120         return
  4121             isSameType(t, s) || // shortcut
  4122             containsType(t, s) && containsType(s, t);
  4125     // <editor-fold defaultstate="collapsed" desc="adapt">
  4126     /**
  4127      * Adapt a type by computing a substitution which maps a source
  4128      * type to a target type.
  4130      * @param source    the source type
  4131      * @param target    the target type
  4132      * @param from      the type variables of the computed substitution
  4133      * @param to        the types of the computed substitution.
  4134      */
  4135     public void adapt(Type source,
  4136                        Type target,
  4137                        ListBuffer<Type> from,
  4138                        ListBuffer<Type> to) throws AdaptFailure {
  4139         new Adapter(from, to).adapt(source, target);
  4142     class Adapter extends SimpleVisitor<Void, Type> {
  4144         ListBuffer<Type> from;
  4145         ListBuffer<Type> to;
  4146         Map<Symbol,Type> mapping;
  4148         Adapter(ListBuffer<Type> from, ListBuffer<Type> to) {
  4149             this.from = from;
  4150             this.to = to;
  4151             mapping = new HashMap<Symbol,Type>();
  4154         public void adapt(Type source, Type target) throws AdaptFailure {
  4155             visit(source, target);
  4156             List<Type> fromList = from.toList();
  4157             List<Type> toList = to.toList();
  4158             while (!fromList.isEmpty()) {
  4159                 Type val = mapping.get(fromList.head.tsym);
  4160                 if (toList.head != val)
  4161                     toList.head = val;
  4162                 fromList = fromList.tail;
  4163                 toList = toList.tail;
  4167         @Override
  4168         public Void visitClassType(ClassType source, Type target) throws AdaptFailure {
  4169             if (target.hasTag(CLASS))
  4170                 adaptRecursive(source.allparams(), target.allparams());
  4171             return null;
  4174         @Override
  4175         public Void visitArrayType(ArrayType source, Type target) throws AdaptFailure {
  4176             if (target.hasTag(ARRAY))
  4177                 adaptRecursive(elemtype(source), elemtype(target));
  4178             return null;
  4181         @Override
  4182         public Void visitWildcardType(WildcardType source, Type target) throws AdaptFailure {
  4183             if (source.isExtendsBound())
  4184                 adaptRecursive(upperBound(source), upperBound(target));
  4185             else if (source.isSuperBound())
  4186                 adaptRecursive(wildLowerBound(source), wildLowerBound(target));
  4187             return null;
  4190         @Override
  4191         public Void visitTypeVar(TypeVar source, Type target) throws AdaptFailure {
  4192             // Check to see if there is
  4193             // already a mapping for $source$, in which case
  4194             // the old mapping will be merged with the new
  4195             Type val = mapping.get(source.tsym);
  4196             if (val != null) {
  4197                 if (val.isSuperBound() && target.isSuperBound()) {
  4198                     val = isSubtype(wildLowerBound(val), wildLowerBound(target))
  4199                         ? target : val;
  4200                 } else if (val.isExtendsBound() && target.isExtendsBound()) {
  4201                     val = isSubtype(upperBound(val), upperBound(target))
  4202                         ? val : target;
  4203                 } else if (!isSameType(val, target)) {
  4204                     throw new AdaptFailure();
  4206             } else {
  4207                 val = target;
  4208                 from.append(source);
  4209                 to.append(target);
  4211             mapping.put(source.tsym, val);
  4212             return null;
  4215         @Override
  4216         public Void visitType(Type source, Type target) {
  4217             return null;
  4220         private Set<TypePair> cache = new HashSet<TypePair>();
  4222         private void adaptRecursive(Type source, Type target) {
  4223             TypePair pair = new TypePair(source, target);
  4224             if (cache.add(pair)) {
  4225                 try {
  4226                     visit(source, target);
  4227                 } finally {
  4228                     cache.remove(pair);
  4233         private void adaptRecursive(List<Type> source, List<Type> target) {
  4234             if (source.length() == target.length()) {
  4235                 while (source.nonEmpty()) {
  4236                     adaptRecursive(source.head, target.head);
  4237                     source = source.tail;
  4238                     target = target.tail;
  4244     public static class AdaptFailure extends RuntimeException {
  4245         static final long serialVersionUID = -7490231548272701566L;
  4248     private void adaptSelf(Type t,
  4249                            ListBuffer<Type> from,
  4250                            ListBuffer<Type> to) {
  4251         try {
  4252             //if (t.tsym.type != t)
  4253                 adapt(t.tsym.type, t, from, to);
  4254         } catch (AdaptFailure ex) {
  4255             // Adapt should never fail calculating a mapping from
  4256             // t.tsym.type to t as there can be no merge problem.
  4257             throw new AssertionError(ex);
  4260     // </editor-fold>
  4262     /**
  4263      * Rewrite all type variables (universal quantifiers) in the given
  4264      * type to wildcards (existential quantifiers).  This is used to
  4265      * determine if a cast is allowed.  For example, if high is true
  4266      * and {@code T <: Number}, then {@code List<T>} is rewritten to
  4267      * {@code List<?  extends Number>}.  Since {@code List<Integer> <:
  4268      * List<? extends Number>} a {@code List<T>} can be cast to {@code
  4269      * List<Integer>} with a warning.
  4270      * @param t a type
  4271      * @param high if true return an upper bound; otherwise a lower
  4272      * bound
  4273      * @param rewriteTypeVars only rewrite captured wildcards if false;
  4274      * otherwise rewrite all type variables
  4275      * @return the type rewritten with wildcards (existential
  4276      * quantifiers) only
  4277      */
  4278     private Type rewriteQuantifiers(Type t, boolean high, boolean rewriteTypeVars) {
  4279         return new Rewriter(high, rewriteTypeVars).visit(t);
  4282     class Rewriter extends UnaryVisitor<Type> {
  4284         boolean high;
  4285         boolean rewriteTypeVars;
  4287         Rewriter(boolean high, boolean rewriteTypeVars) {
  4288             this.high = high;
  4289             this.rewriteTypeVars = rewriteTypeVars;
  4292         @Override
  4293         public Type visitClassType(ClassType t, Void s) {
  4294             ListBuffer<Type> rewritten = new ListBuffer<Type>();
  4295             boolean changed = false;
  4296             for (Type arg : t.allparams()) {
  4297                 Type bound = visit(arg);
  4298                 if (arg != bound) {
  4299                     changed = true;
  4301                 rewritten.append(bound);
  4303             if (changed)
  4304                 return subst(t.tsym.type,
  4305                         t.tsym.type.allparams(),
  4306                         rewritten.toList());
  4307             else
  4308                 return t;
  4311         public Type visitType(Type t, Void s) {
  4312             return high ? upperBound(t) : t;
  4315         @Override
  4316         public Type visitCapturedType(CapturedType t, Void s) {
  4317             Type w_bound = t.wildcard.type;
  4318             Type bound = w_bound.contains(t) ?
  4319                         erasure(w_bound) :
  4320                         visit(w_bound);
  4321             return rewriteAsWildcardType(visit(bound), t.wildcard.bound, t.wildcard.kind);
  4324         @Override
  4325         public Type visitTypeVar(TypeVar t, Void s) {
  4326             if (rewriteTypeVars) {
  4327                 Type bound = t.bound.contains(t) ?
  4328                         erasure(t.bound) :
  4329                         visit(t.bound);
  4330                 return rewriteAsWildcardType(bound, t, EXTENDS);
  4331             } else {
  4332                 return t;
  4336         @Override
  4337         public Type visitWildcardType(WildcardType t, Void s) {
  4338             Type bound2 = visit(t.type);
  4339             return t.type == bound2 ? t : rewriteAsWildcardType(bound2, t.bound, t.kind);
  4342         private Type rewriteAsWildcardType(Type bound, TypeVar formal, BoundKind bk) {
  4343             switch (bk) {
  4344                case EXTENDS: return high ?
  4345                        makeExtendsWildcard(B(bound), formal) :
  4346                        makeExtendsWildcard(syms.objectType, formal);
  4347                case SUPER: return high ?
  4348                        makeSuperWildcard(syms.botType, formal) :
  4349                        makeSuperWildcard(B(bound), formal);
  4350                case UNBOUND: return makeExtendsWildcard(syms.objectType, formal);
  4351                default:
  4352                    Assert.error("Invalid bound kind " + bk);
  4353                    return null;
  4357         Type B(Type t) {
  4358             while (t.hasTag(WILDCARD)) {
  4359                 WildcardType w = (WildcardType)t.unannotatedType();
  4360                 t = high ?
  4361                     w.getExtendsBound() :
  4362                     w.getSuperBound();
  4363                 if (t == null) {
  4364                     t = high ? syms.objectType : syms.botType;
  4367             return t;
  4372     /**
  4373      * Create a wildcard with the given upper (extends) bound; create
  4374      * an unbounded wildcard if bound is Object.
  4376      * @param bound the upper bound
  4377      * @param formal the formal type parameter that will be
  4378      * substituted by the wildcard
  4379      */
  4380     private WildcardType makeExtendsWildcard(Type bound, TypeVar formal) {
  4381         if (bound == syms.objectType) {
  4382             return new WildcardType(syms.objectType,
  4383                                     BoundKind.UNBOUND,
  4384                                     syms.boundClass,
  4385                                     formal);
  4386         } else {
  4387             return new WildcardType(bound,
  4388                                     BoundKind.EXTENDS,
  4389                                     syms.boundClass,
  4390                                     formal);
  4394     /**
  4395      * Create a wildcard with the given lower (super) bound; create an
  4396      * unbounded wildcard if bound is bottom (type of {@code null}).
  4398      * @param bound the lower bound
  4399      * @param formal the formal type parameter that will be
  4400      * substituted by the wildcard
  4401      */
  4402     private WildcardType makeSuperWildcard(Type bound, TypeVar formal) {
  4403         if (bound.hasTag(BOT)) {
  4404             return new WildcardType(syms.objectType,
  4405                                     BoundKind.UNBOUND,
  4406                                     syms.boundClass,
  4407                                     formal);
  4408         } else {
  4409             return new WildcardType(bound,
  4410                                     BoundKind.SUPER,
  4411                                     syms.boundClass,
  4412                                     formal);
  4416     /**
  4417      * A wrapper for a type that allows use in sets.
  4418      */
  4419     public static class UniqueType {
  4420         public final Type type;
  4421         final Types types;
  4423         public UniqueType(Type type, Types types) {
  4424             this.type = type;
  4425             this.types = types;
  4428         public int hashCode() {
  4429             return types.hashCode(type);
  4432         public boolean equals(Object obj) {
  4433             return (obj instanceof UniqueType) &&
  4434                 types.isSameAnnotatedType(type, ((UniqueType)obj).type);
  4437         public String toString() {
  4438             return type.toString();
  4442     // </editor-fold>
  4444     // <editor-fold defaultstate="collapsed" desc="Visitors">
  4445     /**
  4446      * A default visitor for types.  All visitor methods except
  4447      * visitType are implemented by delegating to visitType.  Concrete
  4448      * subclasses must provide an implementation of visitType and can
  4449      * override other methods as needed.
  4451      * @param <R> the return type of the operation implemented by this
  4452      * visitor; use Void if no return type is needed.
  4453      * @param <S> the type of the second argument (the first being the
  4454      * type itself) of the operation implemented by this visitor; use
  4455      * Void if a second argument is not needed.
  4456      */
  4457     public static abstract class DefaultTypeVisitor<R,S> implements Type.Visitor<R,S> {
  4458         final public R visit(Type t, S s)               { return t.accept(this, s); }
  4459         public R visitClassType(ClassType t, S s)       { return visitType(t, s); }
  4460         public R visitWildcardType(WildcardType t, S s) { return visitType(t, s); }
  4461         public R visitArrayType(ArrayType t, S s)       { return visitType(t, s); }
  4462         public R visitMethodType(MethodType t, S s)     { return visitType(t, s); }
  4463         public R visitPackageType(PackageType t, S s)   { return visitType(t, s); }
  4464         public R visitTypeVar(TypeVar t, S s)           { return visitType(t, s); }
  4465         public R visitCapturedType(CapturedType t, S s) { return visitType(t, s); }
  4466         public R visitForAll(ForAll t, S s)             { return visitType(t, s); }
  4467         public R visitUndetVar(UndetVar t, S s)         { return visitType(t, s); }
  4468         public R visitErrorType(ErrorType t, S s)       { return visitType(t, s); }
  4469         // Pretend annotations don't exist
  4470         public R visitAnnotatedType(AnnotatedType t, S s) { return visit(t.unannotatedType(), s); }
  4473     /**
  4474      * A default visitor for symbols.  All visitor methods except
  4475      * visitSymbol are implemented by delegating to visitSymbol.  Concrete
  4476      * subclasses must provide an implementation of visitSymbol and can
  4477      * override other methods as needed.
  4479      * @param <R> the return type of the operation implemented by this
  4480      * visitor; use Void if no return type is needed.
  4481      * @param <S> the type of the second argument (the first being the
  4482      * symbol itself) of the operation implemented by this visitor; use
  4483      * Void if a second argument is not needed.
  4484      */
  4485     public static abstract class DefaultSymbolVisitor<R,S> implements Symbol.Visitor<R,S> {
  4486         final public R visit(Symbol s, S arg)                   { return s.accept(this, arg); }
  4487         public R visitClassSymbol(ClassSymbol s, S arg)         { return visitSymbol(s, arg); }
  4488         public R visitMethodSymbol(MethodSymbol s, S arg)       { return visitSymbol(s, arg); }
  4489         public R visitOperatorSymbol(OperatorSymbol s, S arg)   { return visitSymbol(s, arg); }
  4490         public R visitPackageSymbol(PackageSymbol s, S arg)     { return visitSymbol(s, arg); }
  4491         public R visitTypeSymbol(TypeSymbol s, S arg)           { return visitSymbol(s, arg); }
  4492         public R visitVarSymbol(VarSymbol s, S arg)             { return visitSymbol(s, arg); }
  4495     /**
  4496      * A <em>simple</em> visitor for types.  This visitor is simple as
  4497      * captured wildcards, for-all types (generic methods), and
  4498      * undetermined type variables (part of inference) are hidden.
  4499      * Captured wildcards are hidden by treating them as type
  4500      * variables and the rest are hidden by visiting their qtypes.
  4502      * @param <R> the return type of the operation implemented by this
  4503      * visitor; use Void if no return type is needed.
  4504      * @param <S> the type of the second argument (the first being the
  4505      * type itself) of the operation implemented by this visitor; use
  4506      * Void if a second argument is not needed.
  4507      */
  4508     public static abstract class SimpleVisitor<R,S> extends DefaultTypeVisitor<R,S> {
  4509         @Override
  4510         public R visitCapturedType(CapturedType t, S s) {
  4511             return visitTypeVar(t, s);
  4513         @Override
  4514         public R visitForAll(ForAll t, S s) {
  4515             return visit(t.qtype, s);
  4517         @Override
  4518         public R visitUndetVar(UndetVar t, S s) {
  4519             return visit(t.qtype, s);
  4523     /**
  4524      * A plain relation on types.  That is a 2-ary function on the
  4525      * form Type&nbsp;&times;&nbsp;Type&nbsp;&rarr;&nbsp;Boolean.
  4526      * <!-- In plain text: Type x Type -> Boolean -->
  4527      */
  4528     public static abstract class TypeRelation extends SimpleVisitor<Boolean,Type> {}
  4530     /**
  4531      * A convenience visitor for implementing operations that only
  4532      * require one argument (the type itself), that is, unary
  4533      * operations.
  4535      * @param <R> the return type of the operation implemented by this
  4536      * visitor; use Void if no return type is needed.
  4537      */
  4538     public static abstract class UnaryVisitor<R> extends SimpleVisitor<R,Void> {
  4539         final public R visit(Type t) { return t.accept(this, null); }
  4542     /**
  4543      * A visitor for implementing a mapping from types to types.  The
  4544      * default behavior of this class is to implement the identity
  4545      * mapping (mapping a type to itself).  This can be overridden in
  4546      * subclasses.
  4548      * @param <S> the type of the second argument (the first being the
  4549      * type itself) of this mapping; use Void if a second argument is
  4550      * not needed.
  4551      */
  4552     public static class MapVisitor<S> extends DefaultTypeVisitor<Type,S> {
  4553         final public Type visit(Type t) { return t.accept(this, null); }
  4554         public Type visitType(Type t, S s) { return t; }
  4556     // </editor-fold>
  4559     // <editor-fold defaultstate="collapsed" desc="Annotation support">
  4561     public RetentionPolicy getRetention(Attribute.Compound a) {
  4562         return getRetention(a.type.tsym);
  4565     public RetentionPolicy getRetention(Symbol sym) {
  4566         RetentionPolicy vis = RetentionPolicy.CLASS; // the default
  4567         Attribute.Compound c = sym.attribute(syms.retentionType.tsym);
  4568         if (c != null) {
  4569             Attribute value = c.member(names.value);
  4570             if (value != null && value instanceof Attribute.Enum) {
  4571                 Name levelName = ((Attribute.Enum)value).value.name;
  4572                 if (levelName == names.SOURCE) vis = RetentionPolicy.SOURCE;
  4573                 else if (levelName == names.CLASS) vis = RetentionPolicy.CLASS;
  4574                 else if (levelName == names.RUNTIME) vis = RetentionPolicy.RUNTIME;
  4575                 else ;// /* fail soft */ throw new AssertionError(levelName);
  4578         return vis;
  4580     // </editor-fold>
  4582     // <editor-fold defaultstate="collapsed" desc="Signature Generation">
  4584     public static abstract class SignatureGenerator {
  4586         private final Types types;
  4588         protected abstract void append(char ch);
  4589         protected abstract void append(byte[] ba);
  4590         protected abstract void append(Name name);
  4591         protected void classReference(ClassSymbol c) { /* by default: no-op */ }
  4593         protected SignatureGenerator(Types types) {
  4594             this.types = types;
  4597         /**
  4598          * Assemble signature of given type in string buffer.
  4599          */
  4600         public void assembleSig(Type type) {
  4601             type = type.unannotatedType();
  4602             switch (type.getTag()) {
  4603                 case BYTE:
  4604                     append('B');
  4605                     break;
  4606                 case SHORT:
  4607                     append('S');
  4608                     break;
  4609                 case CHAR:
  4610                     append('C');
  4611                     break;
  4612                 case INT:
  4613                     append('I');
  4614                     break;
  4615                 case LONG:
  4616                     append('J');
  4617                     break;
  4618                 case FLOAT:
  4619                     append('F');
  4620                     break;
  4621                 case DOUBLE:
  4622                     append('D');
  4623                     break;
  4624                 case BOOLEAN:
  4625                     append('Z');
  4626                     break;
  4627                 case VOID:
  4628                     append('V');
  4629                     break;
  4630                 case CLASS:
  4631                     append('L');
  4632                     assembleClassSig(type);
  4633                     append(';');
  4634                     break;
  4635                 case ARRAY:
  4636                     ArrayType at = (ArrayType) type;
  4637                     append('[');
  4638                     assembleSig(at.elemtype);
  4639                     break;
  4640                 case METHOD:
  4641                     MethodType mt = (MethodType) type;
  4642                     append('(');
  4643                     assembleSig(mt.argtypes);
  4644                     append(')');
  4645                     assembleSig(mt.restype);
  4646                     if (hasTypeVar(mt.thrown)) {
  4647                         for (List<Type> l = mt.thrown; l.nonEmpty(); l = l.tail) {
  4648                             append('^');
  4649                             assembleSig(l.head);
  4652                     break;
  4653                 case WILDCARD: {
  4654                     Type.WildcardType ta = (Type.WildcardType) type;
  4655                     switch (ta.kind) {
  4656                         case SUPER:
  4657                             append('-');
  4658                             assembleSig(ta.type);
  4659                             break;
  4660                         case EXTENDS:
  4661                             append('+');
  4662                             assembleSig(ta.type);
  4663                             break;
  4664                         case UNBOUND:
  4665                             append('*');
  4666                             break;
  4667                         default:
  4668                             throw new AssertionError(ta.kind);
  4670                     break;
  4672                 case TYPEVAR:
  4673                     append('T');
  4674                     append(type.tsym.name);
  4675                     append(';');
  4676                     break;
  4677                 case FORALL:
  4678                     Type.ForAll ft = (Type.ForAll) type;
  4679                     assembleParamsSig(ft.tvars);
  4680                     assembleSig(ft.qtype);
  4681                     break;
  4682                 default:
  4683                     throw new AssertionError("typeSig " + type.getTag());
  4687         public boolean hasTypeVar(List<Type> l) {
  4688             while (l.nonEmpty()) {
  4689                 if (l.head.hasTag(TypeTag.TYPEVAR)) {
  4690                     return true;
  4692                 l = l.tail;
  4694             return false;
  4697         public void assembleClassSig(Type type) {
  4698             type = type.unannotatedType();
  4699             ClassType ct = (ClassType) type;
  4700             ClassSymbol c = (ClassSymbol) ct.tsym;
  4701             classReference(c);
  4702             Type outer = ct.getEnclosingType();
  4703             if (outer.allparams().nonEmpty()) {
  4704                 boolean rawOuter =
  4705                         c.owner.kind == Kinds.MTH || // either a local class
  4706                         c.name == types.names.empty; // or anonymous
  4707                 assembleClassSig(rawOuter
  4708                         ? types.erasure(outer)
  4709                         : outer);
  4710                 append('.');
  4711                 Assert.check(c.flatname.startsWith(c.owner.enclClass().flatname));
  4712                 append(rawOuter
  4713                         ? c.flatname.subName(c.owner.enclClass().flatname.getByteLength() + 1, c.flatname.getByteLength())
  4714                         : c.name);
  4715             } else {
  4716                 append(externalize(c.flatname));
  4718             if (ct.getTypeArguments().nonEmpty()) {
  4719                 append('<');
  4720                 assembleSig(ct.getTypeArguments());
  4721                 append('>');
  4725         public void assembleParamsSig(List<Type> typarams) {
  4726             append('<');
  4727             for (List<Type> ts = typarams; ts.nonEmpty(); ts = ts.tail) {
  4728                 Type.TypeVar tvar = (Type.TypeVar) ts.head;
  4729                 append(tvar.tsym.name);
  4730                 List<Type> bounds = types.getBounds(tvar);
  4731                 if ((bounds.head.tsym.flags() & INTERFACE) != 0) {
  4732                     append(':');
  4734                 for (List<Type> l = bounds; l.nonEmpty(); l = l.tail) {
  4735                     append(':');
  4736                     assembleSig(l.head);
  4739             append('>');
  4742         private void assembleSig(List<Type> types) {
  4743             for (List<Type> ts = types; ts.nonEmpty(); ts = ts.tail) {
  4744                 assembleSig(ts.head);
  4748     // </editor-fold>

mercurial