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

Tue, 15 Oct 2013 15:57:13 -0700

author
jjg
date
Tue, 15 Oct 2013 15:57:13 -0700
changeset 2134
b0c086cd4520
parent 2079
de1c5dbe6c28
child 2187
4788eb38cac5
permissions
-rw-r--r--

8026564: import changes from type-annotations forest
Reviewed-by: jjg
Contributed-by: wdietl@gmail.com, steve.sides@oracle.com

     1 /*
     2  * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    26 package com.sun.tools.javac.code;
    28 import java.lang.ref.SoftReference;
    29 import java.util.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.util.*;
    47 import static com.sun.tools.javac.code.BoundKind.*;
    48 import static com.sun.tools.javac.code.Flags.*;
    49 import static com.sun.tools.javac.code.Scope.*;
    50 import static com.sun.tools.javac.code.Symbol.*;
    51 import static com.sun.tools.javac.code.Type.*;
    52 import static com.sun.tools.javac.code.TypeTag.*;
    53 import static com.sun.tools.javac.jvm.ClassFile.externalize;
    55 /**
    56  * Utility class containing various operations on types.
    57  *
    58  * <p>Unless other names are more illustrative, the following naming
    59  * conventions should be observed in this file:
    60  *
    61  * <dl>
    62  * <dt>t</dt>
    63  * <dd>If the first argument to an operation is a type, it should be named t.</dd>
    64  * <dt>s</dt>
    65  * <dd>Similarly, if the second argument to an operation is a type, it should be named s.</dd>
    66  * <dt>ts</dt>
    67  * <dd>If an operations takes a list of types, the first should be named ts.</dd>
    68  * <dt>ss</dt>
    69  * <dd>A second list of types should be named ss.</dd>
    70  * </dl>
    71  *
    72  * <p><b>This is NOT part of any supported API.
    73  * If you write code that depends on this, you do so at your own risk.
    74  * This code and its internal interfaces are subject to change or
    75  * deletion without notice.</b>
    76  */
    77 public class Types {
    78     protected static final Context.Key<Types> typesKey =
    79         new Context.Key<Types>();
    81     final Symtab syms;
    82     final JavacMessages messages;
    83     final Names names;
    84     final boolean allowBoxing;
    85     final boolean allowCovariantReturns;
    86     final boolean allowObjectToPrimitiveCast;
    87     final boolean allowDefaultMethods;
    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         allowDefaultMethods = source.allowDefaultMethods();
   115         reader = ClassReader.instance(context);
   116         chk = Check.instance(context);
   117         enter = Enter.instance(context);
   118         capturedName = names.fromString("<captured wildcard>");
   119         messages = JavacMessages.instance(context);
   120         diags = JCDiagnostic.Factory.instance(context);
   121         functionDescriptorLookupError = new FunctionDescriptorLookupError();
   122         noWarnings = new Warner(null);
   123     }
   124     // </editor-fold>
   126     // <editor-fold defaultstate="collapsed" desc="upperBound">
   127     /**
   128      * The "rvalue conversion".<br>
   129      * The upper bound of most types is the type
   130      * itself.  Wildcards, on the other hand have upper
   131      * and lower bounds.
   132      * @param t a type
   133      * @return the upper bound of the given type
   134      */
   135     public Type upperBound(Type t) {
   136         return upperBound.visit(t).unannotatedType();
   137     }
   138     // where
   139         private final MapVisitor<Void> upperBound = new MapVisitor<Void>() {
   141             @Override
   142             public Type visitWildcardType(WildcardType t, Void ignored) {
   143                 if (t.isSuperBound())
   144                     return t.bound == null ? syms.objectType : t.bound.bound;
   145                 else
   146                     return visit(t.type);
   147             }
   149             @Override
   150             public Type visitCapturedType(CapturedType t, Void ignored) {
   151                 return visit(t.bound);
   152             }
   153         };
   154     // </editor-fold>
   156     // <editor-fold defaultstate="collapsed" desc="lowerBound">
   157     /**
   158      * The "lvalue conversion".<br>
   159      * The lower bound of most types is the type
   160      * itself.  Wildcards, on the other hand have upper
   161      * and lower bounds.
   162      * @param t a type
   163      * @return the lower bound of the given type
   164      */
   165     public Type lowerBound(Type t) {
   166         return lowerBound.visit(t);
   167     }
   168     // where
   169         private final MapVisitor<Void> lowerBound = new MapVisitor<Void>() {
   171             @Override
   172             public Type visitWildcardType(WildcardType t, Void ignored) {
   173                 return t.isExtendsBound() ? syms.botType : visit(t.type);
   174             }
   176             @Override
   177             public Type visitCapturedType(CapturedType t, Void ignored) {
   178                 return visit(t.getLowerBound());
   179             }
   180         };
   181     // </editor-fold>
   183     // <editor-fold defaultstate="collapsed" desc="isUnbounded">
   184     /**
   185      * Checks that all the arguments to a class are unbounded
   186      * wildcards or something else that doesn't make any restrictions
   187      * on the arguments. If a class isUnbounded, a raw super- or
   188      * subclass can be cast to it without a warning.
   189      * @param t a type
   190      * @return true iff the given type is unbounded or raw
   191      */
   192     public boolean isUnbounded(Type t) {
   193         return isUnbounded.visit(t);
   194     }
   195     // where
   196         private final UnaryVisitor<Boolean> isUnbounded = new UnaryVisitor<Boolean>() {
   198             public Boolean visitType(Type t, Void ignored) {
   199                 return true;
   200             }
   202             @Override
   203             public Boolean visitClassType(ClassType t, Void ignored) {
   204                 List<Type> parms = t.tsym.type.allparams();
   205                 List<Type> args = t.allparams();
   206                 while (parms.nonEmpty()) {
   207                     WildcardType unb = new WildcardType(syms.objectType,
   208                                                         BoundKind.UNBOUND,
   209                                                         syms.boundClass,
   210                                                         (TypeVar)parms.head.unannotatedType());
   211                     if (!containsType(args.head, unb))
   212                         return false;
   213                     parms = parms.tail;
   214                     args = args.tail;
   215                 }
   216                 return true;
   217             }
   218         };
   219     // </editor-fold>
   221     // <editor-fold defaultstate="collapsed" desc="asSub">
   222     /**
   223      * Return the least specific subtype of t that starts with symbol
   224      * sym.  If none exists, return null.  The least specific subtype
   225      * is determined as follows:
   226      *
   227      * <p>If there is exactly one parameterized instance of sym that is a
   228      * subtype of t, that parameterized instance is returned.<br>
   229      * Otherwise, if the plain type or raw type `sym' is a subtype of
   230      * type t, the type `sym' itself is returned.  Otherwise, null is
   231      * returned.
   232      */
   233     public Type asSub(Type t, Symbol sym) {
   234         return asSub.visit(t, sym);
   235     }
   236     // where
   237         private final SimpleVisitor<Type,Symbol> asSub = new SimpleVisitor<Type,Symbol>() {
   239             public Type visitType(Type t, Symbol sym) {
   240                 return null;
   241             }
   243             @Override
   244             public Type visitClassType(ClassType t, Symbol sym) {
   245                 if (t.tsym == sym)
   246                     return t;
   247                 Type base = asSuper(sym.type, t);
   248                 if (base == null)
   249                     return null;
   250                 ListBuffer<Type> from = new ListBuffer<Type>();
   251                 ListBuffer<Type> to = new ListBuffer<Type>();
   252                 try {
   253                     adapt(base, t, from, to);
   254                 } catch (AdaptFailure ex) {
   255                     return null;
   256                 }
   257                 Type res = subst(sym.type, from.toList(), to.toList());
   258                 if (!isSubtype(res, t))
   259                     return null;
   260                 ListBuffer<Type> openVars = new ListBuffer<Type>();
   261                 for (List<Type> l = sym.type.allparams();
   262                      l.nonEmpty(); l = l.tail)
   263                     if (res.contains(l.head) && !t.contains(l.head))
   264                         openVars.append(l.head);
   265                 if (openVars.nonEmpty()) {
   266                     if (t.isRaw()) {
   267                         // The subtype of a raw type is raw
   268                         res = erasure(res);
   269                     } else {
   270                         // Unbound type arguments default to ?
   271                         List<Type> opens = openVars.toList();
   272                         ListBuffer<Type> qs = new ListBuffer<Type>();
   273                         for (List<Type> iter = opens; iter.nonEmpty(); iter = iter.tail) {
   274                             qs.append(new WildcardType(syms.objectType, BoundKind.UNBOUND, syms.boundClass, (TypeVar) iter.head.unannotatedType()));
   275                         }
   276                         res = subst(res, opens, qs.toList());
   277                     }
   278                 }
   279                 return res;
   280             }
   282             @Override
   283             public Type visitErrorType(ErrorType t, Symbol sym) {
   284                 return t;
   285             }
   286         };
   287     // </editor-fold>
   289     // <editor-fold defaultstate="collapsed" desc="isConvertible">
   290     /**
   291      * Is t a subtype of or convertible via boxing/unboxing
   292      * conversion to s?
   293      */
   294     public boolean isConvertible(Type t, Type s, Warner warn) {
   295         if (t.hasTag(ERROR)) {
   296             return true;
   297         }
   298         boolean tPrimitive = t.isPrimitive();
   299         boolean sPrimitive = s.isPrimitive();
   300         if (tPrimitive == sPrimitive) {
   301             return isSubtypeUnchecked(t, s, warn);
   302         }
   303         if (!allowBoxing) return false;
   304         return tPrimitive
   305             ? isSubtype(boxedClass(t).type, s)
   306             : isSubtype(unboxedType(t), s);
   307     }
   309     /**
   310      * Is t a subtype of or convertiable via boxing/unboxing
   311      * convertions to s?
   312      */
   313     public boolean isConvertible(Type t, Type s) {
   314         return isConvertible(t, s, noWarnings);
   315     }
   316     // </editor-fold>
   318     // <editor-fold defaultstate="collapsed" desc="findSam">
   320     /**
   321      * Exception used to report a function descriptor lookup failure. The exception
   322      * wraps a diagnostic that can be used to generate more details error
   323      * messages.
   324      */
   325     public static class FunctionDescriptorLookupError extends RuntimeException {
   326         private static final long serialVersionUID = 0;
   328         JCDiagnostic diagnostic;
   330         FunctionDescriptorLookupError() {
   331             this.diagnostic = null;
   332         }
   334         FunctionDescriptorLookupError setMessage(JCDiagnostic diag) {
   335             this.diagnostic = diag;
   336             return this;
   337         }
   339         public JCDiagnostic getDiagnostic() {
   340             return diagnostic;
   341         }
   342     }
   344     /**
   345      * A cache that keeps track of function descriptors associated with given
   346      * functional interfaces.
   347      */
   348     class DescriptorCache {
   350         private WeakHashMap<TypeSymbol, Entry> _map = new WeakHashMap<TypeSymbol, Entry>();
   352         class FunctionDescriptor {
   353             Symbol descSym;
   355             FunctionDescriptor(Symbol descSym) {
   356                 this.descSym = descSym;
   357             }
   359             public Symbol getSymbol() {
   360                 return descSym;
   361             }
   363             public Type getType(Type site) {
   364                 site = removeWildcards(site);
   365                 if (!chk.checkValidGenericType(site)) {
   366                     //if the inferred functional interface type is not well-formed,
   367                     //or if it's not a subtype of the original target, issue an error
   368                     throw failure(diags.fragment("no.suitable.functional.intf.inst", site));
   369                 }
   370                 return memberType(site, descSym);
   371             }
   372         }
   374         class Entry {
   375             final FunctionDescriptor cachedDescRes;
   376             final int prevMark;
   378             public Entry(FunctionDescriptor cachedDescRes,
   379                     int prevMark) {
   380                 this.cachedDescRes = cachedDescRes;
   381                 this.prevMark = prevMark;
   382             }
   384             boolean matches(int mark) {
   385                 return  this.prevMark == mark;
   386             }
   387         }
   389         FunctionDescriptor get(TypeSymbol origin) throws FunctionDescriptorLookupError {
   390             Entry e = _map.get(origin);
   391             CompoundScope members = membersClosure(origin.type, false);
   392             if (e == null ||
   393                     !e.matches(members.getMark())) {
   394                 FunctionDescriptor descRes = findDescriptorInternal(origin, members);
   395                 _map.put(origin, new Entry(descRes, members.getMark()));
   396                 return descRes;
   397             }
   398             else {
   399                 return e.cachedDescRes;
   400             }
   401         }
   403         /**
   404          * Compute the function descriptor associated with a given functional interface
   405          */
   406         public FunctionDescriptor findDescriptorInternal(TypeSymbol origin,
   407                 CompoundScope membersCache) throws FunctionDescriptorLookupError {
   408             if (!origin.isInterface() || (origin.flags() & ANNOTATION) != 0) {
   409                 //t must be an interface
   410                 throw failure("not.a.functional.intf", origin);
   411             }
   413             final ListBuffer<Symbol> abstracts = new ListBuffer<>();
   414             for (Symbol sym : membersCache.getElements(new DescriptorFilter(origin))) {
   415                 Type mtype = memberType(origin.type, sym);
   416                 if (abstracts.isEmpty() ||
   417                         (sym.name == abstracts.first().name &&
   418                         overrideEquivalent(mtype, memberType(origin.type, abstracts.first())))) {
   419                     abstracts.append(sym);
   420                 } else {
   421                     //the target method(s) should be the only abstract members of t
   422                     throw failure("not.a.functional.intf.1",  origin,
   423                             diags.fragment("incompatible.abstracts", Kinds.kindName(origin), origin));
   424                 }
   425             }
   426             if (abstracts.isEmpty()) {
   427                 //t must define a suitable non-generic method
   428                 throw failure("not.a.functional.intf.1", origin,
   429                             diags.fragment("no.abstracts", Kinds.kindName(origin), origin));
   430             } else if (abstracts.size() == 1) {
   431                 return new FunctionDescriptor(abstracts.first());
   432             } else { // size > 1
   433                 FunctionDescriptor descRes = mergeDescriptors(origin, abstracts.toList());
   434                 if (descRes == null) {
   435                     //we can get here if the functional interface is ill-formed
   436                     ListBuffer<JCDiagnostic> descriptors = new ListBuffer<>();
   437                     for (Symbol desc : abstracts) {
   438                         String key = desc.type.getThrownTypes().nonEmpty() ?
   439                                 "descriptor.throws" : "descriptor";
   440                         descriptors.append(diags.fragment(key, desc.name,
   441                                 desc.type.getParameterTypes(),
   442                                 desc.type.getReturnType(),
   443                                 desc.type.getThrownTypes()));
   444                     }
   445                     JCDiagnostic.MultilineDiagnostic incompatibleDescriptors =
   446                             new JCDiagnostic.MultilineDiagnostic(diags.fragment("incompatible.descs.in.functional.intf",
   447                             Kinds.kindName(origin), origin), descriptors.toList());
   448                     throw failure(incompatibleDescriptors);
   449                 }
   450                 return descRes;
   451             }
   452         }
   454         /**
   455          * Compute a synthetic type for the target descriptor given a list
   456          * of override-equivalent methods in the functional interface type.
   457          * The resulting method type is a method type that is override-equivalent
   458          * and return-type substitutable with each method in the original list.
   459          */
   460         private FunctionDescriptor mergeDescriptors(TypeSymbol origin, List<Symbol> methodSyms) {
   461             //pick argument types - simply take the signature that is a
   462             //subsignature of all other signatures in the list (as per JLS 8.4.2)
   463             List<Symbol> mostSpecific = List.nil();
   464             outer: for (Symbol msym1 : methodSyms) {
   465                 Type mt1 = memberType(origin.type, msym1);
   466                 for (Symbol msym2 : methodSyms) {
   467                     Type mt2 = memberType(origin.type, msym2);
   468                     if (!isSubSignature(mt1, mt2)) {
   469                         continue outer;
   470                     }
   471                 }
   472                 mostSpecific = mostSpecific.prepend(msym1);
   473             }
   474             if (mostSpecific.isEmpty()) {
   475                 return null;
   476             }
   479             //pick return types - this is done in two phases: (i) first, the most
   480             //specific return type is chosen using strict subtyping; if this fails,
   481             //a second attempt is made using return type substitutability (see JLS 8.4.5)
   482             boolean phase2 = false;
   483             Symbol bestSoFar = null;
   484             while (bestSoFar == null) {
   485                 outer: for (Symbol msym1 : mostSpecific) {
   486                     Type mt1 = memberType(origin.type, msym1);
   487                     for (Symbol msym2 : methodSyms) {
   488                         Type mt2 = memberType(origin.type, msym2);
   489                         if (phase2 ?
   490                                 !returnTypeSubstitutable(mt1, mt2) :
   491                                 !isSubtypeInternal(mt1.getReturnType(), mt2.getReturnType())) {
   492                             continue outer;
   493                         }
   494                     }
   495                     bestSoFar = msym1;
   496                 }
   497                 if (phase2) {
   498                     break;
   499                 } else {
   500                     phase2 = true;
   501                 }
   502             }
   503             if (bestSoFar == null) return null;
   505             //merge thrown types - form the intersection of all the thrown types in
   506             //all the signatures in the list
   507             boolean toErase = !bestSoFar.type.hasTag(FORALL);
   508             List<Type> thrown = null;
   509             Type mt1 = memberType(origin.type, bestSoFar);
   510             for (Symbol msym2 : methodSyms) {
   511                 Type mt2 = memberType(origin.type, msym2);
   512                 List<Type> thrown_mt2 = mt2.getThrownTypes();
   513                 if (toErase) {
   514                     thrown_mt2 = erasure(thrown_mt2);
   515                 } else {
   516                     /* If bestSoFar is generic then all the methods are generic.
   517                      * The opposite is not true: a non generic method can override
   518                      * a generic method (raw override) so it's safe to cast mt1 and
   519                      * mt2 to ForAll.
   520                      */
   521                     ForAll fa1 = (ForAll)mt1;
   522                     ForAll fa2 = (ForAll)mt2;
   523                     thrown_mt2 = subst(thrown_mt2, fa2.tvars, fa1.tvars);
   524                 }
   525                 thrown = (thrown == null) ?
   526                     thrown_mt2 :
   527                     chk.intersect(thrown_mt2, thrown);
   528             }
   530             final List<Type> thrown1 = thrown;
   531             return new FunctionDescriptor(bestSoFar) {
   532                 @Override
   533                 public Type getType(Type origin) {
   534                     Type mt = memberType(origin, getSymbol());
   535                     return createMethodTypeWithThrown(mt, thrown1);
   536                 }
   537             };
   538         }
   540         boolean isSubtypeInternal(Type s, Type t) {
   541             return (s.isPrimitive() && t.isPrimitive()) ?
   542                     isSameType(t, s) :
   543                     isSubtype(s, t);
   544         }
   546         FunctionDescriptorLookupError failure(String msg, Object... args) {
   547             return failure(diags.fragment(msg, args));
   548         }
   550         FunctionDescriptorLookupError failure(JCDiagnostic diag) {
   551             return functionDescriptorLookupError.setMessage(diag);
   552         }
   553     }
   555     private DescriptorCache descCache = new DescriptorCache();
   557     /**
   558      * Find the method descriptor associated to this class symbol - if the
   559      * symbol 'origin' is not a functional interface, an exception is thrown.
   560      */
   561     public Symbol findDescriptorSymbol(TypeSymbol origin) throws FunctionDescriptorLookupError {
   562         return descCache.get(origin).getSymbol();
   563     }
   565     /**
   566      * Find the type of the method descriptor associated to this class symbol -
   567      * if the symbol 'origin' is not a functional interface, an exception is thrown.
   568      */
   569     public Type findDescriptorType(Type origin) throws FunctionDescriptorLookupError {
   570         return descCache.get(origin.tsym).getType(origin);
   571     }
   573     /**
   574      * Is given type a functional interface?
   575      */
   576     public boolean isFunctionalInterface(TypeSymbol tsym) {
   577         try {
   578             findDescriptorSymbol(tsym);
   579             return true;
   580         } catch (FunctionDescriptorLookupError ex) {
   581             return false;
   582         }
   583     }
   585     public boolean isFunctionalInterface(Type site) {
   586         try {
   587             findDescriptorType(site);
   588             return true;
   589         } catch (FunctionDescriptorLookupError ex) {
   590             return false;
   591         }
   592     }
   594     public Type removeWildcards(Type site) {
   595         Type capturedSite = capture(site);
   596         if (capturedSite != site) {
   597             Type formalInterface = site.tsym.type;
   598             ListBuffer<Type> typeargs = new ListBuffer<>();
   599             List<Type> actualTypeargs = site.getTypeArguments();
   600             List<Type> capturedTypeargs = capturedSite.getTypeArguments();
   601             //simply replace the wildcards with its bound
   602             for (Type t : formalInterface.getTypeArguments()) {
   603                 if (actualTypeargs.head.hasTag(WILDCARD)) {
   604                     WildcardType wt = (WildcardType)actualTypeargs.head.unannotatedType();
   605                     Type bound;
   606                     switch (wt.kind) {
   607                         case EXTENDS:
   608                         case UNBOUND:
   609                             CapturedType capVar = (CapturedType)capturedTypeargs.head.unannotatedType();
   610                             //use declared bound if it doesn't depend on formal type-args
   611                             bound = capVar.bound.containsAny(capturedSite.getTypeArguments()) ?
   612                                     wt.type : capVar.bound;
   613                             break;
   614                         default:
   615                             bound = wt.type;
   616                     }
   617                     typeargs.append(bound);
   618                 } else {
   619                     typeargs.append(actualTypeargs.head);
   620                 }
   621                 actualTypeargs = actualTypeargs.tail;
   622                 capturedTypeargs = capturedTypeargs.tail;
   623             }
   624             return subst(formalInterface, formalInterface.getTypeArguments(), typeargs.toList());
   625         } else {
   626             return site;
   627         }
   628     }
   630     /**
   631      * Create a symbol for a class that implements a given functional interface
   632      * and overrides its functional descriptor. This routine is used for two
   633      * main purposes: (i) checking well-formedness of a functional interface;
   634      * (ii) perform functional interface bridge calculation.
   635      */
   636     public ClassSymbol makeFunctionalInterfaceClass(Env<AttrContext> env, Name name, List<Type> targets, long cflags) {
   637         if (targets.isEmpty() || !isFunctionalInterface(targets.head)) {
   638             return null;
   639         }
   640         Symbol descSym = findDescriptorSymbol(targets.head.tsym);
   641         Type descType = findDescriptorType(targets.head);
   642         ClassSymbol csym = new ClassSymbol(cflags, name, env.enclClass.sym.outermostClass());
   643         csym.completer = null;
   644         csym.members_field = new Scope(csym);
   645         MethodSymbol instDescSym = new MethodSymbol(descSym.flags(), descSym.name, descType, csym);
   646         csym.members_field.enter(instDescSym);
   647         Type.ClassType ctype = new Type.ClassType(Type.noType, List.<Type>nil(), csym);
   648         ctype.supertype_field = syms.objectType;
   649         ctype.interfaces_field = targets;
   650         csym.type = ctype;
   651         csym.sourcefile = ((ClassSymbol)csym.owner).sourcefile;
   652         return csym;
   653     }
   655     /**
   656      * Find the minimal set of methods that are overridden by the functional
   657      * descriptor in 'origin'. All returned methods are assumed to have different
   658      * erased signatures.
   659      */
   660     public List<Symbol> functionalInterfaceBridges(TypeSymbol origin) {
   661         Assert.check(isFunctionalInterface(origin));
   662         Symbol descSym = findDescriptorSymbol(origin);
   663         CompoundScope members = membersClosure(origin.type, false);
   664         ListBuffer<Symbol> overridden = new ListBuffer<>();
   665         outer: for (Symbol m2 : members.getElementsByName(descSym.name, bridgeFilter)) {
   666             if (m2 == descSym) continue;
   667             else if (descSym.overrides(m2, origin, Types.this, false)) {
   668                 for (Symbol m3 : overridden) {
   669                     if (isSameType(m3.erasure(Types.this), m2.erasure(Types.this)) ||
   670                             (m3.overrides(m2, origin, Types.this, false) &&
   671                             (pendingBridges((ClassSymbol)origin, m3.enclClass()) ||
   672                             (((MethodSymbol)m2).binaryImplementation((ClassSymbol)m3.owner, Types.this) != null)))) {
   673                         continue outer;
   674                     }
   675                 }
   676                 overridden.add(m2);
   677             }
   678         }
   679         return overridden.toList();
   680     }
   681     //where
   682         private Filter<Symbol> bridgeFilter = new Filter<Symbol>() {
   683             public boolean accepts(Symbol t) {
   684                 return t.kind == Kinds.MTH &&
   685                         t.name != names.init &&
   686                         t.name != names.clinit &&
   687                         (t.flags() & SYNTHETIC) == 0;
   688             }
   689         };
   690         private boolean pendingBridges(ClassSymbol origin, TypeSymbol sym) {
   691             //a symbol will be completed from a classfile if (a) symbol has
   692             //an associated file object with CLASS kind and (b) the symbol has
   693             //not been entered
   694             if (origin.classfile != null &&
   695                     origin.classfile.getKind() == JavaFileObject.Kind.CLASS &&
   696                     enter.getEnv(origin) == null) {
   697                 return false;
   698             }
   699             if (origin == sym) {
   700                 return true;
   701             }
   702             for (Type t : interfaces(origin.type)) {
   703                 if (pendingBridges((ClassSymbol)t.tsym, sym)) {
   704                     return true;
   705                 }
   706             }
   707             return false;
   708         }
   709     // </editor-fold>
   711    /**
   712     * Scope filter used to skip methods that should be ignored (such as methods
   713     * overridden by j.l.Object) during function interface conversion interface check
   714     */
   715     class DescriptorFilter implements Filter<Symbol> {
   717        TypeSymbol origin;
   719        DescriptorFilter(TypeSymbol origin) {
   720            this.origin = origin;
   721        }
   723        @Override
   724        public boolean accepts(Symbol sym) {
   725            return sym.kind == Kinds.MTH &&
   726                    (sym.flags() & (ABSTRACT | DEFAULT)) == ABSTRACT &&
   727                    !overridesObjectMethod(origin, sym) &&
   728                    (interfaceCandidates(origin.type, (MethodSymbol)sym).head.flags() & DEFAULT) == 0;
   729        }
   730     };
   732     // <editor-fold defaultstate="collapsed" desc="isSubtype">
   733     /**
   734      * Is t an unchecked subtype of s?
   735      */
   736     public boolean isSubtypeUnchecked(Type t, Type s) {
   737         return isSubtypeUnchecked(t, s, noWarnings);
   738     }
   739     /**
   740      * Is t an unchecked subtype of s?
   741      */
   742     public boolean isSubtypeUnchecked(Type t, Type s, Warner warn) {
   743         boolean result = isSubtypeUncheckedInternal(t, s, warn);
   744         if (result) {
   745             checkUnsafeVarargsConversion(t, s, warn);
   746         }
   747         return result;
   748     }
   749     //where
   750         private boolean isSubtypeUncheckedInternal(Type t, Type s, Warner warn) {
   751             if (t.hasTag(ARRAY) && s.hasTag(ARRAY)) {
   752                 t = t.unannotatedType();
   753                 s = s.unannotatedType();
   754                 if (((ArrayType)t).elemtype.isPrimitive()) {
   755                     return isSameType(elemtype(t), elemtype(s));
   756                 } else {
   757                     return isSubtypeUnchecked(elemtype(t), elemtype(s), warn);
   758                 }
   759             } else if (isSubtype(t, s)) {
   760                 return true;
   761             } else if (t.hasTag(TYPEVAR)) {
   762                 return isSubtypeUnchecked(t.getUpperBound(), s, warn);
   763             } else if (!s.isRaw()) {
   764                 Type t2 = asSuper(t, s);
   765                 if (t2 != null && t2.isRaw()) {
   766                     if (isReifiable(s)) {
   767                         warn.silentWarn(LintCategory.UNCHECKED);
   768                     } else {
   769                         warn.warn(LintCategory.UNCHECKED);
   770                     }
   771                     return true;
   772                 }
   773             }
   774             return false;
   775         }
   777         private void checkUnsafeVarargsConversion(Type t, Type s, Warner warn) {
   778             if (!t.hasTag(ARRAY) || isReifiable(t)) {
   779                 return;
   780             }
   781             t = t.unannotatedType();
   782             s = s.unannotatedType();
   783             ArrayType from = (ArrayType)t;
   784             boolean shouldWarn = false;
   785             switch (s.getTag()) {
   786                 case ARRAY:
   787                     ArrayType to = (ArrayType)s;
   788                     shouldWarn = from.isVarargs() &&
   789                             !to.isVarargs() &&
   790                             !isReifiable(from);
   791                     break;
   792                 case CLASS:
   793                     shouldWarn = from.isVarargs();
   794                     break;
   795             }
   796             if (shouldWarn) {
   797                 warn.warn(LintCategory.VARARGS);
   798             }
   799         }
   801     /**
   802      * Is t a subtype of s?<br>
   803      * (not defined for Method and ForAll types)
   804      */
   805     final public boolean isSubtype(Type t, Type s) {
   806         return isSubtype(t, s, true);
   807     }
   808     final public boolean isSubtypeNoCapture(Type t, Type s) {
   809         return isSubtype(t, s, false);
   810     }
   811     public boolean isSubtype(Type t, Type s, boolean capture) {
   812         if (t == s)
   813             return true;
   815         t = t.unannotatedType();
   816         s = s.unannotatedType();
   818         if (t == s)
   819             return true;
   821         if (s.isPartial())
   822             return isSuperType(s, t);
   824         if (s.isCompound()) {
   825             for (Type s2 : interfaces(s).prepend(supertype(s))) {
   826                 if (!isSubtype(t, s2, capture))
   827                     return false;
   828             }
   829             return true;
   830         }
   832         Type lower = lowerBound(s);
   833         if (s != lower)
   834             return isSubtype(capture ? capture(t) : t, lower, false);
   836         return isSubtype.visit(capture ? capture(t) : t, s);
   837     }
   838     // where
   839         private TypeRelation isSubtype = new TypeRelation()
   840         {
   841             @Override
   842             public Boolean visitType(Type t, Type s) {
   843                 switch (t.getTag()) {
   844                  case BYTE:
   845                      return (!s.hasTag(CHAR) && t.getTag().isSubRangeOf(s.getTag()));
   846                  case CHAR:
   847                      return (!s.hasTag(SHORT) && t.getTag().isSubRangeOf(s.getTag()));
   848                  case SHORT: case INT: case LONG:
   849                  case FLOAT: case DOUBLE:
   850                      return t.getTag().isSubRangeOf(s.getTag());
   851                  case BOOLEAN: case VOID:
   852                      return t.hasTag(s.getTag());
   853                  case TYPEVAR:
   854                      return isSubtypeNoCapture(t.getUpperBound(), s);
   855                  case BOT:
   856                      return
   857                          s.hasTag(BOT) || s.hasTag(CLASS) ||
   858                          s.hasTag(ARRAY) || s.hasTag(TYPEVAR);
   859                  case WILDCARD: //we shouldn't be here - avoids crash (see 7034495)
   860                  case NONE:
   861                      return false;
   862                  default:
   863                      throw new AssertionError("isSubtype " + t.getTag());
   864                  }
   865             }
   867             private Set<TypePair> cache = new HashSet<TypePair>();
   869             private boolean containsTypeRecursive(Type t, Type s) {
   870                 TypePair pair = new TypePair(t, s);
   871                 if (cache.add(pair)) {
   872                     try {
   873                         return containsType(t.getTypeArguments(),
   874                                             s.getTypeArguments());
   875                     } finally {
   876                         cache.remove(pair);
   877                     }
   878                 } else {
   879                     return containsType(t.getTypeArguments(),
   880                                         rewriteSupers(s).getTypeArguments());
   881                 }
   882             }
   884             private Type rewriteSupers(Type t) {
   885                 if (!t.isParameterized())
   886                     return t;
   887                 ListBuffer<Type> from = new ListBuffer<>();
   888                 ListBuffer<Type> to = new ListBuffer<>();
   889                 adaptSelf(t, from, to);
   890                 if (from.isEmpty())
   891                     return t;
   892                 ListBuffer<Type> rewrite = new ListBuffer<>();
   893                 boolean changed = false;
   894                 for (Type orig : to.toList()) {
   895                     Type s = rewriteSupers(orig);
   896                     if (s.isSuperBound() && !s.isExtendsBound()) {
   897                         s = new WildcardType(syms.objectType,
   898                                              BoundKind.UNBOUND,
   899                                              syms.boundClass);
   900                         changed = true;
   901                     } else if (s != orig) {
   902                         s = new WildcardType(upperBound(s),
   903                                              BoundKind.EXTENDS,
   904                                              syms.boundClass);
   905                         changed = true;
   906                     }
   907                     rewrite.append(s);
   908                 }
   909                 if (changed)
   910                     return subst(t.tsym.type, from.toList(), rewrite.toList());
   911                 else
   912                     return t;
   913             }
   915             @Override
   916             public Boolean visitClassType(ClassType t, Type s) {
   917                 Type sup = asSuper(t, s);
   918                 return sup != null
   919                     && sup.tsym == s.tsym
   920                     // You're not allowed to write
   921                     //     Vector<Object> vec = new Vector<String>();
   922                     // But with wildcards you can write
   923                     //     Vector<? extends Object> vec = new Vector<String>();
   924                     // which means that subtype checking must be done
   925                     // here instead of same-type checking (via containsType).
   926                     && (!s.isParameterized() || containsTypeRecursive(s, sup))
   927                     && isSubtypeNoCapture(sup.getEnclosingType(),
   928                                           s.getEnclosingType());
   929             }
   931             @Override
   932             public Boolean visitArrayType(ArrayType t, Type s) {
   933                 if (s.hasTag(ARRAY)) {
   934                     if (t.elemtype.isPrimitive())
   935                         return isSameType(t.elemtype, elemtype(s));
   936                     else
   937                         return isSubtypeNoCapture(t.elemtype, elemtype(s));
   938                 }
   940                 if (s.hasTag(CLASS)) {
   941                     Name sname = s.tsym.getQualifiedName();
   942                     return sname == names.java_lang_Object
   943                         || sname == names.java_lang_Cloneable
   944                         || sname == names.java_io_Serializable;
   945                 }
   947                 return false;
   948             }
   950             @Override
   951             public Boolean visitUndetVar(UndetVar t, Type s) {
   952                 //todo: test against origin needed? or replace with substitution?
   953                 if (t == s || t.qtype == s || s.hasTag(ERROR) || s.hasTag(UNKNOWN)) {
   954                     return true;
   955                 } else if (s.hasTag(BOT)) {
   956                     //if 's' is 'null' there's no instantiated type U for which
   957                     //U <: s (but 'null' itself, which is not a valid type)
   958                     return false;
   959                 }
   961                 t.addBound(InferenceBound.UPPER, s, Types.this);
   962                 return true;
   963             }
   965             @Override
   966             public Boolean visitErrorType(ErrorType t, Type s) {
   967                 return true;
   968             }
   969         };
   971     /**
   972      * Is t a subtype of every type in given list `ts'?<br>
   973      * (not defined for Method and ForAll types)<br>
   974      * Allows unchecked conversions.
   975      */
   976     public boolean isSubtypeUnchecked(Type t, List<Type> ts, Warner warn) {
   977         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
   978             if (!isSubtypeUnchecked(t, l.head, warn))
   979                 return false;
   980         return true;
   981     }
   983     /**
   984      * Are corresponding elements of ts subtypes of ss?  If lists are
   985      * of different length, return false.
   986      */
   987     public boolean isSubtypes(List<Type> ts, List<Type> ss) {
   988         while (ts.tail != null && ss.tail != null
   989                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   990                isSubtype(ts.head, ss.head)) {
   991             ts = ts.tail;
   992             ss = ss.tail;
   993         }
   994         return ts.tail == null && ss.tail == null;
   995         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   996     }
   998     /**
   999      * Are corresponding elements of ts subtypes of ss, allowing
  1000      * unchecked conversions?  If lists are of different length,
  1001      * return false.
  1002      **/
  1003     public boolean isSubtypesUnchecked(List<Type> ts, List<Type> ss, Warner warn) {
  1004         while (ts.tail != null && ss.tail != null
  1005                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
  1006                isSubtypeUnchecked(ts.head, ss.head, warn)) {
  1007             ts = ts.tail;
  1008             ss = ss.tail;
  1010         return ts.tail == null && ss.tail == null;
  1011         /*inlined: ts.isEmpty() && ss.isEmpty();*/
  1013     // </editor-fold>
  1015     // <editor-fold defaultstate="collapsed" desc="isSuperType">
  1016     /**
  1017      * Is t a supertype of s?
  1018      */
  1019     public boolean isSuperType(Type t, Type s) {
  1020         switch (t.getTag()) {
  1021         case ERROR:
  1022             return true;
  1023         case UNDETVAR: {
  1024             UndetVar undet = (UndetVar)t;
  1025             if (t == s ||
  1026                 undet.qtype == s ||
  1027                 s.hasTag(ERROR) ||
  1028                 s.hasTag(BOT)) {
  1029                 return true;
  1031             undet.addBound(InferenceBound.LOWER, s, this);
  1032             return true;
  1034         default:
  1035             return isSubtype(s, t);
  1038     // </editor-fold>
  1040     // <editor-fold defaultstate="collapsed" desc="isSameType">
  1041     /**
  1042      * Are corresponding elements of the lists the same type?  If
  1043      * lists are of different length, return false.
  1044      */
  1045     public boolean isSameTypes(List<Type> ts, List<Type> ss) {
  1046         return isSameTypes(ts, ss, false);
  1048     public boolean isSameTypes(List<Type> ts, List<Type> ss, boolean strict) {
  1049         while (ts.tail != null && ss.tail != null
  1050                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
  1051                isSameType(ts.head, ss.head, strict)) {
  1052             ts = ts.tail;
  1053             ss = ss.tail;
  1055         return ts.tail == null && ss.tail == null;
  1056         /*inlined: ts.isEmpty() && ss.isEmpty();*/
  1059     /**
  1060     * A polymorphic signature method (JLS SE 7, 8.4.1) is a method that
  1061     * (i) is declared in the java.lang.invoke.MethodHandle class, (ii) takes
  1062     * a single variable arity parameter (iii) whose declared type is Object[],
  1063     * (iv) has a return type of Object and (v) is native.
  1064     */
  1065    public boolean isSignaturePolymorphic(MethodSymbol msym) {
  1066        List<Type> argtypes = msym.type.getParameterTypes();
  1067        return (msym.flags_field & NATIVE) != 0 &&
  1068                msym.owner == syms.methodHandleType.tsym &&
  1069                argtypes.tail.tail == null &&
  1070                argtypes.head.hasTag(TypeTag.ARRAY) &&
  1071                msym.type.getReturnType().tsym == syms.objectType.tsym &&
  1072                ((ArrayType)argtypes.head).elemtype.tsym == syms.objectType.tsym;
  1075     /**
  1076      * Is t the same type as s?
  1077      */
  1078     public boolean isSameType(Type t, Type s) {
  1079         return isSameType(t, s, false);
  1081     public boolean isSameType(Type t, Type s, boolean strict) {
  1082         return strict ?
  1083                 isSameTypeStrict.visit(t, s) :
  1084                 isSameTypeLoose.visit(t, s);
  1086     public boolean isSameAnnotatedType(Type t, Type s) {
  1087         return isSameAnnotatedType.visit(t, s);
  1089     // where
  1090         abstract class SameTypeVisitor extends TypeRelation {
  1092             public Boolean visitType(Type t, Type s) {
  1093                 if (t == s)
  1094                     return true;
  1096                 if (s.isPartial())
  1097                     return visit(s, t);
  1099                 switch (t.getTag()) {
  1100                 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
  1101                 case DOUBLE: case BOOLEAN: case VOID: case BOT: case NONE:
  1102                     return t.hasTag(s.getTag());
  1103                 case TYPEVAR: {
  1104                     if (s.hasTag(TYPEVAR)) {
  1105                         //type-substitution does not preserve type-var types
  1106                         //check that type var symbols and bounds are indeed the same
  1107                         return sameTypeVars((TypeVar)t.unannotatedType(), (TypeVar)s.unannotatedType());
  1109                     else {
  1110                         //special case for s == ? super X, where upper(s) = u
  1111                         //check that u == t, where u has been set by Type.withTypeVar
  1112                         return s.isSuperBound() &&
  1113                                 !s.isExtendsBound() &&
  1114                                 visit(t, upperBound(s));
  1117                 default:
  1118                     throw new AssertionError("isSameType " + t.getTag());
  1122             abstract boolean sameTypeVars(TypeVar tv1, TypeVar tv2);
  1124             @Override
  1125             public Boolean visitWildcardType(WildcardType t, Type s) {
  1126                 if (s.isPartial())
  1127                     return visit(s, t);
  1128                 else
  1129                     return false;
  1132             @Override
  1133             public Boolean visitClassType(ClassType t, Type s) {
  1134                 if (t == s)
  1135                     return true;
  1137                 if (s.isPartial())
  1138                     return visit(s, t);
  1140                 if (s.isSuperBound() && !s.isExtendsBound())
  1141                     return visit(t, upperBound(s)) && visit(t, lowerBound(s));
  1143                 if (t.isCompound() && s.isCompound()) {
  1144                     if (!visit(supertype(t), supertype(s)))
  1145                         return false;
  1147                     HashSet<UniqueType> set = new HashSet<UniqueType>();
  1148                     for (Type x : interfaces(t))
  1149                         set.add(new UniqueType(x.unannotatedType(), Types.this));
  1150                     for (Type x : interfaces(s)) {
  1151                         if (!set.remove(new UniqueType(x.unannotatedType(), Types.this)))
  1152                             return false;
  1154                     return (set.isEmpty());
  1156                 return t.tsym == s.tsym
  1157                     && visit(t.getEnclosingType(), s.getEnclosingType())
  1158                     && containsTypes(t.getTypeArguments(), s.getTypeArguments());
  1161             abstract protected boolean containsTypes(List<Type> ts1, List<Type> ts2);
  1163             @Override
  1164             public Boolean visitArrayType(ArrayType t, Type s) {
  1165                 if (t == s)
  1166                     return true;
  1168                 if (s.isPartial())
  1169                     return visit(s, t);
  1171                 return s.hasTag(ARRAY)
  1172                     && containsTypeEquivalent(t.elemtype, elemtype(s));
  1175             @Override
  1176             public Boolean visitMethodType(MethodType t, Type s) {
  1177                 // isSameType for methods does not take thrown
  1178                 // exceptions into account!
  1179                 return hasSameArgs(t, s) && visit(t.getReturnType(), s.getReturnType());
  1182             @Override
  1183             public Boolean visitPackageType(PackageType t, Type s) {
  1184                 return t == s;
  1187             @Override
  1188             public Boolean visitForAll(ForAll t, Type s) {
  1189                 if (!s.hasTag(FORALL)) {
  1190                     return false;
  1193                 ForAll forAll = (ForAll)s;
  1194                 return hasSameBounds(t, forAll)
  1195                     && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
  1198             @Override
  1199             public Boolean visitUndetVar(UndetVar t, Type s) {
  1200                 if (s.hasTag(WILDCARD)) {
  1201                     // FIXME, this might be leftovers from before capture conversion
  1202                     return false;
  1205                 if (t == s || t.qtype == s || s.hasTag(ERROR) || s.hasTag(UNKNOWN)) {
  1206                     return true;
  1209                 t.addBound(InferenceBound.EQ, s, Types.this);
  1211                 return true;
  1214             @Override
  1215             public Boolean visitErrorType(ErrorType t, Type s) {
  1216                 return true;
  1220         /**
  1221          * Standard type-equality relation - type variables are considered
  1222          * equals if they share the same type symbol.
  1223          */
  1224         TypeRelation isSameTypeLoose = new LooseSameTypeVisitor();
  1226         private class LooseSameTypeVisitor extends SameTypeVisitor {
  1227             @Override
  1228             boolean sameTypeVars(TypeVar tv1, TypeVar tv2) {
  1229                 return tv1.tsym == tv2.tsym && visit(tv1.getUpperBound(), tv2.getUpperBound());
  1231             @Override
  1232             protected boolean containsTypes(List<Type> ts1, List<Type> ts2) {
  1233                 return containsTypeEquivalent(ts1, ts2);
  1235         };
  1237         /**
  1238          * Strict type-equality relation - type variables are considered
  1239          * equals if they share the same object identity.
  1240          */
  1241         TypeRelation isSameTypeStrict = new SameTypeVisitor() {
  1242             @Override
  1243             boolean sameTypeVars(TypeVar tv1, TypeVar tv2) {
  1244                 return tv1 == tv2;
  1246             @Override
  1247             protected boolean containsTypes(List<Type> ts1, List<Type> ts2) {
  1248                 return isSameTypes(ts1, ts2, true);
  1251             @Override
  1252             public Boolean visitWildcardType(WildcardType t, Type s) {
  1253                 if (!s.hasTag(WILDCARD)) {
  1254                     return false;
  1255                 } else {
  1256                     WildcardType t2 = (WildcardType)s.unannotatedType();
  1257                     return t.kind == t2.kind &&
  1258                             isSameType(t.type, t2.type, true);
  1261         };
  1263         /**
  1264          * A version of LooseSameTypeVisitor that takes AnnotatedTypes
  1265          * into account.
  1266          */
  1267         TypeRelation isSameAnnotatedType = new LooseSameTypeVisitor() {
  1268             @Override
  1269             public Boolean visitAnnotatedType(AnnotatedType t, Type s) {
  1270                 if (!s.isAnnotated())
  1271                     return false;
  1272                 if (!t.getAnnotationMirrors().containsAll(s.getAnnotationMirrors()))
  1273                     return false;
  1274                 if (!s.getAnnotationMirrors().containsAll(t.getAnnotationMirrors()))
  1275                     return false;
  1276                 return visit(t.unannotatedType(), s);
  1278         };
  1279     // </editor-fold>
  1281     // <editor-fold defaultstate="collapsed" desc="Contains Type">
  1282     public boolean containedBy(Type t, Type s) {
  1283         switch (t.getTag()) {
  1284         case UNDETVAR:
  1285             if (s.hasTag(WILDCARD)) {
  1286                 UndetVar undetvar = (UndetVar)t;
  1287                 WildcardType wt = (WildcardType)s.unannotatedType();
  1288                 switch(wt.kind) {
  1289                     case UNBOUND: //similar to ? extends Object
  1290                     case EXTENDS: {
  1291                         Type bound = upperBound(s);
  1292                         undetvar.addBound(InferenceBound.UPPER, bound, this);
  1293                         break;
  1295                     case SUPER: {
  1296                         Type bound = lowerBound(s);
  1297                         undetvar.addBound(InferenceBound.LOWER, bound, this);
  1298                         break;
  1301                 return true;
  1302             } else {
  1303                 return isSameType(t, s);
  1305         case ERROR:
  1306             return true;
  1307         default:
  1308             return containsType(s, t);
  1312     boolean containsType(List<Type> ts, List<Type> ss) {
  1313         while (ts.nonEmpty() && ss.nonEmpty()
  1314                && containsType(ts.head, ss.head)) {
  1315             ts = ts.tail;
  1316             ss = ss.tail;
  1318         return ts.isEmpty() && ss.isEmpty();
  1321     /**
  1322      * Check if t contains s.
  1324      * <p>T contains S if:
  1326      * <p>{@code L(T) <: L(S) && U(S) <: U(T)}
  1328      * <p>This relation is only used by ClassType.isSubtype(), that
  1329      * is,
  1331      * <p>{@code C<S> <: C<T> if T contains S.}
  1333      * <p>Because of F-bounds, this relation can lead to infinite
  1334      * recursion.  Thus we must somehow break that recursion.  Notice
  1335      * that containsType() is only called from ClassType.isSubtype().
  1336      * Since the arguments have already been checked against their
  1337      * bounds, we know:
  1339      * <p>{@code U(S) <: U(T) if T is "super" bound (U(T) *is* the bound)}
  1341      * <p>{@code L(T) <: L(S) if T is "extends" bound (L(T) is bottom)}
  1343      * @param t a type
  1344      * @param s a type
  1345      */
  1346     public boolean containsType(Type t, Type s) {
  1347         return containsType.visit(t, s);
  1349     // where
  1350         private TypeRelation containsType = new TypeRelation() {
  1352             private Type U(Type t) {
  1353                 while (t.hasTag(WILDCARD)) {
  1354                     WildcardType w = (WildcardType)t.unannotatedType();
  1355                     if (w.isSuperBound())
  1356                         return w.bound == null ? syms.objectType : w.bound.bound;
  1357                     else
  1358                         t = w.type;
  1360                 return t;
  1363             private Type L(Type t) {
  1364                 while (t.hasTag(WILDCARD)) {
  1365                     WildcardType w = (WildcardType)t.unannotatedType();
  1366                     if (w.isExtendsBound())
  1367                         return syms.botType;
  1368                     else
  1369                         t = w.type;
  1371                 return t;
  1374             public Boolean visitType(Type t, Type s) {
  1375                 if (s.isPartial())
  1376                     return containedBy(s, t);
  1377                 else
  1378                     return isSameType(t, s);
  1381 //            void debugContainsType(WildcardType t, Type s) {
  1382 //                System.err.println();
  1383 //                System.err.format(" does %s contain %s?%n", t, s);
  1384 //                System.err.format(" %s U(%s) <: U(%s) %s = %s%n",
  1385 //                                  upperBound(s), s, t, U(t),
  1386 //                                  t.isSuperBound()
  1387 //                                  || isSubtypeNoCapture(upperBound(s), U(t)));
  1388 //                System.err.format(" %s L(%s) <: L(%s) %s = %s%n",
  1389 //                                  L(t), t, s, lowerBound(s),
  1390 //                                  t.isExtendsBound()
  1391 //                                  || isSubtypeNoCapture(L(t), lowerBound(s)));
  1392 //                System.err.println();
  1393 //            }
  1395             @Override
  1396             public Boolean visitWildcardType(WildcardType t, Type s) {
  1397                 if (s.isPartial())
  1398                     return containedBy(s, t);
  1399                 else {
  1400 //                    debugContainsType(t, s);
  1401                     return isSameWildcard(t, s)
  1402                         || isCaptureOf(s, t)
  1403                         || ((t.isExtendsBound() || isSubtypeNoCapture(L(t), lowerBound(s))) &&
  1404                             (t.isSuperBound() || isSubtypeNoCapture(upperBound(s), U(t))));
  1408             @Override
  1409             public Boolean visitUndetVar(UndetVar t, Type s) {
  1410                 if (!s.hasTag(WILDCARD)) {
  1411                     return isSameType(t, s);
  1412                 } else {
  1413                     return false;
  1417             @Override
  1418             public Boolean visitErrorType(ErrorType t, Type s) {
  1419                 return true;
  1421         };
  1423     public boolean isCaptureOf(Type s, WildcardType t) {
  1424         if (!s.hasTag(TYPEVAR) || !((TypeVar)s.unannotatedType()).isCaptured())
  1425             return false;
  1426         return isSameWildcard(t, ((CapturedType)s.unannotatedType()).wildcard);
  1429     public boolean isSameWildcard(WildcardType t, Type s) {
  1430         if (!s.hasTag(WILDCARD))
  1431             return false;
  1432         WildcardType w = (WildcardType)s.unannotatedType();
  1433         return w.kind == t.kind && w.type == t.type;
  1436     public boolean containsTypeEquivalent(List<Type> ts, List<Type> ss) {
  1437         while (ts.nonEmpty() && ss.nonEmpty()
  1438                && containsTypeEquivalent(ts.head, ss.head)) {
  1439             ts = ts.tail;
  1440             ss = ss.tail;
  1442         return ts.isEmpty() && ss.isEmpty();
  1444     // </editor-fold>
  1446     /**
  1447      * Can t and s be compared for equality?  Any primitive ==
  1448      * primitive or primitive == object comparisons here are an error.
  1449      * Unboxing and correct primitive == primitive comparisons are
  1450      * already dealt with in Attr.visitBinary.
  1452      */
  1453     public boolean isEqualityComparable(Type s, Type t, Warner warn) {
  1454         if (t.isNumeric() && s.isNumeric())
  1455             return true;
  1457         boolean tPrimitive = t.isPrimitive();
  1458         boolean sPrimitive = s.isPrimitive();
  1459         if (!tPrimitive && !sPrimitive) {
  1460             return isCastable(s, t, warn) || isCastable(t, s, warn);
  1461         } else {
  1462             return false;
  1466     // <editor-fold defaultstate="collapsed" desc="isCastable">
  1467     public boolean isCastable(Type t, Type s) {
  1468         return isCastable(t, s, noWarnings);
  1471     /**
  1472      * Is t is castable to s?<br>
  1473      * s is assumed to be an erased type.<br>
  1474      * (not defined for Method and ForAll types).
  1475      */
  1476     public boolean isCastable(Type t, Type s, Warner warn) {
  1477         if (t == s)
  1478             return true;
  1480         if (t.isPrimitive() != s.isPrimitive())
  1481             return allowBoxing && (
  1482                     isConvertible(t, s, warn)
  1483                     || (allowObjectToPrimitiveCast &&
  1484                         s.isPrimitive() &&
  1485                         isSubtype(boxedClass(s).type, t)));
  1486         if (warn != warnStack.head) {
  1487             try {
  1488                 warnStack = warnStack.prepend(warn);
  1489                 checkUnsafeVarargsConversion(t, s, warn);
  1490                 return isCastable.visit(t,s);
  1491             } finally {
  1492                 warnStack = warnStack.tail;
  1494         } else {
  1495             return isCastable.visit(t,s);
  1498     // where
  1499         private TypeRelation isCastable = new TypeRelation() {
  1501             public Boolean visitType(Type t, Type s) {
  1502                 if (s.hasTag(ERROR))
  1503                     return true;
  1505                 switch (t.getTag()) {
  1506                 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
  1507                 case DOUBLE:
  1508                     return s.isNumeric();
  1509                 case BOOLEAN:
  1510                     return s.hasTag(BOOLEAN);
  1511                 case VOID:
  1512                     return false;
  1513                 case BOT:
  1514                     return isSubtype(t, s);
  1515                 default:
  1516                     throw new AssertionError();
  1520             @Override
  1521             public Boolean visitWildcardType(WildcardType t, Type s) {
  1522                 return isCastable(upperBound(t), s, warnStack.head);
  1525             @Override
  1526             public Boolean visitClassType(ClassType t, Type s) {
  1527                 if (s.hasTag(ERROR) || s.hasTag(BOT))
  1528                     return true;
  1530                 if (s.hasTag(TYPEVAR)) {
  1531                     if (isCastable(t, s.getUpperBound(), noWarnings)) {
  1532                         warnStack.head.warn(LintCategory.UNCHECKED);
  1533                         return true;
  1534                     } else {
  1535                         return false;
  1539                 if (t.isCompound() || s.isCompound()) {
  1540                     return !t.isCompound() ?
  1541                             visitIntersectionType((IntersectionClassType)s.unannotatedType(), t, true) :
  1542                             visitIntersectionType((IntersectionClassType)t.unannotatedType(), s, false);
  1545                 if (s.hasTag(CLASS) || s.hasTag(ARRAY)) {
  1546                     boolean upcast;
  1547                     if ((upcast = isSubtype(erasure(t), erasure(s)))
  1548                         || isSubtype(erasure(s), erasure(t))) {
  1549                         if (!upcast && s.hasTag(ARRAY)) {
  1550                             if (!isReifiable(s))
  1551                                 warnStack.head.warn(LintCategory.UNCHECKED);
  1552                             return true;
  1553                         } else if (s.isRaw()) {
  1554                             return true;
  1555                         } else if (t.isRaw()) {
  1556                             if (!isUnbounded(s))
  1557                                 warnStack.head.warn(LintCategory.UNCHECKED);
  1558                             return true;
  1560                         // Assume |a| <: |b|
  1561                         final Type a = upcast ? t : s;
  1562                         final Type b = upcast ? s : t;
  1563                         final boolean HIGH = true;
  1564                         final boolean LOW = false;
  1565                         final boolean DONT_REWRITE_TYPEVARS = false;
  1566                         Type aHigh = rewriteQuantifiers(a, HIGH, DONT_REWRITE_TYPEVARS);
  1567                         Type aLow  = rewriteQuantifiers(a, LOW,  DONT_REWRITE_TYPEVARS);
  1568                         Type bHigh = rewriteQuantifiers(b, HIGH, DONT_REWRITE_TYPEVARS);
  1569                         Type bLow  = rewriteQuantifiers(b, LOW,  DONT_REWRITE_TYPEVARS);
  1570                         Type lowSub = asSub(bLow, aLow.tsym);
  1571                         Type highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
  1572                         if (highSub == null) {
  1573                             final boolean REWRITE_TYPEVARS = true;
  1574                             aHigh = rewriteQuantifiers(a, HIGH, REWRITE_TYPEVARS);
  1575                             aLow  = rewriteQuantifiers(a, LOW,  REWRITE_TYPEVARS);
  1576                             bHigh = rewriteQuantifiers(b, HIGH, REWRITE_TYPEVARS);
  1577                             bLow  = rewriteQuantifiers(b, LOW,  REWRITE_TYPEVARS);
  1578                             lowSub = asSub(bLow, aLow.tsym);
  1579                             highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
  1581                         if (highSub != null) {
  1582                             if (!(a.tsym == highSub.tsym && a.tsym == lowSub.tsym)) {
  1583                                 Assert.error(a.tsym + " != " + highSub.tsym + " != " + lowSub.tsym);
  1585                             if (!disjointTypes(aHigh.allparams(), highSub.allparams())
  1586                                 && !disjointTypes(aHigh.allparams(), lowSub.allparams())
  1587                                 && !disjointTypes(aLow.allparams(), highSub.allparams())
  1588                                 && !disjointTypes(aLow.allparams(), lowSub.allparams())) {
  1589                                 if (upcast ? giveWarning(a, b) :
  1590                                     giveWarning(b, a))
  1591                                     warnStack.head.warn(LintCategory.UNCHECKED);
  1592                                 return true;
  1595                         if (isReifiable(s))
  1596                             return isSubtypeUnchecked(a, b);
  1597                         else
  1598                             return isSubtypeUnchecked(a, b, warnStack.head);
  1601                     // Sidecast
  1602                     if (s.hasTag(CLASS)) {
  1603                         if ((s.tsym.flags() & INTERFACE) != 0) {
  1604                             return ((t.tsym.flags() & FINAL) == 0)
  1605                                 ? sideCast(t, s, warnStack.head)
  1606                                 : sideCastFinal(t, s, warnStack.head);
  1607                         } else if ((t.tsym.flags() & INTERFACE) != 0) {
  1608                             return ((s.tsym.flags() & FINAL) == 0)
  1609                                 ? sideCast(t, s, warnStack.head)
  1610                                 : sideCastFinal(t, s, warnStack.head);
  1611                         } else {
  1612                             // unrelated class types
  1613                             return false;
  1617                 return false;
  1620             boolean visitIntersectionType(IntersectionClassType ict, Type s, boolean reverse) {
  1621                 Warner warn = noWarnings;
  1622                 for (Type c : ict.getComponents()) {
  1623                     warn.clear();
  1624                     if (reverse ? !isCastable(s, c, warn) : !isCastable(c, s, warn))
  1625                         return false;
  1627                 if (warn.hasLint(LintCategory.UNCHECKED))
  1628                     warnStack.head.warn(LintCategory.UNCHECKED);
  1629                 return true;
  1632             @Override
  1633             public Boolean visitArrayType(ArrayType t, Type s) {
  1634                 switch (s.getTag()) {
  1635                 case ERROR:
  1636                 case BOT:
  1637                     return true;
  1638                 case TYPEVAR:
  1639                     if (isCastable(s, t, noWarnings)) {
  1640                         warnStack.head.warn(LintCategory.UNCHECKED);
  1641                         return true;
  1642                     } else {
  1643                         return false;
  1645                 case CLASS:
  1646                     return isSubtype(t, s);
  1647                 case ARRAY:
  1648                     if (elemtype(t).isPrimitive() || elemtype(s).isPrimitive()) {
  1649                         return elemtype(t).hasTag(elemtype(s).getTag());
  1650                     } else {
  1651                         return visit(elemtype(t), elemtype(s));
  1653                 default:
  1654                     return false;
  1658             @Override
  1659             public Boolean visitTypeVar(TypeVar t, Type s) {
  1660                 switch (s.getTag()) {
  1661                 case ERROR:
  1662                 case BOT:
  1663                     return true;
  1664                 case TYPEVAR:
  1665                     if (isSubtype(t, s)) {
  1666                         return true;
  1667                     } else if (isCastable(t.bound, s, noWarnings)) {
  1668                         warnStack.head.warn(LintCategory.UNCHECKED);
  1669                         return true;
  1670                     } else {
  1671                         return false;
  1673                 default:
  1674                     return isCastable(t.bound, s, warnStack.head);
  1678             @Override
  1679             public Boolean visitErrorType(ErrorType t, Type s) {
  1680                 return true;
  1682         };
  1683     // </editor-fold>
  1685     // <editor-fold defaultstate="collapsed" desc="disjointTypes">
  1686     public boolean disjointTypes(List<Type> ts, List<Type> ss) {
  1687         while (ts.tail != null && ss.tail != null) {
  1688             if (disjointType(ts.head, ss.head)) return true;
  1689             ts = ts.tail;
  1690             ss = ss.tail;
  1692         return false;
  1695     /**
  1696      * Two types or wildcards are considered disjoint if it can be
  1697      * proven that no type can be contained in both. It is
  1698      * conservative in that it is allowed to say that two types are
  1699      * not disjoint, even though they actually are.
  1701      * The type {@code C<X>} is castable to {@code C<Y>} exactly if
  1702      * {@code X} and {@code Y} are not disjoint.
  1703      */
  1704     public boolean disjointType(Type t, Type s) {
  1705         return disjointType.visit(t, s);
  1707     // where
  1708         private TypeRelation disjointType = new TypeRelation() {
  1710             private Set<TypePair> cache = new HashSet<TypePair>();
  1712             @Override
  1713             public Boolean visitType(Type t, Type s) {
  1714                 if (s.hasTag(WILDCARD))
  1715                     return visit(s, t);
  1716                 else
  1717                     return notSoftSubtypeRecursive(t, s) || notSoftSubtypeRecursive(s, t);
  1720             private boolean isCastableRecursive(Type t, Type s) {
  1721                 TypePair pair = new TypePair(t, s);
  1722                 if (cache.add(pair)) {
  1723                     try {
  1724                         return Types.this.isCastable(t, s);
  1725                     } finally {
  1726                         cache.remove(pair);
  1728                 } else {
  1729                     return true;
  1733             private boolean notSoftSubtypeRecursive(Type t, Type s) {
  1734                 TypePair pair = new TypePair(t, s);
  1735                 if (cache.add(pair)) {
  1736                     try {
  1737                         return Types.this.notSoftSubtype(t, s);
  1738                     } finally {
  1739                         cache.remove(pair);
  1741                 } else {
  1742                     return false;
  1746             @Override
  1747             public Boolean visitWildcardType(WildcardType t, Type s) {
  1748                 if (t.isUnbound())
  1749                     return false;
  1751                 if (!s.hasTag(WILDCARD)) {
  1752                     if (t.isExtendsBound())
  1753                         return notSoftSubtypeRecursive(s, t.type);
  1754                     else
  1755                         return notSoftSubtypeRecursive(t.type, s);
  1758                 if (s.isUnbound())
  1759                     return false;
  1761                 if (t.isExtendsBound()) {
  1762                     if (s.isExtendsBound())
  1763                         return !isCastableRecursive(t.type, upperBound(s));
  1764                     else if (s.isSuperBound())
  1765                         return notSoftSubtypeRecursive(lowerBound(s), t.type);
  1766                 } else if (t.isSuperBound()) {
  1767                     if (s.isExtendsBound())
  1768                         return notSoftSubtypeRecursive(t.type, upperBound(s));
  1770                 return false;
  1772         };
  1773     // </editor-fold>
  1775     // <editor-fold defaultstate="collapsed" desc="lowerBoundArgtypes">
  1776     /**
  1777      * Returns the lower bounds of the formals of a method.
  1778      */
  1779     public List<Type> lowerBoundArgtypes(Type t) {
  1780         return lowerBounds(t.getParameterTypes());
  1782     public List<Type> lowerBounds(List<Type> ts) {
  1783         return map(ts, lowerBoundMapping);
  1785     private final Mapping lowerBoundMapping = new Mapping("lowerBound") {
  1786             public Type apply(Type t) {
  1787                 return lowerBound(t);
  1789         };
  1790     // </editor-fold>
  1792     // <editor-fold defaultstate="collapsed" desc="notSoftSubtype">
  1793     /**
  1794      * This relation answers the question: is impossible that
  1795      * something of type `t' can be a subtype of `s'? This is
  1796      * different from the question "is `t' not a subtype of `s'?"
  1797      * when type variables are involved: Integer is not a subtype of T
  1798      * where {@code <T extends Number>} but it is not true that Integer cannot
  1799      * possibly be a subtype of T.
  1800      */
  1801     public boolean notSoftSubtype(Type t, Type s) {
  1802         if (t == s) return false;
  1803         if (t.hasTag(TYPEVAR)) {
  1804             TypeVar tv = (TypeVar) t;
  1805             return !isCastable(tv.bound,
  1806                                relaxBound(s),
  1807                                noWarnings);
  1809         if (!s.hasTag(WILDCARD))
  1810             s = upperBound(s);
  1812         return !isSubtype(t, relaxBound(s));
  1815     private Type relaxBound(Type t) {
  1816         if (t.hasTag(TYPEVAR)) {
  1817             while (t.hasTag(TYPEVAR))
  1818                 t = t.getUpperBound();
  1819             t = rewriteQuantifiers(t, true, true);
  1821         return t;
  1823     // </editor-fold>
  1825     // <editor-fold defaultstate="collapsed" desc="isReifiable">
  1826     public boolean isReifiable(Type t) {
  1827         return isReifiable.visit(t);
  1829     // where
  1830         private UnaryVisitor<Boolean> isReifiable = new UnaryVisitor<Boolean>() {
  1832             public Boolean visitType(Type t, Void ignored) {
  1833                 return true;
  1836             @Override
  1837             public Boolean visitClassType(ClassType t, Void ignored) {
  1838                 if (t.isCompound())
  1839                     return false;
  1840                 else {
  1841                     if (!t.isParameterized())
  1842                         return true;
  1844                     for (Type param : t.allparams()) {
  1845                         if (!param.isUnbound())
  1846                             return false;
  1848                     return true;
  1852             @Override
  1853             public Boolean visitArrayType(ArrayType t, Void ignored) {
  1854                 return visit(t.elemtype);
  1857             @Override
  1858             public Boolean visitTypeVar(TypeVar t, Void ignored) {
  1859                 return false;
  1861         };
  1862     // </editor-fold>
  1864     // <editor-fold defaultstate="collapsed" desc="Array Utils">
  1865     public boolean isArray(Type t) {
  1866         while (t.hasTag(WILDCARD))
  1867             t = upperBound(t);
  1868         return t.hasTag(ARRAY);
  1871     /**
  1872      * The element type of an array.
  1873      */
  1874     public Type elemtype(Type t) {
  1875         switch (t.getTag()) {
  1876         case WILDCARD:
  1877             return elemtype(upperBound(t));
  1878         case ARRAY:
  1879             t = t.unannotatedType();
  1880             return ((ArrayType)t).elemtype;
  1881         case FORALL:
  1882             return elemtype(((ForAll)t).qtype);
  1883         case ERROR:
  1884             return t;
  1885         default:
  1886             return null;
  1890     public Type elemtypeOrType(Type t) {
  1891         Type elemtype = elemtype(t);
  1892         return elemtype != null ?
  1893             elemtype :
  1894             t;
  1897     /**
  1898      * Mapping to take element type of an arraytype
  1899      */
  1900     private Mapping elemTypeFun = new Mapping ("elemTypeFun") {
  1901         public Type apply(Type t) { return elemtype(t); }
  1902     };
  1904     /**
  1905      * The number of dimensions of an array type.
  1906      */
  1907     public int dimensions(Type t) {
  1908         int result = 0;
  1909         while (t.hasTag(ARRAY)) {
  1910             result++;
  1911             t = elemtype(t);
  1913         return result;
  1916     /**
  1917      * Returns an ArrayType with the component type t
  1919      * @param t The component type of the ArrayType
  1920      * @return the ArrayType for the given component
  1921      */
  1922     public ArrayType makeArrayType(Type t) {
  1923         if (t.hasTag(VOID) || t.hasTag(PACKAGE)) {
  1924             Assert.error("Type t must not be a VOID or PACKAGE type, " + t.toString());
  1926         return new ArrayType(t, syms.arrayClass);
  1928     // </editor-fold>
  1930     // <editor-fold defaultstate="collapsed" desc="asSuper">
  1931     /**
  1932      * Return the (most specific) base type of t that starts with the
  1933      * given symbol.  If none exists, return null.
  1935      * @param t a type
  1936      * @param sym a symbol
  1937      */
  1938     public Type asSuper(Type t, Symbol s) {
  1939         return asSuper(t, s.type);
  1942     public Type asSuper(Type t, Type s) {
  1943         return asSuper.visit(t, s);
  1945     // where
  1946         private SimpleVisitor<Type,Type> asSuper = new SimpleVisitor<Type,Type>() {
  1948             public Type visitType(Type t, Type s) {
  1949                 return null;
  1952             @Override
  1953             public Type visitClassType(ClassType t, Type s) {
  1954                 if (t.tsym == s.tsym)
  1955                     return t;
  1957                 Type st = supertype(t);
  1959                 switch(st.getTag()) {
  1960                 default: break;
  1961                 case CLASS:
  1962                 case ARRAY:
  1963                 case TYPEVAR:
  1964                 case ERROR: {
  1965                     Type x = asSuper(st, s);
  1966                     if (x != null)
  1967                         return x;
  1968                 } break;
  1971                 if ((s.tsym.flags() & INTERFACE) != 0) {
  1972                     for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
  1973                         Type x = asSuper(l.head, s);
  1974                         if (x != null)
  1975                             return x;
  1978                 return null;
  1981             @Override
  1982             public Type visitArrayType(ArrayType t, Type s) {
  1983                 return isSubtype(t, s) ? s : null;
  1986             @Override
  1987             public Type visitTypeVar(TypeVar t, Type s) {
  1988                 if (t.tsym == s.tsym)
  1989                     return t;
  1990                 else
  1991                     return asSuper(t.bound, s);
  1994             @Override
  1995             public Type visitErrorType(ErrorType t, Type s) { 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));
  3577                 for (Type t : ts) {
  3578                     lci = intersect(lci, List.of(asSuper(t, erasedSupertype)));
  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();
  3884     public Type capture(Type t) {
  3885         if (!t.hasTag(CLASS))
  3886             return t;
  3887         if (t.getEnclosingType() != Type.noType) {
  3888             Type capturedEncl = capture(t.getEnclosingType());
  3889             if (capturedEncl != t.getEnclosingType()) {
  3890                 Type type1 = memberType(capturedEncl, t.tsym);
  3891                 t = subst(type1, t.tsym.type.getTypeArguments(), t.getTypeArguments());
  3894         t = t.unannotatedType();
  3895         ClassType cls = (ClassType)t;
  3896         if (cls.isRaw() || !cls.isParameterized())
  3897             return cls;
  3899         ClassType G = (ClassType)cls.asElement().asType();
  3900         List<Type> A = G.getTypeArguments();
  3901         List<Type> T = cls.getTypeArguments();
  3902         List<Type> S = freshTypeVariables(T);
  3904         List<Type> currentA = A;
  3905         List<Type> currentT = T;
  3906         List<Type> currentS = S;
  3907         boolean captured = false;
  3908         while (!currentA.isEmpty() &&
  3909                !currentT.isEmpty() &&
  3910                !currentS.isEmpty()) {
  3911             if (currentS.head != currentT.head) {
  3912                 captured = true;
  3913                 WildcardType Ti = (WildcardType)currentT.head.unannotatedType();
  3914                 Type Ui = currentA.head.getUpperBound();
  3915                 CapturedType Si = (CapturedType)currentS.head.unannotatedType();
  3916                 if (Ui == null)
  3917                     Ui = syms.objectType;
  3918                 switch (Ti.kind) {
  3919                 case UNBOUND:
  3920                     Si.bound = subst(Ui, A, S);
  3921                     Si.lower = syms.botType;
  3922                     break;
  3923                 case EXTENDS:
  3924                     Si.bound = glb(Ti.getExtendsBound(), subst(Ui, A, S));
  3925                     Si.lower = syms.botType;
  3926                     break;
  3927                 case SUPER:
  3928                     Si.bound = subst(Ui, A, S);
  3929                     Si.lower = Ti.getSuperBound();
  3930                     break;
  3932                 if (Si.bound == Si.lower)
  3933                     currentS.head = Si.bound;
  3935             currentA = currentA.tail;
  3936             currentT = currentT.tail;
  3937             currentS = currentS.tail;
  3939         if (!currentA.isEmpty() || !currentT.isEmpty() || !currentS.isEmpty())
  3940             return erasure(t); // some "rare" type involved
  3942         if (captured)
  3943             return new ClassType(cls.getEnclosingType(), S, cls.tsym);
  3944         else
  3945             return t;
  3947     // where
  3948         public List<Type> freshTypeVariables(List<Type> types) {
  3949             ListBuffer<Type> result = new ListBuffer<>();
  3950             for (Type t : types) {
  3951                 if (t.hasTag(WILDCARD)) {
  3952                     t = t.unannotatedType();
  3953                     Type bound = ((WildcardType)t).getExtendsBound();
  3954                     if (bound == null)
  3955                         bound = syms.objectType;
  3956                     result.append(new CapturedType(capturedName,
  3957                                                    syms.noSymbol,
  3958                                                    bound,
  3959                                                    syms.botType,
  3960                                                    (WildcardType)t));
  3961                 } else {
  3962                     result.append(t);
  3965             return result.toList();
  3967     // </editor-fold>
  3969     // <editor-fold defaultstate="collapsed" desc="Internal utility methods">
  3970     private List<Type> upperBounds(List<Type> ss) {
  3971         if (ss.isEmpty()) return ss;
  3972         Type head = upperBound(ss.head);
  3973         List<Type> tail = upperBounds(ss.tail);
  3974         if (head != ss.head || tail != ss.tail)
  3975             return tail.prepend(head);
  3976         else
  3977             return ss;
  3980     private boolean sideCast(Type from, Type to, Warner warn) {
  3981         // We are casting from type $from$ to type $to$, which are
  3982         // non-final unrelated types.  This method
  3983         // tries to reject a cast by transferring type parameters
  3984         // from $to$ to $from$ by common superinterfaces.
  3985         boolean reverse = false;
  3986         Type target = to;
  3987         if ((to.tsym.flags() & INTERFACE) == 0) {
  3988             Assert.check((from.tsym.flags() & INTERFACE) != 0);
  3989             reverse = true;
  3990             to = from;
  3991             from = target;
  3993         List<Type> commonSupers = superClosure(to, erasure(from));
  3994         boolean giveWarning = commonSupers.isEmpty();
  3995         // The arguments to the supers could be unified here to
  3996         // get a more accurate analysis
  3997         while (commonSupers.nonEmpty()) {
  3998             Type t1 = asSuper(from, commonSupers.head);
  3999             Type t2 = commonSupers.head; // same as asSuper(to, commonSupers.head.tsym);
  4000             if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
  4001                 return false;
  4002             giveWarning = giveWarning || (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2));
  4003             commonSupers = commonSupers.tail;
  4005         if (giveWarning && !isReifiable(reverse ? from : to))
  4006             warn.warn(LintCategory.UNCHECKED);
  4007         if (!allowCovariantReturns)
  4008             // reject if there is a common method signature with
  4009             // incompatible return types.
  4010             chk.checkCompatibleAbstracts(warn.pos(), from, to);
  4011         return true;
  4014     private boolean sideCastFinal(Type from, Type to, Warner warn) {
  4015         // We are casting from type $from$ to type $to$, which are
  4016         // unrelated types one of which is final and the other of
  4017         // which is an interface.  This method
  4018         // tries to reject a cast by transferring type parameters
  4019         // from the final class to the interface.
  4020         boolean reverse = false;
  4021         Type target = to;
  4022         if ((to.tsym.flags() & INTERFACE) == 0) {
  4023             Assert.check((from.tsym.flags() & INTERFACE) != 0);
  4024             reverse = true;
  4025             to = from;
  4026             from = target;
  4028         Assert.check((from.tsym.flags() & FINAL) != 0);
  4029         Type t1 = asSuper(from, to);
  4030         if (t1 == null) return false;
  4031         Type t2 = to;
  4032         if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
  4033             return false;
  4034         if (!allowCovariantReturns)
  4035             // reject if there is a common method signature with
  4036             // incompatible return types.
  4037             chk.checkCompatibleAbstracts(warn.pos(), from, to);
  4038         if (!isReifiable(target) &&
  4039             (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2)))
  4040             warn.warn(LintCategory.UNCHECKED);
  4041         return true;
  4044     private boolean giveWarning(Type from, Type to) {
  4045         List<Type> bounds = to.isCompound() ?
  4046                 ((IntersectionClassType)to.unannotatedType()).getComponents() : List.of(to);
  4047         for (Type b : bounds) {
  4048             Type subFrom = asSub(from, b.tsym);
  4049             if (b.isParameterized() &&
  4050                     (!(isUnbounded(b) ||
  4051                     isSubtype(from, b) ||
  4052                     ((subFrom != null) && containsType(b.allparams(), subFrom.allparams()))))) {
  4053                 return true;
  4056         return false;
  4059     private List<Type> superClosure(Type t, Type s) {
  4060         List<Type> cl = List.nil();
  4061         for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
  4062             if (isSubtype(s, erasure(l.head))) {
  4063                 cl = insert(cl, l.head);
  4064             } else {
  4065                 cl = union(cl, superClosure(l.head, s));
  4068         return cl;
  4071     private boolean containsTypeEquivalent(Type t, Type s) {
  4072         return
  4073             isSameType(t, s) || // shortcut
  4074             containsType(t, s) && containsType(s, t);
  4077     // <editor-fold defaultstate="collapsed" desc="adapt">
  4078     /**
  4079      * Adapt a type by computing a substitution which maps a source
  4080      * type to a target type.
  4082      * @param source    the source type
  4083      * @param target    the target type
  4084      * @param from      the type variables of the computed substitution
  4085      * @param to        the types of the computed substitution.
  4086      */
  4087     public void adapt(Type source,
  4088                        Type target,
  4089                        ListBuffer<Type> from,
  4090                        ListBuffer<Type> to) throws AdaptFailure {
  4091         new Adapter(from, to).adapt(source, target);
  4094     class Adapter extends SimpleVisitor<Void, Type> {
  4096         ListBuffer<Type> from;
  4097         ListBuffer<Type> to;
  4098         Map<Symbol,Type> mapping;
  4100         Adapter(ListBuffer<Type> from, ListBuffer<Type> to) {
  4101             this.from = from;
  4102             this.to = to;
  4103             mapping = new HashMap<Symbol,Type>();
  4106         public void adapt(Type source, Type target) throws AdaptFailure {
  4107             visit(source, target);
  4108             List<Type> fromList = from.toList();
  4109             List<Type> toList = to.toList();
  4110             while (!fromList.isEmpty()) {
  4111                 Type val = mapping.get(fromList.head.tsym);
  4112                 if (toList.head != val)
  4113                     toList.head = val;
  4114                 fromList = fromList.tail;
  4115                 toList = toList.tail;
  4119         @Override
  4120         public Void visitClassType(ClassType source, Type target) throws AdaptFailure {
  4121             if (target.hasTag(CLASS))
  4122                 adaptRecursive(source.allparams(), target.allparams());
  4123             return null;
  4126         @Override
  4127         public Void visitArrayType(ArrayType source, Type target) throws AdaptFailure {
  4128             if (target.hasTag(ARRAY))
  4129                 adaptRecursive(elemtype(source), elemtype(target));
  4130             return null;
  4133         @Override
  4134         public Void visitWildcardType(WildcardType source, Type target) throws AdaptFailure {
  4135             if (source.isExtendsBound())
  4136                 adaptRecursive(upperBound(source), upperBound(target));
  4137             else if (source.isSuperBound())
  4138                 adaptRecursive(lowerBound(source), lowerBound(target));
  4139             return null;
  4142         @Override
  4143         public Void visitTypeVar(TypeVar source, Type target) throws AdaptFailure {
  4144             // Check to see if there is
  4145             // already a mapping for $source$, in which case
  4146             // the old mapping will be merged with the new
  4147             Type val = mapping.get(source.tsym);
  4148             if (val != null) {
  4149                 if (val.isSuperBound() && target.isSuperBound()) {
  4150                     val = isSubtype(lowerBound(val), lowerBound(target))
  4151                         ? target : val;
  4152                 } else if (val.isExtendsBound() && target.isExtendsBound()) {
  4153                     val = isSubtype(upperBound(val), upperBound(target))
  4154                         ? val : target;
  4155                 } else if (!isSameType(val, target)) {
  4156                     throw new AdaptFailure();
  4158             } else {
  4159                 val = target;
  4160                 from.append(source);
  4161                 to.append(target);
  4163             mapping.put(source.tsym, val);
  4164             return null;
  4167         @Override
  4168         public Void visitType(Type source, Type target) {
  4169             return null;
  4172         private Set<TypePair> cache = new HashSet<TypePair>();
  4174         private void adaptRecursive(Type source, Type target) {
  4175             TypePair pair = new TypePair(source, target);
  4176             if (cache.add(pair)) {
  4177                 try {
  4178                     visit(source, target);
  4179                 } finally {
  4180                     cache.remove(pair);
  4185         private void adaptRecursive(List<Type> source, List<Type> target) {
  4186             if (source.length() == target.length()) {
  4187                 while (source.nonEmpty()) {
  4188                     adaptRecursive(source.head, target.head);
  4189                     source = source.tail;
  4190                     target = target.tail;
  4196     public static class AdaptFailure extends RuntimeException {
  4197         static final long serialVersionUID = -7490231548272701566L;
  4200     private void adaptSelf(Type t,
  4201                            ListBuffer<Type> from,
  4202                            ListBuffer<Type> to) {
  4203         try {
  4204             //if (t.tsym.type != t)
  4205                 adapt(t.tsym.type, t, from, to);
  4206         } catch (AdaptFailure ex) {
  4207             // Adapt should never fail calculating a mapping from
  4208             // t.tsym.type to t as there can be no merge problem.
  4209             throw new AssertionError(ex);
  4212     // </editor-fold>
  4214     /**
  4215      * Rewrite all type variables (universal quantifiers) in the given
  4216      * type to wildcards (existential quantifiers).  This is used to
  4217      * determine if a cast is allowed.  For example, if high is true
  4218      * and {@code T <: Number}, then {@code List<T>} is rewritten to
  4219      * {@code List<?  extends Number>}.  Since {@code List<Integer> <:
  4220      * List<? extends Number>} a {@code List<T>} can be cast to {@code
  4221      * List<Integer>} with a warning.
  4222      * @param t a type
  4223      * @param high if true return an upper bound; otherwise a lower
  4224      * bound
  4225      * @param rewriteTypeVars only rewrite captured wildcards if false;
  4226      * otherwise rewrite all type variables
  4227      * @return the type rewritten with wildcards (existential
  4228      * quantifiers) only
  4229      */
  4230     private Type rewriteQuantifiers(Type t, boolean high, boolean rewriteTypeVars) {
  4231         return new Rewriter(high, rewriteTypeVars).visit(t);
  4234     class Rewriter extends UnaryVisitor<Type> {
  4236         boolean high;
  4237         boolean rewriteTypeVars;
  4239         Rewriter(boolean high, boolean rewriteTypeVars) {
  4240             this.high = high;
  4241             this.rewriteTypeVars = rewriteTypeVars;
  4244         @Override
  4245         public Type visitClassType(ClassType t, Void s) {
  4246             ListBuffer<Type> rewritten = new ListBuffer<Type>();
  4247             boolean changed = false;
  4248             for (Type arg : t.allparams()) {
  4249                 Type bound = visit(arg);
  4250                 if (arg != bound) {
  4251                     changed = true;
  4253                 rewritten.append(bound);
  4255             if (changed)
  4256                 return subst(t.tsym.type,
  4257                         t.tsym.type.allparams(),
  4258                         rewritten.toList());
  4259             else
  4260                 return t;
  4263         public Type visitType(Type t, Void s) {
  4264             return high ? upperBound(t) : lowerBound(t);
  4267         @Override
  4268         public Type visitCapturedType(CapturedType t, Void s) {
  4269             Type w_bound = t.wildcard.type;
  4270             Type bound = w_bound.contains(t) ?
  4271                         erasure(w_bound) :
  4272                         visit(w_bound);
  4273             return rewriteAsWildcardType(visit(bound), t.wildcard.bound, t.wildcard.kind);
  4276         @Override
  4277         public Type visitTypeVar(TypeVar t, Void s) {
  4278             if (rewriteTypeVars) {
  4279                 Type bound = t.bound.contains(t) ?
  4280                         erasure(t.bound) :
  4281                         visit(t.bound);
  4282                 return rewriteAsWildcardType(bound, t, EXTENDS);
  4283             } else {
  4284                 return t;
  4288         @Override
  4289         public Type visitWildcardType(WildcardType t, Void s) {
  4290             Type bound2 = visit(t.type);
  4291             return t.type == bound2 ? t : rewriteAsWildcardType(bound2, t.bound, t.kind);
  4294         private Type rewriteAsWildcardType(Type bound, TypeVar formal, BoundKind bk) {
  4295             switch (bk) {
  4296                case EXTENDS: return high ?
  4297                        makeExtendsWildcard(B(bound), formal) :
  4298                        makeExtendsWildcard(syms.objectType, formal);
  4299                case SUPER: return high ?
  4300                        makeSuperWildcard(syms.botType, formal) :
  4301                        makeSuperWildcard(B(bound), formal);
  4302                case UNBOUND: return makeExtendsWildcard(syms.objectType, formal);
  4303                default:
  4304                    Assert.error("Invalid bound kind " + bk);
  4305                    return null;
  4309         Type B(Type t) {
  4310             while (t.hasTag(WILDCARD)) {
  4311                 WildcardType w = (WildcardType)t.unannotatedType();
  4312                 t = high ?
  4313                     w.getExtendsBound() :
  4314                     w.getSuperBound();
  4315                 if (t == null) {
  4316                     t = high ? syms.objectType : syms.botType;
  4319             return t;
  4324     /**
  4325      * Create a wildcard with the given upper (extends) bound; create
  4326      * an unbounded wildcard if bound is Object.
  4328      * @param bound the upper bound
  4329      * @param formal the formal type parameter that will be
  4330      * substituted by the wildcard
  4331      */
  4332     private WildcardType makeExtendsWildcard(Type bound, TypeVar formal) {
  4333         if (bound == syms.objectType) {
  4334             return new WildcardType(syms.objectType,
  4335                                     BoundKind.UNBOUND,
  4336                                     syms.boundClass,
  4337                                     formal);
  4338         } else {
  4339             return new WildcardType(bound,
  4340                                     BoundKind.EXTENDS,
  4341                                     syms.boundClass,
  4342                                     formal);
  4346     /**
  4347      * Create a wildcard with the given lower (super) bound; create an
  4348      * unbounded wildcard if bound is bottom (type of {@code null}).
  4350      * @param bound the lower bound
  4351      * @param formal the formal type parameter that will be
  4352      * substituted by the wildcard
  4353      */
  4354     private WildcardType makeSuperWildcard(Type bound, TypeVar formal) {
  4355         if (bound.hasTag(BOT)) {
  4356             return new WildcardType(syms.objectType,
  4357                                     BoundKind.UNBOUND,
  4358                                     syms.boundClass,
  4359                                     formal);
  4360         } else {
  4361             return new WildcardType(bound,
  4362                                     BoundKind.SUPER,
  4363                                     syms.boundClass,
  4364                                     formal);
  4368     /**
  4369      * A wrapper for a type that allows use in sets.
  4370      */
  4371     public static class UniqueType {
  4372         public final Type type;
  4373         final Types types;
  4375         public UniqueType(Type type, Types types) {
  4376             this.type = type;
  4377             this.types = types;
  4380         public int hashCode() {
  4381             return types.hashCode(type);
  4384         public boolean equals(Object obj) {
  4385             return (obj instanceof UniqueType) &&
  4386                 types.isSameAnnotatedType(type, ((UniqueType)obj).type);
  4389         public String toString() {
  4390             return type.toString();
  4394     // </editor-fold>
  4396     // <editor-fold defaultstate="collapsed" desc="Visitors">
  4397     /**
  4398      * A default visitor for types.  All visitor methods except
  4399      * visitType are implemented by delegating to visitType.  Concrete
  4400      * subclasses must provide an implementation of visitType and can
  4401      * override other methods as needed.
  4403      * @param <R> the return type of the operation implemented by this
  4404      * visitor; use Void if no return type is needed.
  4405      * @param <S> the type of the second argument (the first being the
  4406      * type itself) of the operation implemented by this visitor; use
  4407      * Void if a second argument is not needed.
  4408      */
  4409     public static abstract class DefaultTypeVisitor<R,S> implements Type.Visitor<R,S> {
  4410         final public R visit(Type t, S s)               { return t.accept(this, s); }
  4411         public R visitClassType(ClassType t, S s)       { return visitType(t, s); }
  4412         public R visitWildcardType(WildcardType t, S s) { return visitType(t, s); }
  4413         public R visitArrayType(ArrayType t, S s)       { return visitType(t, s); }
  4414         public R visitMethodType(MethodType t, S s)     { return visitType(t, s); }
  4415         public R visitPackageType(PackageType t, S s)   { return visitType(t, s); }
  4416         public R visitTypeVar(TypeVar t, S s)           { return visitType(t, s); }
  4417         public R visitCapturedType(CapturedType t, S s) { return visitType(t, s); }
  4418         public R visitForAll(ForAll t, S s)             { return visitType(t, s); }
  4419         public R visitUndetVar(UndetVar t, S s)         { return visitType(t, s); }
  4420         public R visitErrorType(ErrorType t, S s)       { return visitType(t, s); }
  4421         // Pretend annotations don't exist
  4422         public R visitAnnotatedType(AnnotatedType t, S s) { return visit(t.unannotatedType(), s); }
  4425     /**
  4426      * A default visitor for symbols.  All visitor methods except
  4427      * visitSymbol are implemented by delegating to visitSymbol.  Concrete
  4428      * subclasses must provide an implementation of visitSymbol and can
  4429      * override other methods as needed.
  4431      * @param <R> the return type of the operation implemented by this
  4432      * visitor; use Void if no return type is needed.
  4433      * @param <S> the type of the second argument (the first being the
  4434      * symbol itself) of the operation implemented by this visitor; use
  4435      * Void if a second argument is not needed.
  4436      */
  4437     public static abstract class DefaultSymbolVisitor<R,S> implements Symbol.Visitor<R,S> {
  4438         final public R visit(Symbol s, S arg)                   { return s.accept(this, arg); }
  4439         public R visitClassSymbol(ClassSymbol s, S arg)         { return visitSymbol(s, arg); }
  4440         public R visitMethodSymbol(MethodSymbol s, S arg)       { return visitSymbol(s, arg); }
  4441         public R visitOperatorSymbol(OperatorSymbol s, S arg)   { return visitSymbol(s, arg); }
  4442         public R visitPackageSymbol(PackageSymbol s, S arg)     { return visitSymbol(s, arg); }
  4443         public R visitTypeSymbol(TypeSymbol s, S arg)           { return visitSymbol(s, arg); }
  4444         public R visitVarSymbol(VarSymbol s, S arg)             { return visitSymbol(s, arg); }
  4447     /**
  4448      * A <em>simple</em> visitor for types.  This visitor is simple as
  4449      * captured wildcards, for-all types (generic methods), and
  4450      * undetermined type variables (part of inference) are hidden.
  4451      * Captured wildcards are hidden by treating them as type
  4452      * variables and the rest are hidden by visiting their qtypes.
  4454      * @param <R> the return type of the operation implemented by this
  4455      * visitor; use Void if no return type is needed.
  4456      * @param <S> the type of the second argument (the first being the
  4457      * type itself) of the operation implemented by this visitor; use
  4458      * Void if a second argument is not needed.
  4459      */
  4460     public static abstract class SimpleVisitor<R,S> extends DefaultTypeVisitor<R,S> {
  4461         @Override
  4462         public R visitCapturedType(CapturedType t, S s) {
  4463             return visitTypeVar(t, s);
  4465         @Override
  4466         public R visitForAll(ForAll t, S s) {
  4467             return visit(t.qtype, s);
  4469         @Override
  4470         public R visitUndetVar(UndetVar t, S s) {
  4471             return visit(t.qtype, s);
  4475     /**
  4476      * A plain relation on types.  That is a 2-ary function on the
  4477      * form Type&nbsp;&times;&nbsp;Type&nbsp;&rarr;&nbsp;Boolean.
  4478      * <!-- In plain text: Type x Type -> Boolean -->
  4479      */
  4480     public static abstract class TypeRelation extends SimpleVisitor<Boolean,Type> {}
  4482     /**
  4483      * A convenience visitor for implementing operations that only
  4484      * require one argument (the type itself), that is, unary
  4485      * operations.
  4487      * @param <R> the return type of the operation implemented by this
  4488      * visitor; use Void if no return type is needed.
  4489      */
  4490     public static abstract class UnaryVisitor<R> extends SimpleVisitor<R,Void> {
  4491         final public R visit(Type t) { return t.accept(this, null); }
  4494     /**
  4495      * A visitor for implementing a mapping from types to types.  The
  4496      * default behavior of this class is to implement the identity
  4497      * mapping (mapping a type to itself).  This can be overridden in
  4498      * subclasses.
  4500      * @param <S> the type of the second argument (the first being the
  4501      * type itself) of this mapping; use Void if a second argument is
  4502      * not needed.
  4503      */
  4504     public static class MapVisitor<S> extends DefaultTypeVisitor<Type,S> {
  4505         final public Type visit(Type t) { return t.accept(this, null); }
  4506         public Type visitType(Type t, S s) { return t; }
  4508     // </editor-fold>
  4511     // <editor-fold defaultstate="collapsed" desc="Annotation support">
  4513     public RetentionPolicy getRetention(Attribute.Compound a) {
  4514         return getRetention(a.type.tsym);
  4517     public RetentionPolicy getRetention(Symbol sym) {
  4518         RetentionPolicy vis = RetentionPolicy.CLASS; // the default
  4519         Attribute.Compound c = sym.attribute(syms.retentionType.tsym);
  4520         if (c != null) {
  4521             Attribute value = c.member(names.value);
  4522             if (value != null && value instanceof Attribute.Enum) {
  4523                 Name levelName = ((Attribute.Enum)value).value.name;
  4524                 if (levelName == names.SOURCE) vis = RetentionPolicy.SOURCE;
  4525                 else if (levelName == names.CLASS) vis = RetentionPolicy.CLASS;
  4526                 else if (levelName == names.RUNTIME) vis = RetentionPolicy.RUNTIME;
  4527                 else ;// /* fail soft */ throw new AssertionError(levelName);
  4530         return vis;
  4532     // </editor-fold>
  4534     // <editor-fold defaultstate="collapsed" desc="Signature Generation">
  4536     public static abstract class SignatureGenerator {
  4538         private final Types types;
  4540         protected abstract void append(char ch);
  4541         protected abstract void append(byte[] ba);
  4542         protected abstract void append(Name name);
  4543         protected void classReference(ClassSymbol c) { /* by default: no-op */ }
  4545         protected SignatureGenerator(Types types) {
  4546             this.types = types;
  4549         /**
  4550          * Assemble signature of given type in string buffer.
  4551          */
  4552         public void assembleSig(Type type) {
  4553             type = type.unannotatedType();
  4554             switch (type.getTag()) {
  4555                 case BYTE:
  4556                     append('B');
  4557                     break;
  4558                 case SHORT:
  4559                     append('S');
  4560                     break;
  4561                 case CHAR:
  4562                     append('C');
  4563                     break;
  4564                 case INT:
  4565                     append('I');
  4566                     break;
  4567                 case LONG:
  4568                     append('J');
  4569                     break;
  4570                 case FLOAT:
  4571                     append('F');
  4572                     break;
  4573                 case DOUBLE:
  4574                     append('D');
  4575                     break;
  4576                 case BOOLEAN:
  4577                     append('Z');
  4578                     break;
  4579                 case VOID:
  4580                     append('V');
  4581                     break;
  4582                 case CLASS:
  4583                     append('L');
  4584                     assembleClassSig(type);
  4585                     append(';');
  4586                     break;
  4587                 case ARRAY:
  4588                     ArrayType at = (ArrayType) type;
  4589                     append('[');
  4590                     assembleSig(at.elemtype);
  4591                     break;
  4592                 case METHOD:
  4593                     MethodType mt = (MethodType) type;
  4594                     append('(');
  4595                     assembleSig(mt.argtypes);
  4596                     append(')');
  4597                     assembleSig(mt.restype);
  4598                     if (hasTypeVar(mt.thrown)) {
  4599                         for (List<Type> l = mt.thrown; l.nonEmpty(); l = l.tail) {
  4600                             append('^');
  4601                             assembleSig(l.head);
  4604                     break;
  4605                 case WILDCARD: {
  4606                     Type.WildcardType ta = (Type.WildcardType) type;
  4607                     switch (ta.kind) {
  4608                         case SUPER:
  4609                             append('-');
  4610                             assembleSig(ta.type);
  4611                             break;
  4612                         case EXTENDS:
  4613                             append('+');
  4614                             assembleSig(ta.type);
  4615                             break;
  4616                         case UNBOUND:
  4617                             append('*');
  4618                             break;
  4619                         default:
  4620                             throw new AssertionError(ta.kind);
  4622                     break;
  4624                 case TYPEVAR:
  4625                     append('T');
  4626                     append(type.tsym.name);
  4627                     append(';');
  4628                     break;
  4629                 case FORALL:
  4630                     Type.ForAll ft = (Type.ForAll) type;
  4631                     assembleParamsSig(ft.tvars);
  4632                     assembleSig(ft.qtype);
  4633                     break;
  4634                 default:
  4635                     throw new AssertionError("typeSig " + type.getTag());
  4639         public boolean hasTypeVar(List<Type> l) {
  4640             while (l.nonEmpty()) {
  4641                 if (l.head.hasTag(TypeTag.TYPEVAR)) {
  4642                     return true;
  4644                 l = l.tail;
  4646             return false;
  4649         public void assembleClassSig(Type type) {
  4650             type = type.unannotatedType();
  4651             ClassType ct = (ClassType) type;
  4652             ClassSymbol c = (ClassSymbol) ct.tsym;
  4653             classReference(c);
  4654             Type outer = ct.getEnclosingType();
  4655             if (outer.allparams().nonEmpty()) {
  4656                 boolean rawOuter =
  4657                         c.owner.kind == Kinds.MTH || // either a local class
  4658                         c.name == types.names.empty; // or anonymous
  4659                 assembleClassSig(rawOuter
  4660                         ? types.erasure(outer)
  4661                         : outer);
  4662                 append('.');
  4663                 Assert.check(c.flatname.startsWith(c.owner.enclClass().flatname));
  4664                 append(rawOuter
  4665                         ? c.flatname.subName(c.owner.enclClass().flatname.getByteLength() + 1, c.flatname.getByteLength())
  4666                         : c.name);
  4667             } else {
  4668                 append(externalize(c.flatname));
  4670             if (ct.getTypeArguments().nonEmpty()) {
  4671                 append('<');
  4672                 assembleSig(ct.getTypeArguments());
  4673                 append('>');
  4677         public void assembleParamsSig(List<Type> typarams) {
  4678             append('<');
  4679             for (List<Type> ts = typarams; ts.nonEmpty(); ts = ts.tail) {
  4680                 Type.TypeVar tvar = (Type.TypeVar) ts.head;
  4681                 append(tvar.tsym.name);
  4682                 List<Type> bounds = types.getBounds(tvar);
  4683                 if ((bounds.head.tsym.flags() & INTERFACE) != 0) {
  4684                     append(':');
  4686                 for (List<Type> l = bounds; l.nonEmpty(); l = l.tail) {
  4687                     append(':');
  4688                     assembleSig(l.head);
  4691             append('>');
  4694         private void assembleSig(List<Type> types) {
  4695             for (List<Type> ts = types; ts.nonEmpty(); ts = ts.tail) {
  4696                 assembleSig(ts.head);
  4700     // </editor-fold>

mercurial