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

Fri, 02 May 2014 01:25:26 +0100

author
vromero
date
Fri, 02 May 2014 01:25:26 +0100
changeset 2382
14979dd5e034
parent 2260
fb870c70e774
child 2384
327122b01a9e
permissions
-rw-r--r--

8030741: Inference: implement eager resolution of return types, consistent with JDK-8028800
Reviewed-by: dlsmith, jjg

     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="lowerBound">
   156     /**
   157      * The "lvalue conversion".<br>
   158      * The lower bound of most types is the type
   159      * itself.  Wildcards, on the other hand have upper
   160      * and lower bounds.
   161      * @param t a type
   162      * @return the lower bound of the given type
   163      */
   164     public Type lowerBound(Type t) {
   165         return lowerBound.visit(t);
   166     }
   167     // where
   168         private final MapVisitor<Void> lowerBound = new MapVisitor<Void>() {
   170             @Override
   171             public Type visitWildcardType(WildcardType t, Void ignored) {
   172                 return t.isExtendsBound() ? syms.botType : visit(t.type);
   173             }
   175             @Override
   176             public Type visitCapturedType(CapturedType t, Void ignored) {
   177                 return visit(t.getLowerBound());
   178             }
   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         Type lower = lowerBound(s);
   832         if (s != lower)
   833             return isSubtype(capture ? capture(t) : t, lower, false);
   835         return isSubtype.visit(capture ? capture(t) : t, s);
   836     }
   837     // where
   838         private TypeRelation isSubtype = new TypeRelation()
   839         {
   840             @Override
   841             public Boolean visitType(Type t, Type s) {
   842                 switch (t.getTag()) {
   843                  case BYTE:
   844                      return (!s.hasTag(CHAR) && t.getTag().isSubRangeOf(s.getTag()));
   845                  case CHAR:
   846                      return (!s.hasTag(SHORT) && t.getTag().isSubRangeOf(s.getTag()));
   847                  case SHORT: case INT: case LONG:
   848                  case FLOAT: case DOUBLE:
   849                      return t.getTag().isSubRangeOf(s.getTag());
   850                  case BOOLEAN: case VOID:
   851                      return t.hasTag(s.getTag());
   852                  case TYPEVAR:
   853                      return isSubtypeNoCapture(t.getUpperBound(), s);
   854                  case BOT:
   855                      return
   856                          s.hasTag(BOT) || s.hasTag(CLASS) ||
   857                          s.hasTag(ARRAY) || s.hasTag(TYPEVAR);
   858                  case WILDCARD: //we shouldn't be here - avoids crash (see 7034495)
   859                  case NONE:
   860                      return false;
   861                  default:
   862                      throw new AssertionError("isSubtype " + t.getTag());
   863                  }
   864             }
   866             private Set<TypePair> cache = new HashSet<TypePair>();
   868             private boolean containsTypeRecursive(Type t, Type s) {
   869                 TypePair pair = new TypePair(t, s);
   870                 if (cache.add(pair)) {
   871                     try {
   872                         return containsType(t.getTypeArguments(),
   873                                             s.getTypeArguments());
   874                     } finally {
   875                         cache.remove(pair);
   876                     }
   877                 } else {
   878                     return containsType(t.getTypeArguments(),
   879                                         rewriteSupers(s).getTypeArguments());
   880                 }
   881             }
   883             private Type rewriteSupers(Type t) {
   884                 if (!t.isParameterized())
   885                     return t;
   886                 ListBuffer<Type> from = new ListBuffer<>();
   887                 ListBuffer<Type> to = new ListBuffer<>();
   888                 adaptSelf(t, from, to);
   889                 if (from.isEmpty())
   890                     return t;
   891                 ListBuffer<Type> rewrite = new ListBuffer<>();
   892                 boolean changed = false;
   893                 for (Type orig : to.toList()) {
   894                     Type s = rewriteSupers(orig);
   895                     if (s.isSuperBound() && !s.isExtendsBound()) {
   896                         s = new WildcardType(syms.objectType,
   897                                              BoundKind.UNBOUND,
   898                                              syms.boundClass);
   899                         changed = true;
   900                     } else if (s != orig) {
   901                         s = new WildcardType(upperBound(s),
   902                                              BoundKind.EXTENDS,
   903                                              syms.boundClass);
   904                         changed = true;
   905                     }
   906                     rewrite.append(s);
   907                 }
   908                 if (changed)
   909                     return subst(t.tsym.type, from.toList(), rewrite.toList());
   910                 else
   911                     return t;
   912             }
   914             @Override
   915             public Boolean visitClassType(ClassType t, Type s) {
   916                 Type sup = asSuper(t, s.tsym);
   917                 return sup != null
   918                     && sup.tsym == s.tsym
   919                     // You're not allowed to write
   920                     //     Vector<Object> vec = new Vector<String>();
   921                     // But with wildcards you can write
   922                     //     Vector<? extends Object> vec = new Vector<String>();
   923                     // which means that subtype checking must be done
   924                     // here instead of same-type checking (via containsType).
   925                     && (!s.isParameterized() || containsTypeRecursive(s, sup))
   926                     && isSubtypeNoCapture(sup.getEnclosingType(),
   927                                           s.getEnclosingType());
   928             }
   930             @Override
   931             public Boolean visitArrayType(ArrayType t, Type s) {
   932                 if (s.hasTag(ARRAY)) {
   933                     if (t.elemtype.isPrimitive())
   934                         return isSameType(t.elemtype, elemtype(s));
   935                     else
   936                         return isSubtypeNoCapture(t.elemtype, elemtype(s));
   937                 }
   939                 if (s.hasTag(CLASS)) {
   940                     Name sname = s.tsym.getQualifiedName();
   941                     return sname == names.java_lang_Object
   942                         || sname == names.java_lang_Cloneable
   943                         || sname == names.java_io_Serializable;
   944                 }
   946                 return false;
   947             }
   949             @Override
   950             public Boolean visitUndetVar(UndetVar t, Type s) {
   951                 //todo: test against origin needed? or replace with substitution?
   952                 if (t == s || t.qtype == s || s.hasTag(ERROR) || s.hasTag(UNKNOWN)) {
   953                     return true;
   954                 } else if (s.hasTag(BOT)) {
   955                     //if 's' is 'null' there's no instantiated type U for which
   956                     //U <: s (but 'null' itself, which is not a valid type)
   957                     return false;
   958                 }
   960                 t.addBound(InferenceBound.UPPER, s, Types.this);
   961                 return true;
   962             }
   964             @Override
   965             public Boolean visitErrorType(ErrorType t, Type s) {
   966                 return true;
   967             }
   968         };
   970     /**
   971      * Is t a subtype of every type in given list `ts'?<br>
   972      * (not defined for Method and ForAll types)<br>
   973      * Allows unchecked conversions.
   974      */
   975     public boolean isSubtypeUnchecked(Type t, List<Type> ts, Warner warn) {
   976         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
   977             if (!isSubtypeUnchecked(t, l.head, warn))
   978                 return false;
   979         return true;
   980     }
   982     /**
   983      * Are corresponding elements of ts subtypes of ss?  If lists are
   984      * of different length, return false.
   985      */
   986     public boolean isSubtypes(List<Type> ts, List<Type> ss) {
   987         while (ts.tail != null && ss.tail != null
   988                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   989                isSubtype(ts.head, ss.head)) {
   990             ts = ts.tail;
   991             ss = ss.tail;
   992         }
   993         return ts.tail == null && ss.tail == null;
   994         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   995     }
   997     /**
   998      * Are corresponding elements of ts subtypes of ss, allowing
   999      * unchecked conversions?  If lists are of different length,
  1000      * return false.
  1001      **/
  1002     public boolean isSubtypesUnchecked(List<Type> ts, List<Type> ss, Warner warn) {
  1003         while (ts.tail != null && ss.tail != null
  1004                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
  1005                isSubtypeUnchecked(ts.head, ss.head, warn)) {
  1006             ts = ts.tail;
  1007             ss = ss.tail;
  1009         return ts.tail == null && ss.tail == null;
  1010         /*inlined: ts.isEmpty() && ss.isEmpty();*/
  1012     // </editor-fold>
  1014     // <editor-fold defaultstate="collapsed" desc="isSuperType">
  1015     /**
  1016      * Is t a supertype of s?
  1017      */
  1018     public boolean isSuperType(Type t, Type s) {
  1019         switch (t.getTag()) {
  1020         case ERROR:
  1021             return true;
  1022         case UNDETVAR: {
  1023             UndetVar undet = (UndetVar)t;
  1024             if (t == s ||
  1025                 undet.qtype == s ||
  1026                 s.hasTag(ERROR) ||
  1027                 s.hasTag(BOT)) {
  1028                 return true;
  1030             undet.addBound(InferenceBound.LOWER, s, this);
  1031             return true;
  1033         default:
  1034             return isSubtype(s, t);
  1037     // </editor-fold>
  1039     // <editor-fold defaultstate="collapsed" desc="isSameType">
  1040     /**
  1041      * Are corresponding elements of the lists the same type?  If
  1042      * lists are of different length, return false.
  1043      */
  1044     public boolean isSameTypes(List<Type> ts, List<Type> ss) {
  1045         return isSameTypes(ts, ss, false);
  1047     public boolean isSameTypes(List<Type> ts, List<Type> ss, boolean strict) {
  1048         while (ts.tail != null && ss.tail != null
  1049                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
  1050                isSameType(ts.head, ss.head, strict)) {
  1051             ts = ts.tail;
  1052             ss = ss.tail;
  1054         return ts.tail == null && ss.tail == null;
  1055         /*inlined: ts.isEmpty() && ss.isEmpty();*/
  1058     /**
  1059     * A polymorphic signature method (JLS SE 7, 8.4.1) is a method that
  1060     * (i) is declared in the java.lang.invoke.MethodHandle class, (ii) takes
  1061     * a single variable arity parameter (iii) whose declared type is Object[],
  1062     * (iv) has a return type of Object and (v) is native.
  1063     */
  1064    public boolean isSignaturePolymorphic(MethodSymbol msym) {
  1065        List<Type> argtypes = msym.type.getParameterTypes();
  1066        return (msym.flags_field & NATIVE) != 0 &&
  1067                msym.owner == syms.methodHandleType.tsym &&
  1068                argtypes.tail.tail == null &&
  1069                argtypes.head.hasTag(TypeTag.ARRAY) &&
  1070                msym.type.getReturnType().tsym == syms.objectType.tsym &&
  1071                ((ArrayType)argtypes.head).elemtype.tsym == syms.objectType.tsym;
  1074     /**
  1075      * Is t the same type as s?
  1076      */
  1077     public boolean isSameType(Type t, Type s) {
  1078         return isSameType(t, s, false);
  1080     public boolean isSameType(Type t, Type s, boolean strict) {
  1081         return strict ?
  1082                 isSameTypeStrict.visit(t, s) :
  1083                 isSameTypeLoose.visit(t, s);
  1085     public boolean isSameAnnotatedType(Type t, Type s) {
  1086         return isSameAnnotatedType.visit(t, s);
  1088     // where
  1089         abstract class SameTypeVisitor extends TypeRelation {
  1091             public Boolean visitType(Type t, Type s) {
  1092                 if (t == s)
  1093                     return true;
  1095                 if (s.isPartial())
  1096                     return visit(s, t);
  1098                 switch (t.getTag()) {
  1099                 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
  1100                 case DOUBLE: case BOOLEAN: case VOID: case BOT: case NONE:
  1101                     return t.hasTag(s.getTag());
  1102                 case TYPEVAR: {
  1103                     if (s.hasTag(TYPEVAR)) {
  1104                         //type-substitution does not preserve type-var types
  1105                         //check that type var symbols and bounds are indeed the same
  1106                         return sameTypeVars((TypeVar)t.unannotatedType(), (TypeVar)s.unannotatedType());
  1108                     else {
  1109                         //special case for s == ? super X, where upper(s) = u
  1110                         //check that u == t, where u has been set by Type.withTypeVar
  1111                         return s.isSuperBound() &&
  1112                                 !s.isExtendsBound() &&
  1113                                 visit(t, upperBound(s));
  1116                 default:
  1117                     throw new AssertionError("isSameType " + t.getTag());
  1121             abstract boolean sameTypeVars(TypeVar tv1, TypeVar tv2);
  1123             @Override
  1124             public Boolean visitWildcardType(WildcardType t, Type s) {
  1125                 if (s.isPartial())
  1126                     return visit(s, t);
  1127                 else
  1128                     return false;
  1131             @Override
  1132             public Boolean visitClassType(ClassType t, Type s) {
  1133                 if (t == s)
  1134                     return true;
  1136                 if (s.isPartial())
  1137                     return visit(s, t);
  1139                 if (s.isSuperBound() && !s.isExtendsBound())
  1140                     return visit(t, upperBound(s)) && visit(t, lowerBound(s));
  1142                 if (t.isCompound() && s.isCompound()) {
  1143                     if (!visit(supertype(t), supertype(s)))
  1144                         return false;
  1146                     HashSet<UniqueType> set = new HashSet<UniqueType>();
  1147                     for (Type x : interfaces(t))
  1148                         set.add(new UniqueType(x.unannotatedType(), Types.this));
  1149                     for (Type x : interfaces(s)) {
  1150                         if (!set.remove(new UniqueType(x.unannotatedType(), Types.this)))
  1151                             return false;
  1153                     return (set.isEmpty());
  1155                 return t.tsym == s.tsym
  1156                     && visit(t.getEnclosingType(), s.getEnclosingType())
  1157                     && containsTypes(t.getTypeArguments(), s.getTypeArguments());
  1160             abstract protected boolean containsTypes(List<Type> ts1, List<Type> ts2);
  1162             @Override
  1163             public Boolean visitArrayType(ArrayType t, Type s) {
  1164                 if (t == s)
  1165                     return true;
  1167                 if (s.isPartial())
  1168                     return visit(s, t);
  1170                 return s.hasTag(ARRAY)
  1171                     && containsTypeEquivalent(t.elemtype, elemtype(s));
  1174             @Override
  1175             public Boolean visitMethodType(MethodType t, Type s) {
  1176                 // isSameType for methods does not take thrown
  1177                 // exceptions into account!
  1178                 return hasSameArgs(t, s) && visit(t.getReturnType(), s.getReturnType());
  1181             @Override
  1182             public Boolean visitPackageType(PackageType t, Type s) {
  1183                 return t == s;
  1186             @Override
  1187             public Boolean visitForAll(ForAll t, Type s) {
  1188                 if (!s.hasTag(FORALL)) {
  1189                     return false;
  1192                 ForAll forAll = (ForAll)s;
  1193                 return hasSameBounds(t, forAll)
  1194                     && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
  1197             @Override
  1198             public Boolean visitUndetVar(UndetVar t, Type s) {
  1199                 if (s.hasTag(WILDCARD)) {
  1200                     // FIXME, this might be leftovers from before capture conversion
  1201                     return false;
  1204                 if (t == s || t.qtype == s || s.hasTag(ERROR) || s.hasTag(UNKNOWN)) {
  1205                     return true;
  1208                 t.addBound(InferenceBound.EQ, s, Types.this);
  1210                 return true;
  1213             @Override
  1214             public Boolean visitErrorType(ErrorType t, Type s) {
  1215                 return true;
  1219         /**
  1220          * Standard type-equality relation - type variables are considered
  1221          * equals if they share the same type symbol.
  1222          */
  1223         TypeRelation isSameTypeLoose = new LooseSameTypeVisitor();
  1225         private class LooseSameTypeVisitor extends SameTypeVisitor {
  1226             @Override
  1227             boolean sameTypeVars(TypeVar tv1, TypeVar tv2) {
  1228                 return tv1.tsym == tv2.tsym && visit(tv1.getUpperBound(), tv2.getUpperBound());
  1230             @Override
  1231             protected boolean containsTypes(List<Type> ts1, List<Type> ts2) {
  1232                 return containsTypeEquivalent(ts1, ts2);
  1234         };
  1236         /**
  1237          * Strict type-equality relation - type variables are considered
  1238          * equals if they share the same object identity.
  1239          */
  1240         TypeRelation isSameTypeStrict = new SameTypeVisitor() {
  1241             @Override
  1242             boolean sameTypeVars(TypeVar tv1, TypeVar tv2) {
  1243                 return tv1 == tv2;
  1245             @Override
  1246             protected boolean containsTypes(List<Type> ts1, List<Type> ts2) {
  1247                 return isSameTypes(ts1, ts2, true);
  1250             @Override
  1251             public Boolean visitWildcardType(WildcardType t, Type s) {
  1252                 if (!s.hasTag(WILDCARD)) {
  1253                     return false;
  1254                 } else {
  1255                     WildcardType t2 = (WildcardType)s.unannotatedType();
  1256                     return t.kind == t2.kind &&
  1257                             isSameType(t.type, t2.type, true);
  1260         };
  1262         /**
  1263          * A version of LooseSameTypeVisitor that takes AnnotatedTypes
  1264          * into account.
  1265          */
  1266         TypeRelation isSameAnnotatedType = new LooseSameTypeVisitor() {
  1267             @Override
  1268             public Boolean visitAnnotatedType(AnnotatedType t, Type s) {
  1269                 if (!s.isAnnotated())
  1270                     return false;
  1271                 if (!t.getAnnotationMirrors().containsAll(s.getAnnotationMirrors()))
  1272                     return false;
  1273                 if (!s.getAnnotationMirrors().containsAll(t.getAnnotationMirrors()))
  1274                     return false;
  1275                 return visit(t.unannotatedType(), s);
  1277         };
  1278     // </editor-fold>
  1280     // <editor-fold defaultstate="collapsed" desc="Contains Type">
  1281     public boolean containedBy(Type t, Type s) {
  1282         switch (t.getTag()) {
  1283         case UNDETVAR:
  1284             if (s.hasTag(WILDCARD)) {
  1285                 UndetVar undetvar = (UndetVar)t;
  1286                 WildcardType wt = (WildcardType)s.unannotatedType();
  1287                 switch(wt.kind) {
  1288                     case UNBOUND: //similar to ? extends Object
  1289                     case EXTENDS: {
  1290                         Type bound = upperBound(s);
  1291                         undetvar.addBound(InferenceBound.UPPER, bound, this);
  1292                         break;
  1294                     case SUPER: {
  1295                         Type bound = lowerBound(s);
  1296                         undetvar.addBound(InferenceBound.LOWER, bound, this);
  1297                         break;
  1300                 return true;
  1301             } else {
  1302                 return isSameType(t, s);
  1304         case ERROR:
  1305             return true;
  1306         default:
  1307             return containsType(s, t);
  1311     boolean containsType(List<Type> ts, List<Type> ss) {
  1312         while (ts.nonEmpty() && ss.nonEmpty()
  1313                && containsType(ts.head, ss.head)) {
  1314             ts = ts.tail;
  1315             ss = ss.tail;
  1317         return ts.isEmpty() && ss.isEmpty();
  1320     /**
  1321      * Check if t contains s.
  1323      * <p>T contains S if:
  1325      * <p>{@code L(T) <: L(S) && U(S) <: U(T)}
  1327      * <p>This relation is only used by ClassType.isSubtype(), that
  1328      * is,
  1330      * <p>{@code C<S> <: C<T> if T contains S.}
  1332      * <p>Because of F-bounds, this relation can lead to infinite
  1333      * recursion.  Thus we must somehow break that recursion.  Notice
  1334      * that containsType() is only called from ClassType.isSubtype().
  1335      * Since the arguments have already been checked against their
  1336      * bounds, we know:
  1338      * <p>{@code U(S) <: U(T) if T is "super" bound (U(T) *is* the bound)}
  1340      * <p>{@code L(T) <: L(S) if T is "extends" bound (L(T) is bottom)}
  1342      * @param t a type
  1343      * @param s a type
  1344      */
  1345     public boolean containsType(Type t, Type s) {
  1346         return containsType.visit(t, s);
  1348     // where
  1349         private TypeRelation containsType = new TypeRelation() {
  1351             private Type U(Type t) {
  1352                 while (t.hasTag(WILDCARD)) {
  1353                     WildcardType w = (WildcardType)t.unannotatedType();
  1354                     if (w.isSuperBound())
  1355                         return w.bound == null ? syms.objectType : w.bound.bound;
  1356                     else
  1357                         t = w.type;
  1359                 return t;
  1362             private Type L(Type t) {
  1363                 while (t.hasTag(WILDCARD)) {
  1364                     WildcardType w = (WildcardType)t.unannotatedType();
  1365                     if (w.isExtendsBound())
  1366                         return syms.botType;
  1367                     else
  1368                         t = w.type;
  1370                 return t;
  1373             public Boolean visitType(Type t, Type s) {
  1374                 if (s.isPartial())
  1375                     return containedBy(s, t);
  1376                 else
  1377                     return isSameType(t, s);
  1380 //            void debugContainsType(WildcardType t, Type s) {
  1381 //                System.err.println();
  1382 //                System.err.format(" does %s contain %s?%n", t, s);
  1383 //                System.err.format(" %s U(%s) <: U(%s) %s = %s%n",
  1384 //                                  upperBound(s), s, t, U(t),
  1385 //                                  t.isSuperBound()
  1386 //                                  || isSubtypeNoCapture(upperBound(s), U(t)));
  1387 //                System.err.format(" %s L(%s) <: L(%s) %s = %s%n",
  1388 //                                  L(t), t, s, lowerBound(s),
  1389 //                                  t.isExtendsBound()
  1390 //                                  || isSubtypeNoCapture(L(t), lowerBound(s)));
  1391 //                System.err.println();
  1392 //            }
  1394             @Override
  1395             public Boolean visitWildcardType(WildcardType t, Type s) {
  1396                 if (s.isPartial())
  1397                     return containedBy(s, t);
  1398                 else {
  1399 //                    debugContainsType(t, s);
  1400                     return isSameWildcard(t, s)
  1401                         || isCaptureOf(s, t)
  1402                         || ((t.isExtendsBound() || isSubtypeNoCapture(L(t), lowerBound(s))) &&
  1403                             (t.isSuperBound() || isSubtypeNoCapture(upperBound(s), U(t))));
  1407             @Override
  1408             public Boolean visitUndetVar(UndetVar t, Type s) {
  1409                 if (!s.hasTag(WILDCARD)) {
  1410                     return isSameType(t, s);
  1411                 } else {
  1412                     return false;
  1416             @Override
  1417             public Boolean visitErrorType(ErrorType t, Type s) {
  1418                 return true;
  1420         };
  1422     public boolean isCaptureOf(Type s, WildcardType t) {
  1423         if (!s.hasTag(TYPEVAR) || !((TypeVar)s.unannotatedType()).isCaptured())
  1424             return false;
  1425         return isSameWildcard(t, ((CapturedType)s.unannotatedType()).wildcard);
  1428     public boolean isSameWildcard(WildcardType t, Type s) {
  1429         if (!s.hasTag(WILDCARD))
  1430             return false;
  1431         WildcardType w = (WildcardType)s.unannotatedType();
  1432         return w.kind == t.kind && w.type == t.type;
  1435     public boolean containsTypeEquivalent(List<Type> ts, List<Type> ss) {
  1436         while (ts.nonEmpty() && ss.nonEmpty()
  1437                && containsTypeEquivalent(ts.head, ss.head)) {
  1438             ts = ts.tail;
  1439             ss = ss.tail;
  1441         return ts.isEmpty() && ss.isEmpty();
  1443     // </editor-fold>
  1445     /**
  1446      * Can t and s be compared for equality?  Any primitive ==
  1447      * primitive or primitive == object comparisons here are an error.
  1448      * Unboxing and correct primitive == primitive comparisons are
  1449      * already dealt with in Attr.visitBinary.
  1451      */
  1452     public boolean isEqualityComparable(Type s, Type t, Warner warn) {
  1453         if (t.isNumeric() && s.isNumeric())
  1454             return true;
  1456         boolean tPrimitive = t.isPrimitive();
  1457         boolean sPrimitive = s.isPrimitive();
  1458         if (!tPrimitive && !sPrimitive) {
  1459             return isCastable(s, t, warn) || isCastable(t, s, warn);
  1460         } else {
  1461             return false;
  1465     // <editor-fold defaultstate="collapsed" desc="isCastable">
  1466     public boolean isCastable(Type t, Type s) {
  1467         return isCastable(t, s, noWarnings);
  1470     /**
  1471      * Is t is castable to s?<br>
  1472      * s is assumed to be an erased type.<br>
  1473      * (not defined for Method and ForAll types).
  1474      */
  1475     public boolean isCastable(Type t, Type s, Warner warn) {
  1476         if (t == s)
  1477             return true;
  1479         if (t.isPrimitive() != s.isPrimitive())
  1480             return allowBoxing && (
  1481                     isConvertible(t, s, warn)
  1482                     || (allowObjectToPrimitiveCast &&
  1483                         s.isPrimitive() &&
  1484                         isSubtype(boxedClass(s).type, t)));
  1485         if (warn != warnStack.head) {
  1486             try {
  1487                 warnStack = warnStack.prepend(warn);
  1488                 checkUnsafeVarargsConversion(t, s, warn);
  1489                 return isCastable.visit(t,s);
  1490             } finally {
  1491                 warnStack = warnStack.tail;
  1493         } else {
  1494             return isCastable.visit(t,s);
  1497     // where
  1498         private TypeRelation isCastable = new TypeRelation() {
  1500             public Boolean visitType(Type t, Type s) {
  1501                 if (s.hasTag(ERROR))
  1502                     return true;
  1504                 switch (t.getTag()) {
  1505                 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
  1506                 case DOUBLE:
  1507                     return s.isNumeric();
  1508                 case BOOLEAN:
  1509                     return s.hasTag(BOOLEAN);
  1510                 case VOID:
  1511                     return false;
  1512                 case BOT:
  1513                     return isSubtype(t, s);
  1514                 default:
  1515                     throw new AssertionError();
  1519             @Override
  1520             public Boolean visitWildcardType(WildcardType t, Type s) {
  1521                 return isCastable(upperBound(t), s, warnStack.head);
  1524             @Override
  1525             public Boolean visitClassType(ClassType t, Type s) {
  1526                 if (s.hasTag(ERROR) || s.hasTag(BOT))
  1527                     return true;
  1529                 if (s.hasTag(TYPEVAR)) {
  1530                     if (isCastable(t, s.getUpperBound(), noWarnings)) {
  1531                         warnStack.head.warn(LintCategory.UNCHECKED);
  1532                         return true;
  1533                     } else {
  1534                         return false;
  1538                 if (t.isCompound() || s.isCompound()) {
  1539                     return !t.isCompound() ?
  1540                             visitIntersectionType((IntersectionClassType)s.unannotatedType(), t, true) :
  1541                             visitIntersectionType((IntersectionClassType)t.unannotatedType(), s, false);
  1544                 if (s.hasTag(CLASS) || s.hasTag(ARRAY)) {
  1545                     boolean upcast;
  1546                     if ((upcast = isSubtype(erasure(t), erasure(s)))
  1547                         || isSubtype(erasure(s), erasure(t))) {
  1548                         if (!upcast && s.hasTag(ARRAY)) {
  1549                             if (!isReifiable(s))
  1550                                 warnStack.head.warn(LintCategory.UNCHECKED);
  1551                             return true;
  1552                         } else if (s.isRaw()) {
  1553                             return true;
  1554                         } else if (t.isRaw()) {
  1555                             if (!isUnbounded(s))
  1556                                 warnStack.head.warn(LintCategory.UNCHECKED);
  1557                             return true;
  1559                         // Assume |a| <: |b|
  1560                         final Type a = upcast ? t : s;
  1561                         final Type b = upcast ? s : t;
  1562                         final boolean HIGH = true;
  1563                         final boolean LOW = false;
  1564                         final boolean DONT_REWRITE_TYPEVARS = false;
  1565                         Type aHigh = rewriteQuantifiers(a, HIGH, DONT_REWRITE_TYPEVARS);
  1566                         Type aLow  = rewriteQuantifiers(a, LOW,  DONT_REWRITE_TYPEVARS);
  1567                         Type bHigh = rewriteQuantifiers(b, HIGH, DONT_REWRITE_TYPEVARS);
  1568                         Type bLow  = rewriteQuantifiers(b, LOW,  DONT_REWRITE_TYPEVARS);
  1569                         Type lowSub = asSub(bLow, aLow.tsym);
  1570                         Type highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
  1571                         if (highSub == null) {
  1572                             final boolean REWRITE_TYPEVARS = true;
  1573                             aHigh = rewriteQuantifiers(a, HIGH, REWRITE_TYPEVARS);
  1574                             aLow  = rewriteQuantifiers(a, LOW,  REWRITE_TYPEVARS);
  1575                             bHigh = rewriteQuantifiers(b, HIGH, REWRITE_TYPEVARS);
  1576                             bLow  = rewriteQuantifiers(b, LOW,  REWRITE_TYPEVARS);
  1577                             lowSub = asSub(bLow, aLow.tsym);
  1578                             highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
  1580                         if (highSub != null) {
  1581                             if (!(a.tsym == highSub.tsym && a.tsym == lowSub.tsym)) {
  1582                                 Assert.error(a.tsym + " != " + highSub.tsym + " != " + lowSub.tsym);
  1584                             if (!disjointTypes(aHigh.allparams(), highSub.allparams())
  1585                                 && !disjointTypes(aHigh.allparams(), lowSub.allparams())
  1586                                 && !disjointTypes(aLow.allparams(), highSub.allparams())
  1587                                 && !disjointTypes(aLow.allparams(), lowSub.allparams())) {
  1588                                 if (upcast ? giveWarning(a, b) :
  1589                                     giveWarning(b, a))
  1590                                     warnStack.head.warn(LintCategory.UNCHECKED);
  1591                                 return true;
  1594                         if (isReifiable(s))
  1595                             return isSubtypeUnchecked(a, b);
  1596                         else
  1597                             return isSubtypeUnchecked(a, b, warnStack.head);
  1600                     // Sidecast
  1601                     if (s.hasTag(CLASS)) {
  1602                         if ((s.tsym.flags() & INTERFACE) != 0) {
  1603                             return ((t.tsym.flags() & FINAL) == 0)
  1604                                 ? sideCast(t, s, warnStack.head)
  1605                                 : sideCastFinal(t, s, warnStack.head);
  1606                         } else if ((t.tsym.flags() & INTERFACE) != 0) {
  1607                             return ((s.tsym.flags() & FINAL) == 0)
  1608                                 ? sideCast(t, s, warnStack.head)
  1609                                 : sideCastFinal(t, s, warnStack.head);
  1610                         } else {
  1611                             // unrelated class types
  1612                             return false;
  1616                 return false;
  1619             boolean visitIntersectionType(IntersectionClassType ict, Type s, boolean reverse) {
  1620                 Warner warn = noWarnings;
  1621                 for (Type c : ict.getComponents()) {
  1622                     warn.clear();
  1623                     if (reverse ? !isCastable(s, c, warn) : !isCastable(c, s, warn))
  1624                         return false;
  1626                 if (warn.hasLint(LintCategory.UNCHECKED))
  1627                     warnStack.head.warn(LintCategory.UNCHECKED);
  1628                 return true;
  1631             @Override
  1632             public Boolean visitArrayType(ArrayType t, Type s) {
  1633                 switch (s.getTag()) {
  1634                 case ERROR:
  1635                 case BOT:
  1636                     return true;
  1637                 case TYPEVAR:
  1638                     if (isCastable(s, t, noWarnings)) {
  1639                         warnStack.head.warn(LintCategory.UNCHECKED);
  1640                         return true;
  1641                     } else {
  1642                         return false;
  1644                 case CLASS:
  1645                     return isSubtype(t, s);
  1646                 case ARRAY:
  1647                     if (elemtype(t).isPrimitive() || elemtype(s).isPrimitive()) {
  1648                         return elemtype(t).hasTag(elemtype(s).getTag());
  1649                     } else {
  1650                         return visit(elemtype(t), elemtype(s));
  1652                 default:
  1653                     return false;
  1657             @Override
  1658             public Boolean visitTypeVar(TypeVar t, Type s) {
  1659                 switch (s.getTag()) {
  1660                 case ERROR:
  1661                 case BOT:
  1662                     return true;
  1663                 case TYPEVAR:
  1664                     if (isSubtype(t, s)) {
  1665                         return true;
  1666                     } else if (isCastable(t.bound, s, noWarnings)) {
  1667                         warnStack.head.warn(LintCategory.UNCHECKED);
  1668                         return true;
  1669                     } else {
  1670                         return false;
  1672                 default:
  1673                     return isCastable(t.bound, s, warnStack.head);
  1677             @Override
  1678             public Boolean visitErrorType(ErrorType t, Type s) {
  1679                 return true;
  1681         };
  1682     // </editor-fold>
  1684     // <editor-fold defaultstate="collapsed" desc="disjointTypes">
  1685     public boolean disjointTypes(List<Type> ts, List<Type> ss) {
  1686         while (ts.tail != null && ss.tail != null) {
  1687             if (disjointType(ts.head, ss.head)) return true;
  1688             ts = ts.tail;
  1689             ss = ss.tail;
  1691         return false;
  1694     /**
  1695      * Two types or wildcards are considered disjoint if it can be
  1696      * proven that no type can be contained in both. It is
  1697      * conservative in that it is allowed to say that two types are
  1698      * not disjoint, even though they actually are.
  1700      * The type {@code C<X>} is castable to {@code C<Y>} exactly if
  1701      * {@code X} and {@code Y} are not disjoint.
  1702      */
  1703     public boolean disjointType(Type t, Type s) {
  1704         return disjointType.visit(t, s);
  1706     // where
  1707         private TypeRelation disjointType = new TypeRelation() {
  1709             private Set<TypePair> cache = new HashSet<TypePair>();
  1711             @Override
  1712             public Boolean visitType(Type t, Type s) {
  1713                 if (s.hasTag(WILDCARD))
  1714                     return visit(s, t);
  1715                 else
  1716                     return notSoftSubtypeRecursive(t, s) || notSoftSubtypeRecursive(s, t);
  1719             private boolean isCastableRecursive(Type t, Type s) {
  1720                 TypePair pair = new TypePair(t, s);
  1721                 if (cache.add(pair)) {
  1722                     try {
  1723                         return Types.this.isCastable(t, s);
  1724                     } finally {
  1725                         cache.remove(pair);
  1727                 } else {
  1728                     return true;
  1732             private boolean notSoftSubtypeRecursive(Type t, Type s) {
  1733                 TypePair pair = new TypePair(t, s);
  1734                 if (cache.add(pair)) {
  1735                     try {
  1736                         return Types.this.notSoftSubtype(t, s);
  1737                     } finally {
  1738                         cache.remove(pair);
  1740                 } else {
  1741                     return false;
  1745             @Override
  1746             public Boolean visitWildcardType(WildcardType t, Type s) {
  1747                 if (t.isUnbound())
  1748                     return false;
  1750                 if (!s.hasTag(WILDCARD)) {
  1751                     if (t.isExtendsBound())
  1752                         return notSoftSubtypeRecursive(s, t.type);
  1753                     else
  1754                         return notSoftSubtypeRecursive(t.type, s);
  1757                 if (s.isUnbound())
  1758                     return false;
  1760                 if (t.isExtendsBound()) {
  1761                     if (s.isExtendsBound())
  1762                         return !isCastableRecursive(t.type, upperBound(s));
  1763                     else if (s.isSuperBound())
  1764                         return notSoftSubtypeRecursive(lowerBound(s), t.type);
  1765                 } else if (t.isSuperBound()) {
  1766                     if (s.isExtendsBound())
  1767                         return notSoftSubtypeRecursive(t.type, upperBound(s));
  1769                 return false;
  1771         };
  1772     // </editor-fold>
  1774     // <editor-fold defaultstate="collapsed" desc="lowerBoundArgtypes">
  1775     /**
  1776      * Returns the lower bounds of the formals of a method.
  1777      */
  1778     public List<Type> lowerBoundArgtypes(Type t) {
  1779         return lowerBounds(t.getParameterTypes());
  1781     public List<Type> lowerBounds(List<Type> ts) {
  1782         return map(ts, lowerBoundMapping);
  1784     private final Mapping lowerBoundMapping = new Mapping("lowerBound") {
  1785             public Type apply(Type t) {
  1786                 return lowerBound(t);
  1788         };
  1789     // </editor-fold>
  1791     // <editor-fold defaultstate="collapsed" desc="notSoftSubtype">
  1792     /**
  1793      * This relation answers the question: is impossible that
  1794      * something of type `t' can be a subtype of `s'? This is
  1795      * different from the question "is `t' not a subtype of `s'?"
  1796      * when type variables are involved: Integer is not a subtype of T
  1797      * where {@code <T extends Number>} but it is not true that Integer cannot
  1798      * possibly be a subtype of T.
  1799      */
  1800     public boolean notSoftSubtype(Type t, Type s) {
  1801         if (t == s) return false;
  1802         if (t.hasTag(TYPEVAR)) {
  1803             TypeVar tv = (TypeVar) t;
  1804             return !isCastable(tv.bound,
  1805                                relaxBound(s),
  1806                                noWarnings);
  1808         if (!s.hasTag(WILDCARD))
  1809             s = upperBound(s);
  1811         return !isSubtype(t, relaxBound(s));
  1814     private Type relaxBound(Type t) {
  1815         if (t.hasTag(TYPEVAR)) {
  1816             while (t.hasTag(TYPEVAR))
  1817                 t = t.getUpperBound();
  1818             t = rewriteQuantifiers(t, true, true);
  1820         return t;
  1822     // </editor-fold>
  1824     // <editor-fold defaultstate="collapsed" desc="isReifiable">
  1825     public boolean isReifiable(Type t) {
  1826         return isReifiable.visit(t);
  1828     // where
  1829         private UnaryVisitor<Boolean> isReifiable = new UnaryVisitor<Boolean>() {
  1831             public Boolean visitType(Type t, Void ignored) {
  1832                 return true;
  1835             @Override
  1836             public Boolean visitClassType(ClassType t, Void ignored) {
  1837                 if (t.isCompound())
  1838                     return false;
  1839                 else {
  1840                     if (!t.isParameterized())
  1841                         return true;
  1843                     for (Type param : t.allparams()) {
  1844                         if (!param.isUnbound())
  1845                             return false;
  1847                     return true;
  1851             @Override
  1852             public Boolean visitArrayType(ArrayType t, Void ignored) {
  1853                 return visit(t.elemtype);
  1856             @Override
  1857             public Boolean visitTypeVar(TypeVar t, Void ignored) {
  1858                 return false;
  1860         };
  1861     // </editor-fold>
  1863     // <editor-fold defaultstate="collapsed" desc="Array Utils">
  1864     public boolean isArray(Type t) {
  1865         while (t.hasTag(WILDCARD))
  1866             t = upperBound(t);
  1867         return t.hasTag(ARRAY);
  1870     /**
  1871      * The element type of an array.
  1872      */
  1873     public Type elemtype(Type t) {
  1874         switch (t.getTag()) {
  1875         case WILDCARD:
  1876             return elemtype(upperBound(t));
  1877         case ARRAY:
  1878             t = t.unannotatedType();
  1879             return ((ArrayType)t).elemtype;
  1880         case FORALL:
  1881             return elemtype(((ForAll)t).qtype);
  1882         case ERROR:
  1883             return t;
  1884         default:
  1885             return null;
  1889     public Type elemtypeOrType(Type t) {
  1890         Type elemtype = elemtype(t);
  1891         return elemtype != null ?
  1892             elemtype :
  1893             t;
  1896     /**
  1897      * Mapping to take element type of an arraytype
  1898      */
  1899     private Mapping elemTypeFun = new Mapping ("elemTypeFun") {
  1900         public Type apply(Type t) { return elemtype(t); }
  1901     };
  1903     /**
  1904      * The number of dimensions of an array type.
  1905      */
  1906     public int dimensions(Type t) {
  1907         int result = 0;
  1908         while (t.hasTag(ARRAY)) {
  1909             result++;
  1910             t = elemtype(t);
  1912         return result;
  1915     /**
  1916      * Returns an ArrayType with the component type t
  1918      * @param t The component type of the ArrayType
  1919      * @return the ArrayType for the given component
  1920      */
  1921     public ArrayType makeArrayType(Type t) {
  1922         if (t.hasTag(VOID) || t.hasTag(PACKAGE)) {
  1923             Assert.error("Type t must not be a VOID or PACKAGE type, " + t.toString());
  1925         return new ArrayType(t, syms.arrayClass);
  1927     // </editor-fold>
  1929     // <editor-fold defaultstate="collapsed" desc="asSuper">
  1930     /**
  1931      * Return the (most specific) base type of t that starts with the
  1932      * given symbol.  If none exists, return null.
  1934      * @param t a type
  1935      * @param sym a symbol
  1936      */
  1937     public Type asSuper(Type t, Symbol sym) {
  1938         /* Some examples:
  1940          * (Enum<E>, Comparable) => Comparable<E>
  1941          * (c.s.s.d.AttributeTree.ValueKind, Enum) => Enum<c.s.s.d.AttributeTree.ValueKind>
  1942          * (c.s.s.t.ExpressionTree, c.s.s.t.Tree) => c.s.s.t.Tree
  1943          * (j.u.List<capture#160 of ? extends c.s.s.d.DocTree>, Iterable) =>
  1944          *     Iterable<capture#160 of ? extends c.s.s.d.DocTree>
  1945          */
  1946         if (sym.type == syms.objectType) { //optimization
  1947             return syms.objectType;
  1949         return asSuper.visit(t, sym);
  1951     // where
  1952         private SimpleVisitor<Type,Symbol> asSuper = new SimpleVisitor<Type,Symbol>() {
  1954             public Type visitType(Type t, Symbol sym) {
  1955                 return null;
  1958             @Override
  1959             public Type visitClassType(ClassType t, Symbol sym) {
  1960                 if (t.tsym == sym)
  1961                     return t;
  1963                 Type st = supertype(t);
  1964                 if (st.hasTag(CLASS) || st.hasTag(TYPEVAR) || st.hasTag(ERROR)) {
  1965                     Type x = asSuper(st, sym);
  1966                     if (x != null)
  1967                         return x;
  1969                 if ((sym.flags() & INTERFACE) != 0) {
  1970                     for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
  1971                         Type x = asSuper(l.head, sym);
  1972                         if (x != null)
  1973                             return x;
  1976                 return null;
  1979             @Override
  1980             public Type visitArrayType(ArrayType t, Symbol sym) {
  1981                 return isSubtype(t, sym.type) ? sym.type : null;
  1984             @Override
  1985             public Type visitTypeVar(TypeVar t, Symbol sym) {
  1986                 if (t.tsym == sym)
  1987                     return t;
  1988                 else
  1989                     return asSuper(t.bound, sym);
  1992             @Override
  1993             public Type visitErrorType(ErrorType t, Symbol sym) {
  1994                 return t;
  1996         };
  1998     /**
  1999      * Return the base type of t or any of its outer types that starts
  2000      * with the given symbol.  If none exists, return null.
  2002      * @param t a type
  2003      * @param sym a symbol
  2004      */
  2005     public Type asOuterSuper(Type t, Symbol sym) {
  2006         switch (t.getTag()) {
  2007         case CLASS:
  2008             do {
  2009                 Type s = asSuper(t, sym);
  2010                 if (s != null) return s;
  2011                 t = t.getEnclosingType();
  2012             } while (t.hasTag(CLASS));
  2013             return null;
  2014         case ARRAY:
  2015             return isSubtype(t, sym.type) ? sym.type : null;
  2016         case TYPEVAR:
  2017             return asSuper(t, sym);
  2018         case ERROR:
  2019             return t;
  2020         default:
  2021             return null;
  2025     /**
  2026      * Return the base type of t or any of its enclosing types that
  2027      * starts with the given symbol.  If none exists, return null.
  2029      * @param t a type
  2030      * @param sym a symbol
  2031      */
  2032     public Type asEnclosingSuper(Type t, Symbol sym) {
  2033         switch (t.getTag()) {
  2034         case CLASS:
  2035             do {
  2036                 Type s = asSuper(t, sym);
  2037                 if (s != null) return s;
  2038                 Type outer = t.getEnclosingType();
  2039                 t = (outer.hasTag(CLASS)) ? outer :
  2040                     (t.tsym.owner.enclClass() != null) ? t.tsym.owner.enclClass().type :
  2041                     Type.noType;
  2042             } while (t.hasTag(CLASS));
  2043             return null;
  2044         case ARRAY:
  2045             return isSubtype(t, sym.type) ? sym.type : null;
  2046         case TYPEVAR:
  2047             return asSuper(t, sym);
  2048         case ERROR:
  2049             return t;
  2050         default:
  2051             return null;
  2054     // </editor-fold>
  2056     // <editor-fold defaultstate="collapsed" desc="memberType">
  2057     /**
  2058      * The type of given symbol, seen as a member of t.
  2060      * @param t a type
  2061      * @param sym a symbol
  2062      */
  2063     public Type memberType(Type t, Symbol sym) {
  2064         return (sym.flags() & STATIC) != 0
  2065             ? sym.type
  2066             : memberType.visit(t, sym);
  2068     // where
  2069         private SimpleVisitor<Type,Symbol> memberType = new SimpleVisitor<Type,Symbol>() {
  2071             public Type visitType(Type t, Symbol sym) {
  2072                 return sym.type;
  2075             @Override
  2076             public Type visitWildcardType(WildcardType t, Symbol sym) {
  2077                 return memberType(upperBound(t), sym);
  2080             @Override
  2081             public Type visitClassType(ClassType t, Symbol sym) {
  2082                 Symbol owner = sym.owner;
  2083                 long flags = sym.flags();
  2084                 if (((flags & STATIC) == 0) && owner.type.isParameterized()) {
  2085                     Type base = asOuterSuper(t, owner);
  2086                     //if t is an intersection type T = CT & I1 & I2 ... & In
  2087                     //its supertypes CT, I1, ... In might contain wildcards
  2088                     //so we need to go through capture conversion
  2089                     base = t.isCompound() ? capture(base) : base;
  2090                     if (base != null) {
  2091                         List<Type> ownerParams = owner.type.allparams();
  2092                         List<Type> baseParams = base.allparams();
  2093                         if (ownerParams.nonEmpty()) {
  2094                             if (baseParams.isEmpty()) {
  2095                                 // then base is a raw type
  2096                                 return erasure(sym.type);
  2097                             } else {
  2098                                 return subst(sym.type, ownerParams, baseParams);
  2103                 return sym.type;
  2106             @Override
  2107             public Type visitTypeVar(TypeVar t, Symbol sym) {
  2108                 return memberType(t.bound, sym);
  2111             @Override
  2112             public Type visitErrorType(ErrorType t, Symbol sym) {
  2113                 return t;
  2115         };
  2116     // </editor-fold>
  2118     // <editor-fold defaultstate="collapsed" desc="isAssignable">
  2119     public boolean isAssignable(Type t, Type s) {
  2120         return isAssignable(t, s, noWarnings);
  2123     /**
  2124      * Is t assignable to s?<br>
  2125      * Equivalent to subtype except for constant values and raw
  2126      * types.<br>
  2127      * (not defined for Method and ForAll types)
  2128      */
  2129     public boolean isAssignable(Type t, Type s, Warner warn) {
  2130         if (t.hasTag(ERROR))
  2131             return true;
  2132         if (t.getTag().isSubRangeOf(INT) && t.constValue() != null) {
  2133             int value = ((Number)t.constValue()).intValue();
  2134             switch (s.getTag()) {
  2135             case BYTE:
  2136                 if (Byte.MIN_VALUE <= value && value <= Byte.MAX_VALUE)
  2137                     return true;
  2138                 break;
  2139             case CHAR:
  2140                 if (Character.MIN_VALUE <= value && value <= Character.MAX_VALUE)
  2141                     return true;
  2142                 break;
  2143             case SHORT:
  2144                 if (Short.MIN_VALUE <= value && value <= Short.MAX_VALUE)
  2145                     return true;
  2146                 break;
  2147             case INT:
  2148                 return true;
  2149             case CLASS:
  2150                 switch (unboxedType(s).getTag()) {
  2151                 case BYTE:
  2152                 case CHAR:
  2153                 case SHORT:
  2154                     return isAssignable(t, unboxedType(s), warn);
  2156                 break;
  2159         return isConvertible(t, s, warn);
  2161     // </editor-fold>
  2163     // <editor-fold defaultstate="collapsed" desc="erasure">
  2164     /**
  2165      * The erasure of t {@code |t|} -- the type that results when all
  2166      * type parameters in t are deleted.
  2167      */
  2168     public Type erasure(Type t) {
  2169         return eraseNotNeeded(t)? t : erasure(t, false);
  2171     //where
  2172     private boolean eraseNotNeeded(Type t) {
  2173         // We don't want to erase primitive types and String type as that
  2174         // operation is idempotent. Also, erasing these could result in loss
  2175         // of information such as constant values attached to such types.
  2176         return (t.isPrimitive()) || (syms.stringType.tsym == t.tsym);
  2179     private Type erasure(Type t, boolean recurse) {
  2180         if (t.isPrimitive())
  2181             return t; /* fast special case */
  2182         else
  2183             return erasure.visit(t, recurse);
  2185     // where
  2186         private SimpleVisitor<Type, Boolean> erasure = new SimpleVisitor<Type, Boolean>() {
  2187             public Type visitType(Type t, Boolean recurse) {
  2188                 if (t.isPrimitive())
  2189                     return t; /*fast special case*/
  2190                 else
  2191                     return t.map(recurse ? erasureRecFun : erasureFun);
  2194             @Override
  2195             public Type visitWildcardType(WildcardType t, Boolean recurse) {
  2196                 return erasure(upperBound(t), recurse);
  2199             @Override
  2200             public Type visitClassType(ClassType t, Boolean recurse) {
  2201                 Type erased = t.tsym.erasure(Types.this);
  2202                 if (recurse) {
  2203                     erased = new ErasedClassType(erased.getEnclosingType(),erased.tsym);
  2205                 return erased;
  2208             @Override
  2209             public Type visitTypeVar(TypeVar t, Boolean recurse) {
  2210                 return erasure(t.bound, recurse);
  2213             @Override
  2214             public Type visitErrorType(ErrorType t, Boolean recurse) {
  2215                 return t;
  2218             @Override
  2219             public Type visitAnnotatedType(AnnotatedType t, Boolean recurse) {
  2220                 Type erased = erasure(t.unannotatedType(), recurse);
  2221                 if (erased.isAnnotated()) {
  2222                     // This can only happen when the underlying type is a
  2223                     // type variable and the upper bound of it is annotated.
  2224                     // The annotation on the type variable overrides the one
  2225                     // on the bound.
  2226                     erased = ((AnnotatedType)erased).unannotatedType();
  2228                 return erased.annotatedType(t.getAnnotationMirrors());
  2230         };
  2232     private Mapping erasureFun = new Mapping ("erasure") {
  2233             public Type apply(Type t) { return erasure(t); }
  2234         };
  2236     private Mapping erasureRecFun = new Mapping ("erasureRecursive") {
  2237         public Type apply(Type t) { return erasureRecursive(t); }
  2238     };
  2240     public List<Type> erasure(List<Type> ts) {
  2241         return Type.map(ts, erasureFun);
  2244     public Type erasureRecursive(Type t) {
  2245         return erasure(t, true);
  2248     public List<Type> erasureRecursive(List<Type> ts) {
  2249         return Type.map(ts, erasureRecFun);
  2251     // </editor-fold>
  2253     // <editor-fold defaultstate="collapsed" desc="makeCompoundType">
  2254     /**
  2255      * Make a compound type from non-empty list of 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() || t.tsym.precedes(cl.head.tsym, this)) {
  3346             return cl.prepend(t);
  3347         } else if (cl.head.tsym.precedes(t.tsym, this)) {
  3348             return insert(cl.tail, t).prepend(cl.head);
  3349         } else {
  3350             return cl;
  3354     /**
  3355      * Form the union of two closures
  3356      */
  3357     public List<Type> union(List<Type> cl1, List<Type> cl2) {
  3358         if (cl1.isEmpty()) {
  3359             return cl2;
  3360         } else if (cl2.isEmpty()) {
  3361             return cl1;
  3362         } else if (cl1.head.tsym.precedes(cl2.head.tsym, this)) {
  3363             return union(cl1.tail, cl2).prepend(cl1.head);
  3364         } else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) {
  3365             return union(cl1, cl2.tail).prepend(cl2.head);
  3366         } else {
  3367             return union(cl1.tail, cl2.tail).prepend(cl1.head);
  3371     /**
  3372      * Intersect two closures
  3373      */
  3374     public List<Type> intersect(List<Type> cl1, List<Type> cl2) {
  3375         if (cl1 == cl2)
  3376             return cl1;
  3377         if (cl1.isEmpty() || cl2.isEmpty())
  3378             return List.nil();
  3379         if (cl1.head.tsym.precedes(cl2.head.tsym, this))
  3380             return intersect(cl1.tail, cl2);
  3381         if (cl2.head.tsym.precedes(cl1.head.tsym, this))
  3382             return intersect(cl1, cl2.tail);
  3383         if (isSameType(cl1.head, cl2.head))
  3384             return intersect(cl1.tail, cl2.tail).prepend(cl1.head);
  3385         if (cl1.head.tsym == cl2.head.tsym &&
  3386             cl1.head.hasTag(CLASS) && cl2.head.hasTag(CLASS)) {
  3387             if (cl1.head.isParameterized() && cl2.head.isParameterized()) {
  3388                 Type merge = merge(cl1.head,cl2.head);
  3389                 return intersect(cl1.tail, cl2.tail).prepend(merge);
  3391             if (cl1.head.isRaw() || cl2.head.isRaw())
  3392                 return intersect(cl1.tail, cl2.tail).prepend(erasure(cl1.head));
  3394         return intersect(cl1.tail, cl2.tail);
  3396     // where
  3397         class TypePair {
  3398             final Type t1;
  3399             final Type t2;
  3400             TypePair(Type t1, Type t2) {
  3401                 this.t1 = t1;
  3402                 this.t2 = t2;
  3404             @Override
  3405             public int hashCode() {
  3406                 return 127 * Types.this.hashCode(t1) + Types.this.hashCode(t2);
  3408             @Override
  3409             public boolean equals(Object obj) {
  3410                 if (!(obj instanceof TypePair))
  3411                     return false;
  3412                 TypePair typePair = (TypePair)obj;
  3413                 return isSameType(t1, typePair.t1)
  3414                     && isSameType(t2, typePair.t2);
  3417         Set<TypePair> mergeCache = new HashSet<TypePair>();
  3418         private Type merge(Type c1, Type c2) {
  3419             ClassType class1 = (ClassType) c1;
  3420             List<Type> act1 = class1.getTypeArguments();
  3421             ClassType class2 = (ClassType) c2;
  3422             List<Type> act2 = class2.getTypeArguments();
  3423             ListBuffer<Type> merged = new ListBuffer<Type>();
  3424             List<Type> typarams = class1.tsym.type.getTypeArguments();
  3426             while (act1.nonEmpty() && act2.nonEmpty() && typarams.nonEmpty()) {
  3427                 if (containsType(act1.head, act2.head)) {
  3428                     merged.append(act1.head);
  3429                 } else if (containsType(act2.head, act1.head)) {
  3430                     merged.append(act2.head);
  3431                 } else {
  3432                     TypePair pair = new TypePair(c1, c2);
  3433                     Type m;
  3434                     if (mergeCache.add(pair)) {
  3435                         m = new WildcardType(lub(upperBound(act1.head),
  3436                                                  upperBound(act2.head)),
  3437                                              BoundKind.EXTENDS,
  3438                                              syms.boundClass);
  3439                         mergeCache.remove(pair);
  3440                     } else {
  3441                         m = new WildcardType(syms.objectType,
  3442                                              BoundKind.UNBOUND,
  3443                                              syms.boundClass);
  3445                     merged.append(m.withTypeVar(typarams.head));
  3447                 act1 = act1.tail;
  3448                 act2 = act2.tail;
  3449                 typarams = typarams.tail;
  3451             Assert.check(act1.isEmpty() && act2.isEmpty() && typarams.isEmpty());
  3452             return new ClassType(class1.getEnclosingType(), merged.toList(), class1.tsym);
  3455     /**
  3456      * Return the minimum type of a closure, a compound type if no
  3457      * unique minimum exists.
  3458      */
  3459     private Type compoundMin(List<Type> cl) {
  3460         if (cl.isEmpty()) return syms.objectType;
  3461         List<Type> compound = closureMin(cl);
  3462         if (compound.isEmpty())
  3463             return null;
  3464         else if (compound.tail.isEmpty())
  3465             return compound.head;
  3466         else
  3467             return makeCompoundType(compound);
  3470     /**
  3471      * Return the minimum types of a closure, suitable for computing
  3472      * compoundMin or glb.
  3473      */
  3474     private List<Type> closureMin(List<Type> cl) {
  3475         ListBuffer<Type> classes = new ListBuffer<>();
  3476         ListBuffer<Type> interfaces = new ListBuffer<>();
  3477         while (!cl.isEmpty()) {
  3478             Type current = cl.head;
  3479             if (current.isInterface())
  3480                 interfaces.append(current);
  3481             else
  3482                 classes.append(current);
  3483             ListBuffer<Type> candidates = new ListBuffer<>();
  3484             for (Type t : cl.tail) {
  3485                 if (!isSubtypeNoCapture(current, t))
  3486                     candidates.append(t);
  3488             cl = candidates.toList();
  3490         return classes.appendList(interfaces).toList();
  3493     /**
  3494      * Return the least upper bound of pair of types.  if the lub does
  3495      * not exist return null.
  3496      */
  3497     public Type lub(Type t1, Type t2) {
  3498         return lub(List.of(t1, t2));
  3501     /**
  3502      * Return the least upper bound (lub) of set of types.  If the lub
  3503      * does not exist return the type of null (bottom).
  3504      */
  3505     public Type lub(List<Type> ts) {
  3506         final int ARRAY_BOUND = 1;
  3507         final int CLASS_BOUND = 2;
  3508         int boundkind = 0;
  3509         for (Type t : ts) {
  3510             switch (t.getTag()) {
  3511             case CLASS:
  3512                 boundkind |= CLASS_BOUND;
  3513                 break;
  3514             case ARRAY:
  3515                 boundkind |= ARRAY_BOUND;
  3516                 break;
  3517             case  TYPEVAR:
  3518                 do {
  3519                     t = t.getUpperBound();
  3520                 } while (t.hasTag(TYPEVAR));
  3521                 if (t.hasTag(ARRAY)) {
  3522                     boundkind |= ARRAY_BOUND;
  3523                 } else {
  3524                     boundkind |= CLASS_BOUND;
  3526                 break;
  3527             default:
  3528                 if (t.isPrimitive())
  3529                     return syms.errType;
  3532         switch (boundkind) {
  3533         case 0:
  3534             return syms.botType;
  3536         case ARRAY_BOUND:
  3537             // calculate lub(A[], B[])
  3538             List<Type> elements = Type.map(ts, elemTypeFun);
  3539             for (Type t : elements) {
  3540                 if (t.isPrimitive()) {
  3541                     // if a primitive type is found, then return
  3542                     // arraySuperType unless all the types are the
  3543                     // same
  3544                     Type first = ts.head;
  3545                     for (Type s : ts.tail) {
  3546                         if (!isSameType(first, s)) {
  3547                              // lub(int[], B[]) is Cloneable & Serializable
  3548                             return arraySuperType();
  3551                     // all the array types are the same, return one
  3552                     // lub(int[], int[]) is int[]
  3553                     return first;
  3556             // lub(A[], B[]) is lub(A, B)[]
  3557             return new ArrayType(lub(elements), syms.arrayClass);
  3559         case CLASS_BOUND:
  3560             // calculate lub(A, B)
  3561             while (!ts.head.hasTag(CLASS) && !ts.head.hasTag(TYPEVAR)) {
  3562                 ts = ts.tail;
  3564             Assert.check(!ts.isEmpty());
  3565             //step 1 - compute erased candidate set (EC)
  3566             List<Type> cl = erasedSupertypes(ts.head);
  3567             for (Type t : ts.tail) {
  3568                 if (t.hasTag(CLASS) || t.hasTag(TYPEVAR))
  3569                     cl = intersect(cl, erasedSupertypes(t));
  3571             //step 2 - compute minimal erased candidate set (MEC)
  3572             List<Type> mec = closureMin(cl);
  3573             //step 3 - for each element G in MEC, compute lci(Inv(G))
  3574             List<Type> candidates = List.nil();
  3575             for (Type erasedSupertype : mec) {
  3576                 List<Type> lci = List.of(asSuper(ts.head, erasedSupertype.tsym));
  3577                 for (Type t : ts) {
  3578                     lci = intersect(lci, List.of(asSuper(t, erasedSupertype.tsym)));
  3580                 candidates = candidates.appendList(lci);
  3582             //step 4 - let MEC be { G1, G2 ... Gn }, then we have that
  3583             //lub = lci(Inv(G1)) & lci(Inv(G2)) & ... & lci(Inv(Gn))
  3584             return compoundMin(candidates);
  3586         default:
  3587             // calculate lub(A, B[])
  3588             List<Type> classes = List.of(arraySuperType());
  3589             for (Type t : ts) {
  3590                 if (!t.hasTag(ARRAY)) // Filter out any arrays
  3591                     classes = classes.prepend(t);
  3593             // lub(A, B[]) is lub(A, arraySuperType)
  3594             return lub(classes);
  3597     // where
  3598         List<Type> erasedSupertypes(Type t) {
  3599             ListBuffer<Type> buf = new ListBuffer<>();
  3600             for (Type sup : closure(t)) {
  3601                 if (sup.hasTag(TYPEVAR)) {
  3602                     buf.append(sup);
  3603                 } else {
  3604                     buf.append(erasure(sup));
  3607             return buf.toList();
  3610         private Type arraySuperType = null;
  3611         private Type arraySuperType() {
  3612             // initialized lazily to avoid problems during compiler startup
  3613             if (arraySuperType == null) {
  3614                 synchronized (this) {
  3615                     if (arraySuperType == null) {
  3616                         // JLS 10.8: all arrays implement Cloneable and Serializable.
  3617                         arraySuperType = makeCompoundType(List.of(syms.serializableType,
  3618                                                                   syms.cloneableType), true);
  3622             return arraySuperType;
  3624     // </editor-fold>
  3626     // <editor-fold defaultstate="collapsed" desc="Greatest lower bound">
  3627     public Type glb(List<Type> ts) {
  3628         Type t1 = ts.head;
  3629         for (Type t2 : ts.tail) {
  3630             if (t1.isErroneous())
  3631                 return t1;
  3632             t1 = glb(t1, t2);
  3634         return t1;
  3636     //where
  3637     public Type glb(Type t, Type s) {
  3638         if (s == null)
  3639             return t;
  3640         else if (t.isPrimitive() || s.isPrimitive())
  3641             return syms.errType;
  3642         else if (isSubtypeNoCapture(t, s))
  3643             return t;
  3644         else if (isSubtypeNoCapture(s, t))
  3645             return s;
  3647         List<Type> closure = union(closure(t), closure(s));
  3648         List<Type> bounds = closureMin(closure);
  3650         if (bounds.isEmpty()) {             // length == 0
  3651             return syms.objectType;
  3652         } else if (bounds.tail.isEmpty()) { // length == 1
  3653             return bounds.head;
  3654         } else {                            // length > 1
  3655             int classCount = 0;
  3656             for (Type bound : bounds)
  3657                 if (!bound.isInterface())
  3658                     classCount++;
  3659             if (classCount > 1)
  3660                 return createErrorType(t);
  3662         return makeCompoundType(bounds);
  3664     // </editor-fold>
  3666     // <editor-fold defaultstate="collapsed" desc="hashCode">
  3667     /**
  3668      * Compute a hash code on a type.
  3669      */
  3670     public int hashCode(Type t) {
  3671         return hashCode.visit(t);
  3673     // where
  3674         private static final UnaryVisitor<Integer> hashCode = new UnaryVisitor<Integer>() {
  3676             public Integer visitType(Type t, Void ignored) {
  3677                 return t.getTag().ordinal();
  3680             @Override
  3681             public Integer visitClassType(ClassType t, Void ignored) {
  3682                 int result = visit(t.getEnclosingType());
  3683                 result *= 127;
  3684                 result += t.tsym.flatName().hashCode();
  3685                 for (Type s : t.getTypeArguments()) {
  3686                     result *= 127;
  3687                     result += visit(s);
  3689                 return result;
  3692             @Override
  3693             public Integer visitMethodType(MethodType t, Void ignored) {
  3694                 int h = METHOD.ordinal();
  3695                 for (List<Type> thisargs = t.argtypes;
  3696                      thisargs.tail != null;
  3697                      thisargs = thisargs.tail)
  3698                     h = (h << 5) + visit(thisargs.head);
  3699                 return (h << 5) + visit(t.restype);
  3702             @Override
  3703             public Integer visitWildcardType(WildcardType t, Void ignored) {
  3704                 int result = t.kind.hashCode();
  3705                 if (t.type != null) {
  3706                     result *= 127;
  3707                     result += visit(t.type);
  3709                 return result;
  3712             @Override
  3713             public Integer visitArrayType(ArrayType t, Void ignored) {
  3714                 return visit(t.elemtype) + 12;
  3717             @Override
  3718             public Integer visitTypeVar(TypeVar t, Void ignored) {
  3719                 return System.identityHashCode(t.tsym);
  3722             @Override
  3723             public Integer visitUndetVar(UndetVar t, Void ignored) {
  3724                 return System.identityHashCode(t);
  3727             @Override
  3728             public Integer visitErrorType(ErrorType t, Void ignored) {
  3729                 return 0;
  3731         };
  3732     // </editor-fold>
  3734     // <editor-fold defaultstate="collapsed" desc="Return-Type-Substitutable">
  3735     /**
  3736      * Does t have a result that is a subtype of the result type of s,
  3737      * suitable for covariant returns?  It is assumed that both types
  3738      * are (possibly polymorphic) method types.  Monomorphic method
  3739      * types are handled in the obvious way.  Polymorphic method types
  3740      * require renaming all type variables of one to corresponding
  3741      * type variables in the other, where correspondence is by
  3742      * position in the type parameter list. */
  3743     public boolean resultSubtype(Type t, Type s, Warner warner) {
  3744         List<Type> tvars = t.getTypeArguments();
  3745         List<Type> svars = s.getTypeArguments();
  3746         Type tres = t.getReturnType();
  3747         Type sres = subst(s.getReturnType(), svars, tvars);
  3748         return covariantReturnType(tres, sres, warner);
  3751     /**
  3752      * Return-Type-Substitutable.
  3753      * @jls section 8.4.5
  3754      */
  3755     public boolean returnTypeSubstitutable(Type r1, Type r2) {
  3756         if (hasSameArgs(r1, r2))
  3757             return resultSubtype(r1, r2, noWarnings);
  3758         else
  3759             return covariantReturnType(r1.getReturnType(),
  3760                                        erasure(r2.getReturnType()),
  3761                                        noWarnings);
  3764     public boolean returnTypeSubstitutable(Type r1,
  3765                                            Type r2, Type r2res,
  3766                                            Warner warner) {
  3767         if (isSameType(r1.getReturnType(), r2res))
  3768             return true;
  3769         if (r1.getReturnType().isPrimitive() || r2res.isPrimitive())
  3770             return false;
  3772         if (hasSameArgs(r1, r2))
  3773             return covariantReturnType(r1.getReturnType(), r2res, warner);
  3774         if (!allowCovariantReturns)
  3775             return false;
  3776         if (isSubtypeUnchecked(r1.getReturnType(), r2res, warner))
  3777             return true;
  3778         if (!isSubtype(r1.getReturnType(), erasure(r2res)))
  3779             return false;
  3780         warner.warn(LintCategory.UNCHECKED);
  3781         return true;
  3784     /**
  3785      * Is t an appropriate return type in an overrider for a
  3786      * method that returns s?
  3787      */
  3788     public boolean covariantReturnType(Type t, Type s, Warner warner) {
  3789         return
  3790             isSameType(t, s) ||
  3791             allowCovariantReturns &&
  3792             !t.isPrimitive() &&
  3793             !s.isPrimitive() &&
  3794             isAssignable(t, s, warner);
  3796     // </editor-fold>
  3798     // <editor-fold defaultstate="collapsed" desc="Box/unbox support">
  3799     /**
  3800      * Return the class that boxes the given primitive.
  3801      */
  3802     public ClassSymbol boxedClass(Type t) {
  3803         return reader.enterClass(syms.boxedName[t.getTag().ordinal()]);
  3806     /**
  3807      * Return the boxed type if 't' is primitive, otherwise return 't' itself.
  3808      */
  3809     public Type boxedTypeOrType(Type t) {
  3810         return t.isPrimitive() ?
  3811             boxedClass(t).type :
  3812             t;
  3815     /**
  3816      * Return the primitive type corresponding to a boxed type.
  3817      */
  3818     public Type unboxedType(Type t) {
  3819         if (allowBoxing) {
  3820             for (int i=0; i<syms.boxedName.length; i++) {
  3821                 Name box = syms.boxedName[i];
  3822                 if (box != null &&
  3823                     asSuper(t, reader.enterClass(box)) != null)
  3824                     return syms.typeOfTag[i];
  3827         return Type.noType;
  3830     /**
  3831      * Return the unboxed type if 't' is a boxed class, otherwise return 't' itself.
  3832      */
  3833     public Type unboxedTypeOrType(Type t) {
  3834         Type unboxedType = unboxedType(t);
  3835         return unboxedType.hasTag(NONE) ? t : unboxedType;
  3837     // </editor-fold>
  3839     // <editor-fold defaultstate="collapsed" desc="Capture conversion">
  3840     /*
  3841      * JLS 5.1.10 Capture Conversion:
  3843      * Let G name a generic type declaration with n formal type
  3844      * parameters A1 ... An with corresponding bounds U1 ... Un. There
  3845      * exists a capture conversion from G<T1 ... Tn> to G<S1 ... Sn>,
  3846      * where, for 1 <= i <= n:
  3848      * + If Ti is a wildcard type argument (4.5.1) of the form ? then
  3849      *   Si is a fresh type variable whose upper bound is
  3850      *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is the null
  3851      *   type.
  3853      * + If Ti is a wildcard type argument of the form ? extends Bi,
  3854      *   then Si is a fresh type variable whose upper bound is
  3855      *   glb(Bi, Ui[A1 := S1, ..., An := Sn]) and whose lower bound is
  3856      *   the null type, where glb(V1,... ,Vm) is V1 & ... & Vm. It is
  3857      *   a compile-time error if for any two classes (not interfaces)
  3858      *   Vi and Vj,Vi is not a subclass of Vj or vice versa.
  3860      * + If Ti is a wildcard type argument of the form ? super Bi,
  3861      *   then Si is a fresh type variable whose upper bound is
  3862      *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is Bi.
  3864      * + Otherwise, Si = Ti.
  3866      * Capture conversion on any type other than a parameterized type
  3867      * (4.5) acts as an identity conversion (5.1.1). Capture
  3868      * conversions never require a special action at run time and
  3869      * therefore never throw an exception at run time.
  3871      * Capture conversion is not applied recursively.
  3872      */
  3873     /**
  3874      * Capture conversion as specified by the JLS.
  3875      */
  3877     public List<Type> capture(List<Type> ts) {
  3878         List<Type> buf = List.nil();
  3879         for (Type t : ts) {
  3880             buf = buf.prepend(capture(t));
  3882         return buf.reverse();
  3885     public Type capture(Type t) {
  3886         if (!t.hasTag(CLASS)) {
  3887             return t;
  3889         if (t.getEnclosingType() != Type.noType) {
  3890             Type capturedEncl = capture(t.getEnclosingType());
  3891             if (capturedEncl != t.getEnclosingType()) {
  3892                 Type type1 = memberType(capturedEncl, t.tsym);
  3893                 t = subst(type1, t.tsym.type.getTypeArguments(), t.getTypeArguments());
  3896         t = t.unannotatedType();
  3897         ClassType cls = (ClassType)t;
  3898         if (cls.isRaw() || !cls.isParameterized())
  3899             return cls;
  3901         ClassType G = (ClassType)cls.asElement().asType();
  3902         List<Type> A = G.getTypeArguments();
  3903         List<Type> T = cls.getTypeArguments();
  3904         List<Type> S = freshTypeVariables(T);
  3906         List<Type> currentA = A;
  3907         List<Type> currentT = T;
  3908         List<Type> currentS = S;
  3909         boolean captured = false;
  3910         while (!currentA.isEmpty() &&
  3911                !currentT.isEmpty() &&
  3912                !currentS.isEmpty()) {
  3913             if (currentS.head != currentT.head) {
  3914                 captured = true;
  3915                 WildcardType Ti = (WildcardType)currentT.head.unannotatedType();
  3916                 Type Ui = currentA.head.getUpperBound();
  3917                 CapturedType Si = (CapturedType)currentS.head.unannotatedType();
  3918                 if (Ui == null)
  3919                     Ui = syms.objectType;
  3920                 switch (Ti.kind) {
  3921                 case UNBOUND:
  3922                     Si.bound = subst(Ui, A, S);
  3923                     Si.lower = syms.botType;
  3924                     break;
  3925                 case EXTENDS:
  3926                     Si.bound = glb(Ti.getExtendsBound(), subst(Ui, A, S));
  3927                     Si.lower = syms.botType;
  3928                     break;
  3929                 case SUPER:
  3930                     Si.bound = subst(Ui, A, S);
  3931                     Si.lower = Ti.getSuperBound();
  3932                     break;
  3934                 if (Si.bound == Si.lower)
  3935                     currentS.head = Si.bound;
  3937             currentA = currentA.tail;
  3938             currentT = currentT.tail;
  3939             currentS = currentS.tail;
  3941         if (!currentA.isEmpty() || !currentT.isEmpty() || !currentS.isEmpty())
  3942             return erasure(t); // some "rare" type involved
  3944         if (captured)
  3945             return new ClassType(cls.getEnclosingType(), S, cls.tsym);
  3946         else
  3947             return t;
  3949     // where
  3950         public List<Type> freshTypeVariables(List<Type> types) {
  3951             ListBuffer<Type> result = new ListBuffer<>();
  3952             for (Type t : types) {
  3953                 if (t.hasTag(WILDCARD)) {
  3954                     t = t.unannotatedType();
  3955                     Type bound = ((WildcardType)t).getExtendsBound();
  3956                     if (bound == null)
  3957                         bound = syms.objectType;
  3958                     result.append(new CapturedType(capturedName,
  3959                                                    syms.noSymbol,
  3960                                                    bound,
  3961                                                    syms.botType,
  3962                                                    (WildcardType)t));
  3963                 } else {
  3964                     result.append(t);
  3967             return result.toList();
  3969     // </editor-fold>
  3971     // <editor-fold defaultstate="collapsed" desc="Internal utility methods">
  3972     private List<Type> upperBounds(List<Type> ss) {
  3973         if (ss.isEmpty()) return ss;
  3974         Type head = upperBound(ss.head);
  3975         List<Type> tail = upperBounds(ss.tail);
  3976         if (head != ss.head || tail != ss.tail)
  3977             return tail.prepend(head);
  3978         else
  3979             return ss;
  3982     private boolean sideCast(Type from, Type to, Warner warn) {
  3983         // We are casting from type $from$ to type $to$, which are
  3984         // non-final unrelated types.  This method
  3985         // tries to reject a cast by transferring type parameters
  3986         // from $to$ to $from$ by common superinterfaces.
  3987         boolean reverse = false;
  3988         Type target = to;
  3989         if ((to.tsym.flags() & INTERFACE) == 0) {
  3990             Assert.check((from.tsym.flags() & INTERFACE) != 0);
  3991             reverse = true;
  3992             to = from;
  3993             from = target;
  3995         List<Type> commonSupers = superClosure(to, erasure(from));
  3996         boolean giveWarning = commonSupers.isEmpty();
  3997         // The arguments to the supers could be unified here to
  3998         // get a more accurate analysis
  3999         while (commonSupers.nonEmpty()) {
  4000             Type t1 = asSuper(from, commonSupers.head.tsym);
  4001             Type t2 = commonSupers.head; // same as asSuper(to, commonSupers.head.tsym);
  4002             if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
  4003                 return false;
  4004             giveWarning = giveWarning || (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2));
  4005             commonSupers = commonSupers.tail;
  4007         if (giveWarning && !isReifiable(reverse ? from : to))
  4008             warn.warn(LintCategory.UNCHECKED);
  4009         if (!allowCovariantReturns)
  4010             // reject if there is a common method signature with
  4011             // incompatible return types.
  4012             chk.checkCompatibleAbstracts(warn.pos(), from, to);
  4013         return true;
  4016     private boolean sideCastFinal(Type from, Type to, Warner warn) {
  4017         // We are casting from type $from$ to type $to$, which are
  4018         // unrelated types one of which is final and the other of
  4019         // which is an interface.  This method
  4020         // tries to reject a cast by transferring type parameters
  4021         // from the final class to the interface.
  4022         boolean reverse = false;
  4023         Type target = to;
  4024         if ((to.tsym.flags() & INTERFACE) == 0) {
  4025             Assert.check((from.tsym.flags() & INTERFACE) != 0);
  4026             reverse = true;
  4027             to = from;
  4028             from = target;
  4030         Assert.check((from.tsym.flags() & FINAL) != 0);
  4031         Type t1 = asSuper(from, to.tsym);
  4032         if (t1 == null) return false;
  4033         Type t2 = to;
  4034         if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
  4035             return false;
  4036         if (!allowCovariantReturns)
  4037             // reject if there is a common method signature with
  4038             // incompatible return types.
  4039             chk.checkCompatibleAbstracts(warn.pos(), from, to);
  4040         if (!isReifiable(target) &&
  4041             (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2)))
  4042             warn.warn(LintCategory.UNCHECKED);
  4043         return true;
  4046     private boolean giveWarning(Type from, Type to) {
  4047         List<Type> bounds = to.isCompound() ?
  4048                 ((IntersectionClassType)to.unannotatedType()).getComponents() : List.of(to);
  4049         for (Type b : bounds) {
  4050             Type subFrom = asSub(from, b.tsym);
  4051             if (b.isParameterized() &&
  4052                     (!(isUnbounded(b) ||
  4053                     isSubtype(from, b) ||
  4054                     ((subFrom != null) && containsType(b.allparams(), subFrom.allparams()))))) {
  4055                 return true;
  4058         return false;
  4061     private List<Type> superClosure(Type t, Type s) {
  4062         List<Type> cl = List.nil();
  4063         for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
  4064             if (isSubtype(s, erasure(l.head))) {
  4065                 cl = insert(cl, l.head);
  4066             } else {
  4067                 cl = union(cl, superClosure(l.head, s));
  4070         return cl;
  4073     private boolean containsTypeEquivalent(Type t, Type s) {
  4074         return
  4075             isSameType(t, s) || // shortcut
  4076             containsType(t, s) && containsType(s, t);
  4079     // <editor-fold defaultstate="collapsed" desc="adapt">
  4080     /**
  4081      * Adapt a type by computing a substitution which maps a source
  4082      * type to a target type.
  4084      * @param source    the source type
  4085      * @param target    the target type
  4086      * @param from      the type variables of the computed substitution
  4087      * @param to        the types of the computed substitution.
  4088      */
  4089     public void adapt(Type source,
  4090                        Type target,
  4091                        ListBuffer<Type> from,
  4092                        ListBuffer<Type> to) throws AdaptFailure {
  4093         new Adapter(from, to).adapt(source, target);
  4096     class Adapter extends SimpleVisitor<Void, Type> {
  4098         ListBuffer<Type> from;
  4099         ListBuffer<Type> to;
  4100         Map<Symbol,Type> mapping;
  4102         Adapter(ListBuffer<Type> from, ListBuffer<Type> to) {
  4103             this.from = from;
  4104             this.to = to;
  4105             mapping = new HashMap<Symbol,Type>();
  4108         public void adapt(Type source, Type target) throws AdaptFailure {
  4109             visit(source, target);
  4110             List<Type> fromList = from.toList();
  4111             List<Type> toList = to.toList();
  4112             while (!fromList.isEmpty()) {
  4113                 Type val = mapping.get(fromList.head.tsym);
  4114                 if (toList.head != val)
  4115                     toList.head = val;
  4116                 fromList = fromList.tail;
  4117                 toList = toList.tail;
  4121         @Override
  4122         public Void visitClassType(ClassType source, Type target) throws AdaptFailure {
  4123             if (target.hasTag(CLASS))
  4124                 adaptRecursive(source.allparams(), target.allparams());
  4125             return null;
  4128         @Override
  4129         public Void visitArrayType(ArrayType source, Type target) throws AdaptFailure {
  4130             if (target.hasTag(ARRAY))
  4131                 adaptRecursive(elemtype(source), elemtype(target));
  4132             return null;
  4135         @Override
  4136         public Void visitWildcardType(WildcardType source, Type target) throws AdaptFailure {
  4137             if (source.isExtendsBound())
  4138                 adaptRecursive(upperBound(source), upperBound(target));
  4139             else if (source.isSuperBound())
  4140                 adaptRecursive(lowerBound(source), lowerBound(target));
  4141             return null;
  4144         @Override
  4145         public Void visitTypeVar(TypeVar source, Type target) throws AdaptFailure {
  4146             // Check to see if there is
  4147             // already a mapping for $source$, in which case
  4148             // the old mapping will be merged with the new
  4149             Type val = mapping.get(source.tsym);
  4150             if (val != null) {
  4151                 if (val.isSuperBound() && target.isSuperBound()) {
  4152                     val = isSubtype(lowerBound(val), lowerBound(target))
  4153                         ? target : val;
  4154                 } else if (val.isExtendsBound() && target.isExtendsBound()) {
  4155                     val = isSubtype(upperBound(val), upperBound(target))
  4156                         ? val : target;
  4157                 } else if (!isSameType(val, target)) {
  4158                     throw new AdaptFailure();
  4160             } else {
  4161                 val = target;
  4162                 from.append(source);
  4163                 to.append(target);
  4165             mapping.put(source.tsym, val);
  4166             return null;
  4169         @Override
  4170         public Void visitType(Type source, Type target) {
  4171             return null;
  4174         private Set<TypePair> cache = new HashSet<TypePair>();
  4176         private void adaptRecursive(Type source, Type target) {
  4177             TypePair pair = new TypePair(source, target);
  4178             if (cache.add(pair)) {
  4179                 try {
  4180                     visit(source, target);
  4181                 } finally {
  4182                     cache.remove(pair);
  4187         private void adaptRecursive(List<Type> source, List<Type> target) {
  4188             if (source.length() == target.length()) {
  4189                 while (source.nonEmpty()) {
  4190                     adaptRecursive(source.head, target.head);
  4191                     source = source.tail;
  4192                     target = target.tail;
  4198     public static class AdaptFailure extends RuntimeException {
  4199         static final long serialVersionUID = -7490231548272701566L;
  4202     private void adaptSelf(Type t,
  4203                            ListBuffer<Type> from,
  4204                            ListBuffer<Type> to) {
  4205         try {
  4206             //if (t.tsym.type != t)
  4207                 adapt(t.tsym.type, t, from, to);
  4208         } catch (AdaptFailure ex) {
  4209             // Adapt should never fail calculating a mapping from
  4210             // t.tsym.type to t as there can be no merge problem.
  4211             throw new AssertionError(ex);
  4214     // </editor-fold>
  4216     /**
  4217      * Rewrite all type variables (universal quantifiers) in the given
  4218      * type to wildcards (existential quantifiers).  This is used to
  4219      * determine if a cast is allowed.  For example, if high is true
  4220      * and {@code T <: Number}, then {@code List<T>} is rewritten to
  4221      * {@code List<?  extends Number>}.  Since {@code List<Integer> <:
  4222      * List<? extends Number>} a {@code List<T>} can be cast to {@code
  4223      * List<Integer>} with a warning.
  4224      * @param t a type
  4225      * @param high if true return an upper bound; otherwise a lower
  4226      * bound
  4227      * @param rewriteTypeVars only rewrite captured wildcards if false;
  4228      * otherwise rewrite all type variables
  4229      * @return the type rewritten with wildcards (existential
  4230      * quantifiers) only
  4231      */
  4232     private Type rewriteQuantifiers(Type t, boolean high, boolean rewriteTypeVars) {
  4233         return new Rewriter(high, rewriteTypeVars).visit(t);
  4236     class Rewriter extends UnaryVisitor<Type> {
  4238         boolean high;
  4239         boolean rewriteTypeVars;
  4241         Rewriter(boolean high, boolean rewriteTypeVars) {
  4242             this.high = high;
  4243             this.rewriteTypeVars = rewriteTypeVars;
  4246         @Override
  4247         public Type visitClassType(ClassType t, Void s) {
  4248             ListBuffer<Type> rewritten = new ListBuffer<Type>();
  4249             boolean changed = false;
  4250             for (Type arg : t.allparams()) {
  4251                 Type bound = visit(arg);
  4252                 if (arg != bound) {
  4253                     changed = true;
  4255                 rewritten.append(bound);
  4257             if (changed)
  4258                 return subst(t.tsym.type,
  4259                         t.tsym.type.allparams(),
  4260                         rewritten.toList());
  4261             else
  4262                 return t;
  4265         public Type visitType(Type t, Void s) {
  4266             return high ? upperBound(t) : lowerBound(t);
  4269         @Override
  4270         public Type visitCapturedType(CapturedType t, Void s) {
  4271             Type w_bound = t.wildcard.type;
  4272             Type bound = w_bound.contains(t) ?
  4273                         erasure(w_bound) :
  4274                         visit(w_bound);
  4275             return rewriteAsWildcardType(visit(bound), t.wildcard.bound, t.wildcard.kind);
  4278         @Override
  4279         public Type visitTypeVar(TypeVar t, Void s) {
  4280             if (rewriteTypeVars) {
  4281                 Type bound = t.bound.contains(t) ?
  4282                         erasure(t.bound) :
  4283                         visit(t.bound);
  4284                 return rewriteAsWildcardType(bound, t, EXTENDS);
  4285             } else {
  4286                 return t;
  4290         @Override
  4291         public Type visitWildcardType(WildcardType t, Void s) {
  4292             Type bound2 = visit(t.type);
  4293             return t.type == bound2 ? t : rewriteAsWildcardType(bound2, t.bound, t.kind);
  4296         private Type rewriteAsWildcardType(Type bound, TypeVar formal, BoundKind bk) {
  4297             switch (bk) {
  4298                case EXTENDS: return high ?
  4299                        makeExtendsWildcard(B(bound), formal) :
  4300                        makeExtendsWildcard(syms.objectType, formal);
  4301                case SUPER: return high ?
  4302                        makeSuperWildcard(syms.botType, formal) :
  4303                        makeSuperWildcard(B(bound), formal);
  4304                case UNBOUND: return makeExtendsWildcard(syms.objectType, formal);
  4305                default:
  4306                    Assert.error("Invalid bound kind " + bk);
  4307                    return null;
  4311         Type B(Type t) {
  4312             while (t.hasTag(WILDCARD)) {
  4313                 WildcardType w = (WildcardType)t.unannotatedType();
  4314                 t = high ?
  4315                     w.getExtendsBound() :
  4316                     w.getSuperBound();
  4317                 if (t == null) {
  4318                     t = high ? syms.objectType : syms.botType;
  4321             return t;
  4326     /**
  4327      * Create a wildcard with the given upper (extends) bound; create
  4328      * an unbounded wildcard if bound is Object.
  4330      * @param bound the upper bound
  4331      * @param formal the formal type parameter that will be
  4332      * substituted by the wildcard
  4333      */
  4334     private WildcardType makeExtendsWildcard(Type bound, TypeVar formal) {
  4335         if (bound == syms.objectType) {
  4336             return new WildcardType(syms.objectType,
  4337                                     BoundKind.UNBOUND,
  4338                                     syms.boundClass,
  4339                                     formal);
  4340         } else {
  4341             return new WildcardType(bound,
  4342                                     BoundKind.EXTENDS,
  4343                                     syms.boundClass,
  4344                                     formal);
  4348     /**
  4349      * Create a wildcard with the given lower (super) bound; create an
  4350      * unbounded wildcard if bound is bottom (type of {@code null}).
  4352      * @param bound the lower bound
  4353      * @param formal the formal type parameter that will be
  4354      * substituted by the wildcard
  4355      */
  4356     private WildcardType makeSuperWildcard(Type bound, TypeVar formal) {
  4357         if (bound.hasTag(BOT)) {
  4358             return new WildcardType(syms.objectType,
  4359                                     BoundKind.UNBOUND,
  4360                                     syms.boundClass,
  4361                                     formal);
  4362         } else {
  4363             return new WildcardType(bound,
  4364                                     BoundKind.SUPER,
  4365                                     syms.boundClass,
  4366                                     formal);
  4370     /**
  4371      * A wrapper for a type that allows use in sets.
  4372      */
  4373     public static class UniqueType {
  4374         public final Type type;
  4375         final Types types;
  4377         public UniqueType(Type type, Types types) {
  4378             this.type = type;
  4379             this.types = types;
  4382         public int hashCode() {
  4383             return types.hashCode(type);
  4386         public boolean equals(Object obj) {
  4387             return (obj instanceof UniqueType) &&
  4388                 types.isSameAnnotatedType(type, ((UniqueType)obj).type);
  4391         public String toString() {
  4392             return type.toString();
  4396     // </editor-fold>
  4398     // <editor-fold defaultstate="collapsed" desc="Visitors">
  4399     /**
  4400      * A default visitor for types.  All visitor methods except
  4401      * visitType are implemented by delegating to visitType.  Concrete
  4402      * subclasses must provide an implementation of visitType and can
  4403      * override other methods as needed.
  4405      * @param <R> the return type of the operation implemented by this
  4406      * visitor; use Void if no return type is needed.
  4407      * @param <S> the type of the second argument (the first being the
  4408      * type itself) of the operation implemented by this visitor; use
  4409      * Void if a second argument is not needed.
  4410      */
  4411     public static abstract class DefaultTypeVisitor<R,S> implements Type.Visitor<R,S> {
  4412         final public R visit(Type t, S s)               { return t.accept(this, s); }
  4413         public R visitClassType(ClassType t, S s)       { return visitType(t, s); }
  4414         public R visitWildcardType(WildcardType t, S s) { return visitType(t, s); }
  4415         public R visitArrayType(ArrayType t, S s)       { return visitType(t, s); }
  4416         public R visitMethodType(MethodType t, S s)     { return visitType(t, s); }
  4417         public R visitPackageType(PackageType t, S s)   { return visitType(t, s); }
  4418         public R visitTypeVar(TypeVar t, S s)           { return visitType(t, s); }
  4419         public R visitCapturedType(CapturedType t, S s) { return visitType(t, s); }
  4420         public R visitForAll(ForAll t, S s)             { return visitType(t, s); }
  4421         public R visitUndetVar(UndetVar t, S s)         { return visitType(t, s); }
  4422         public R visitErrorType(ErrorType t, S s)       { return visitType(t, s); }
  4423         // Pretend annotations don't exist
  4424         public R visitAnnotatedType(AnnotatedType t, S s) { return visit(t.unannotatedType(), s); }
  4427     /**
  4428      * A default visitor for symbols.  All visitor methods except
  4429      * visitSymbol are implemented by delegating to visitSymbol.  Concrete
  4430      * subclasses must provide an implementation of visitSymbol and can
  4431      * override other methods as needed.
  4433      * @param <R> the return type of the operation implemented by this
  4434      * visitor; use Void if no return type is needed.
  4435      * @param <S> the type of the second argument (the first being the
  4436      * symbol itself) of the operation implemented by this visitor; use
  4437      * Void if a second argument is not needed.
  4438      */
  4439     public static abstract class DefaultSymbolVisitor<R,S> implements Symbol.Visitor<R,S> {
  4440         final public R visit(Symbol s, S arg)                   { return s.accept(this, arg); }
  4441         public R visitClassSymbol(ClassSymbol s, S arg)         { return visitSymbol(s, arg); }
  4442         public R visitMethodSymbol(MethodSymbol s, S arg)       { return visitSymbol(s, arg); }
  4443         public R visitOperatorSymbol(OperatorSymbol s, S arg)   { return visitSymbol(s, arg); }
  4444         public R visitPackageSymbol(PackageSymbol s, S arg)     { return visitSymbol(s, arg); }
  4445         public R visitTypeSymbol(TypeSymbol s, S arg)           { return visitSymbol(s, arg); }
  4446         public R visitVarSymbol(VarSymbol s, S arg)             { return visitSymbol(s, arg); }
  4449     /**
  4450      * A <em>simple</em> visitor for types.  This visitor is simple as
  4451      * captured wildcards, for-all types (generic methods), and
  4452      * undetermined type variables (part of inference) are hidden.
  4453      * Captured wildcards are hidden by treating them as type
  4454      * variables and the rest are hidden by visiting their qtypes.
  4456      * @param <R> the return type of the operation implemented by this
  4457      * visitor; use Void if no return type is needed.
  4458      * @param <S> the type of the second argument (the first being the
  4459      * type itself) of the operation implemented by this visitor; use
  4460      * Void if a second argument is not needed.
  4461      */
  4462     public static abstract class SimpleVisitor<R,S> extends DefaultTypeVisitor<R,S> {
  4463         @Override
  4464         public R visitCapturedType(CapturedType t, S s) {
  4465             return visitTypeVar(t, s);
  4467         @Override
  4468         public R visitForAll(ForAll t, S s) {
  4469             return visit(t.qtype, s);
  4471         @Override
  4472         public R visitUndetVar(UndetVar t, S s) {
  4473             return visit(t.qtype, s);
  4477     /**
  4478      * A plain relation on types.  That is a 2-ary function on the
  4479      * form Type&nbsp;&times;&nbsp;Type&nbsp;&rarr;&nbsp;Boolean.
  4480      * <!-- In plain text: Type x Type -> Boolean -->
  4481      */
  4482     public static abstract class TypeRelation extends SimpleVisitor<Boolean,Type> {}
  4484     /**
  4485      * A convenience visitor for implementing operations that only
  4486      * require one argument (the type itself), that is, unary
  4487      * operations.
  4489      * @param <R> the return type of the operation implemented by this
  4490      * visitor; use Void if no return type is needed.
  4491      */
  4492     public static abstract class UnaryVisitor<R> extends SimpleVisitor<R,Void> {
  4493         final public R visit(Type t) { return t.accept(this, null); }
  4496     /**
  4497      * A visitor for implementing a mapping from types to types.  The
  4498      * default behavior of this class is to implement the identity
  4499      * mapping (mapping a type to itself).  This can be overridden in
  4500      * subclasses.
  4502      * @param <S> the type of the second argument (the first being the
  4503      * type itself) of this mapping; use Void if a second argument is
  4504      * not needed.
  4505      */
  4506     public static class MapVisitor<S> extends DefaultTypeVisitor<Type,S> {
  4507         final public Type visit(Type t) { return t.accept(this, null); }
  4508         public Type visitType(Type t, S s) { return t; }
  4510     // </editor-fold>
  4513     // <editor-fold defaultstate="collapsed" desc="Annotation support">
  4515     public RetentionPolicy getRetention(Attribute.Compound a) {
  4516         return getRetention(a.type.tsym);
  4519     public RetentionPolicy getRetention(Symbol sym) {
  4520         RetentionPolicy vis = RetentionPolicy.CLASS; // the default
  4521         Attribute.Compound c = sym.attribute(syms.retentionType.tsym);
  4522         if (c != null) {
  4523             Attribute value = c.member(names.value);
  4524             if (value != null && value instanceof Attribute.Enum) {
  4525                 Name levelName = ((Attribute.Enum)value).value.name;
  4526                 if (levelName == names.SOURCE) vis = RetentionPolicy.SOURCE;
  4527                 else if (levelName == names.CLASS) vis = RetentionPolicy.CLASS;
  4528                 else if (levelName == names.RUNTIME) vis = RetentionPolicy.RUNTIME;
  4529                 else ;// /* fail soft */ throw new AssertionError(levelName);
  4532         return vis;
  4534     // </editor-fold>
  4536     // <editor-fold defaultstate="collapsed" desc="Signature Generation">
  4538     public static abstract class SignatureGenerator {
  4540         private final Types types;
  4542         protected abstract void append(char ch);
  4543         protected abstract void append(byte[] ba);
  4544         protected abstract void append(Name name);
  4545         protected void classReference(ClassSymbol c) { /* by default: no-op */ }
  4547         protected SignatureGenerator(Types types) {
  4548             this.types = types;
  4551         /**
  4552          * Assemble signature of given type in string buffer.
  4553          */
  4554         public void assembleSig(Type type) {
  4555             type = type.unannotatedType();
  4556             switch (type.getTag()) {
  4557                 case BYTE:
  4558                     append('B');
  4559                     break;
  4560                 case SHORT:
  4561                     append('S');
  4562                     break;
  4563                 case CHAR:
  4564                     append('C');
  4565                     break;
  4566                 case INT:
  4567                     append('I');
  4568                     break;
  4569                 case LONG:
  4570                     append('J');
  4571                     break;
  4572                 case FLOAT:
  4573                     append('F');
  4574                     break;
  4575                 case DOUBLE:
  4576                     append('D');
  4577                     break;
  4578                 case BOOLEAN:
  4579                     append('Z');
  4580                     break;
  4581                 case VOID:
  4582                     append('V');
  4583                     break;
  4584                 case CLASS:
  4585                     append('L');
  4586                     assembleClassSig(type);
  4587                     append(';');
  4588                     break;
  4589                 case ARRAY:
  4590                     ArrayType at = (ArrayType) type;
  4591                     append('[');
  4592                     assembleSig(at.elemtype);
  4593                     break;
  4594                 case METHOD:
  4595                     MethodType mt = (MethodType) type;
  4596                     append('(');
  4597                     assembleSig(mt.argtypes);
  4598                     append(')');
  4599                     assembleSig(mt.restype);
  4600                     if (hasTypeVar(mt.thrown)) {
  4601                         for (List<Type> l = mt.thrown; l.nonEmpty(); l = l.tail) {
  4602                             append('^');
  4603                             assembleSig(l.head);
  4606                     break;
  4607                 case WILDCARD: {
  4608                     Type.WildcardType ta = (Type.WildcardType) type;
  4609                     switch (ta.kind) {
  4610                         case SUPER:
  4611                             append('-');
  4612                             assembleSig(ta.type);
  4613                             break;
  4614                         case EXTENDS:
  4615                             append('+');
  4616                             assembleSig(ta.type);
  4617                             break;
  4618                         case UNBOUND:
  4619                             append('*');
  4620                             break;
  4621                         default:
  4622                             throw new AssertionError(ta.kind);
  4624                     break;
  4626                 case TYPEVAR:
  4627                     append('T');
  4628                     append(type.tsym.name);
  4629                     append(';');
  4630                     break;
  4631                 case FORALL:
  4632                     Type.ForAll ft = (Type.ForAll) type;
  4633                     assembleParamsSig(ft.tvars);
  4634                     assembleSig(ft.qtype);
  4635                     break;
  4636                 default:
  4637                     throw new AssertionError("typeSig " + type.getTag());
  4641         public boolean hasTypeVar(List<Type> l) {
  4642             while (l.nonEmpty()) {
  4643                 if (l.head.hasTag(TypeTag.TYPEVAR)) {
  4644                     return true;
  4646                 l = l.tail;
  4648             return false;
  4651         public void assembleClassSig(Type type) {
  4652             type = type.unannotatedType();
  4653             ClassType ct = (ClassType) type;
  4654             ClassSymbol c = (ClassSymbol) ct.tsym;
  4655             classReference(c);
  4656             Type outer = ct.getEnclosingType();
  4657             if (outer.allparams().nonEmpty()) {
  4658                 boolean rawOuter =
  4659                         c.owner.kind == Kinds.MTH || // either a local class
  4660                         c.name == types.names.empty; // or anonymous
  4661                 assembleClassSig(rawOuter
  4662                         ? types.erasure(outer)
  4663                         : outer);
  4664                 append('.');
  4665                 Assert.check(c.flatname.startsWith(c.owner.enclClass().flatname));
  4666                 append(rawOuter
  4667                         ? c.flatname.subName(c.owner.enclClass().flatname.getByteLength() + 1, c.flatname.getByteLength())
  4668                         : c.name);
  4669             } else {
  4670                 append(externalize(c.flatname));
  4672             if (ct.getTypeArguments().nonEmpty()) {
  4673                 append('<');
  4674                 assembleSig(ct.getTypeArguments());
  4675                 append('>');
  4679         public void assembleParamsSig(List<Type> typarams) {
  4680             append('<');
  4681             for (List<Type> ts = typarams; ts.nonEmpty(); ts = ts.tail) {
  4682                 Type.TypeVar tvar = (Type.TypeVar) ts.head;
  4683                 append(tvar.tsym.name);
  4684                 List<Type> bounds = types.getBounds(tvar);
  4685                 if ((bounds.head.tsym.flags() & INTERFACE) != 0) {
  4686                     append(':');
  4688                 for (List<Type> l = bounds; l.nonEmpty(); l = l.tail) {
  4689                     append(':');
  4690                     assembleSig(l.head);
  4693             append('>');
  4696         private void assembleSig(List<Type> types) {
  4697             for (List<Type> ts = types; ts.nonEmpty(); ts = ts.tail) {
  4698                 assembleSig(ts.head);
  4702     // </editor-fold>

mercurial