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

Tue, 18 Mar 2014 22:12:46 +0000

author
vromero
date
Tue, 18 Mar 2014 22:12:46 +0000
changeset 2434
7de1481c6cd8
parent 2431
37c7dbe8efee
child 2525
2eb010b6cb22
child 2543
c6d5efccedc3
permissions
-rw-r--r--

8036007: javac crashes when encountering an unresolvable interface
Reviewed-by: vromero, jlahoda
Contributed-by: paul.govereau@oracle.com

     1 /*
     2  * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    26 package com.sun.tools.javac.code;
    28 import java.lang.ref.SoftReference;
    29 import java.util.HashSet;
    30 import java.util.HashMap;
    31 import java.util.Locale;
    32 import java.util.Map;
    33 import java.util.Set;
    34 import java.util.WeakHashMap;
    36 import javax.tools.JavaFileObject;
    38 import com.sun.tools.javac.code.Attribute.RetentionPolicy;
    39 import com.sun.tools.javac.code.Lint.LintCategory;
    40 import com.sun.tools.javac.code.Type.UndetVar.InferenceBound;
    41 import com.sun.tools.javac.comp.AttrContext;
    42 import com.sun.tools.javac.comp.Check;
    43 import com.sun.tools.javac.comp.Enter;
    44 import com.sun.tools.javac.comp.Env;
    45 import com.sun.tools.javac.jvm.ClassReader;
    46 import com.sun.tools.javac.tree.JCTree;
    47 import com.sun.tools.javac.util.*;
    48 import static com.sun.tools.javac.code.BoundKind.*;
    49 import static com.sun.tools.javac.code.Flags.*;
    50 import static com.sun.tools.javac.code.Scope.*;
    51 import static com.sun.tools.javac.code.Symbol.*;
    52 import static com.sun.tools.javac.code.Type.*;
    53 import static com.sun.tools.javac.code.TypeTag.*;
    54 import static com.sun.tools.javac.jvm.ClassFile.externalize;
    56 /**
    57  * Utility class containing various operations on types.
    58  *
    59  * <p>Unless other names are more illustrative, the following naming
    60  * conventions should be observed in this file:
    61  *
    62  * <dl>
    63  * <dt>t</dt>
    64  * <dd>If the first argument to an operation is a type, it should be named t.</dd>
    65  * <dt>s</dt>
    66  * <dd>Similarly, if the second argument to an operation is a type, it should be named s.</dd>
    67  * <dt>ts</dt>
    68  * <dd>If an operations takes a list of types, the first should be named ts.</dd>
    69  * <dt>ss</dt>
    70  * <dd>A second list of types should be named ss.</dd>
    71  * </dl>
    72  *
    73  * <p><b>This is NOT part of any supported API.
    74  * If you write code that depends on this, you do so at your own risk.
    75  * This code and its internal interfaces are subject to change or
    76  * deletion without notice.</b>
    77  */
    78 public class Types {
    79     protected static final Context.Key<Types> typesKey =
    80         new Context.Key<Types>();
    82     final Symtab syms;
    83     final JavacMessages messages;
    84     final Names names;
    85     final boolean allowBoxing;
    86     final boolean allowCovariantReturns;
    87     final boolean allowObjectToPrimitiveCast;
    88     final ClassReader reader;
    89     final Check chk;
    90     final Enter enter;
    91     JCDiagnostic.Factory diags;
    92     List<Warner> warnStack = List.nil();
    93     final Name capturedName;
    94     private final FunctionDescriptorLookupError functionDescriptorLookupError;
    96     public final Warner noWarnings;
    98     // <editor-fold defaultstate="collapsed" desc="Instantiating">
    99     public static Types instance(Context context) {
   100         Types instance = context.get(typesKey);
   101         if (instance == null)
   102             instance = new Types(context);
   103         return instance;
   104     }
   106     protected Types(Context context) {
   107         context.put(typesKey, this);
   108         syms = Symtab.instance(context);
   109         names = Names.instance(context);
   110         Source source = Source.instance(context);
   111         allowBoxing = source.allowBoxing();
   112         allowCovariantReturns = source.allowCovariantReturns();
   113         allowObjectToPrimitiveCast = source.allowObjectToPrimitiveCast();
   114         reader = ClassReader.instance(context);
   115         chk = Check.instance(context);
   116         enter = Enter.instance(context);
   117         capturedName = names.fromString("<captured wildcard>");
   118         messages = JavacMessages.instance(context);
   119         diags = JCDiagnostic.Factory.instance(context);
   120         functionDescriptorLookupError = new FunctionDescriptorLookupError();
   121         noWarnings = new Warner(null);
   122     }
   123     // </editor-fold>
   125      // <editor-fold defaultstate="collapsed" desc="bounds">
   126      /**
   127       * Get a wildcard's upper bound, returning non-wildcards unchanged.
   128       * @param t a type argument, either a wildcard or a type
   129       */
   130      public Type wildUpperBound(Type t) {
   131          if (t.hasTag(WILDCARD)) {
   132              WildcardType w = (WildcardType) t.unannotatedType();
   133              if (w.isSuperBound())
   134                  return w.bound == null ? syms.objectType : w.bound.bound;
   135              else
   136                  return wildUpperBound(w.type);
   137          }
   138          else return t.unannotatedType();
   139      }
   141      /**
   142       * Get a capture variable's upper bound, returning other types unchanged.
   143       * @param t a type
   144       */
   145      public Type cvarUpperBound(Type t) {
   146          if (t.hasTag(TYPEVAR)) {
   147              TypeVar v = (TypeVar) t.unannotatedType();
   148              return v.isCaptured() ? cvarUpperBound(v.bound) : v;
   149          }
   150          else return t.unannotatedType();
   151      }
   153     /**
   154      * Get a wildcard's lower bound, returning non-wildcards unchanged.
   155      * @param t a type argument, either a wildcard or a type
   156      */
   157     public Type wildLowerBound(Type t) {
   158         if (t.hasTag(WILDCARD)) {
   159             WildcardType w = (WildcardType) t.unannotatedType();
   160             return w.isExtendsBound() ? syms.botType : wildLowerBound(w.type);
   161         }
   162         else return t.unannotatedType();
   163     }
   165     /**
   166      * Get a capture variable's lower bound, returning other types unchanged.
   167      * @param t a type
   168      */
   169     public Type cvarLowerBound(Type t) {
   170         if (t.hasTag(TYPEVAR)) {
   171             TypeVar v = (TypeVar) t.unannotatedType();
   172             return v.isCaptured() ? cvarLowerBound(v.getLowerBound()) : v;
   173         }
   174         else return t.unannotatedType();
   175     }
   176     // </editor-fold>
   178     // <editor-fold defaultstate="collapsed" desc="isUnbounded">
   179     /**
   180      * Checks that all the arguments to a class are unbounded
   181      * wildcards or something else that doesn't make any restrictions
   182      * on the arguments. If a class isUnbounded, a raw super- or
   183      * subclass can be cast to it without a warning.
   184      * @param t a type
   185      * @return true iff the given type is unbounded or raw
   186      */
   187     public boolean isUnbounded(Type t) {
   188         return isUnbounded.visit(t);
   189     }
   190     // where
   191         private final UnaryVisitor<Boolean> isUnbounded = new UnaryVisitor<Boolean>() {
   193             public Boolean visitType(Type t, Void ignored) {
   194                 return true;
   195             }
   197             @Override
   198             public Boolean visitClassType(ClassType t, Void ignored) {
   199                 List<Type> parms = t.tsym.type.allparams();
   200                 List<Type> args = t.allparams();
   201                 while (parms.nonEmpty()) {
   202                     WildcardType unb = new WildcardType(syms.objectType,
   203                                                         BoundKind.UNBOUND,
   204                                                         syms.boundClass,
   205                                                         (TypeVar)parms.head.unannotatedType());
   206                     if (!containsType(args.head, unb))
   207                         return false;
   208                     parms = parms.tail;
   209                     args = args.tail;
   210                 }
   211                 return true;
   212             }
   213         };
   214     // </editor-fold>
   216     // <editor-fold defaultstate="collapsed" desc="asSub">
   217     /**
   218      * Return the least specific subtype of t that starts with symbol
   219      * sym.  If none exists, return null.  The least specific subtype
   220      * is determined as follows:
   221      *
   222      * <p>If there is exactly one parameterized instance of sym that is a
   223      * subtype of t, that parameterized instance is returned.<br>
   224      * Otherwise, if the plain type or raw type `sym' is a subtype of
   225      * type t, the type `sym' itself is returned.  Otherwise, null is
   226      * returned.
   227      */
   228     public Type asSub(Type t, Symbol sym) {
   229         return asSub.visit(t, sym);
   230     }
   231     // where
   232         private final SimpleVisitor<Type,Symbol> asSub = new SimpleVisitor<Type,Symbol>() {
   234             public Type visitType(Type t, Symbol sym) {
   235                 return null;
   236             }
   238             @Override
   239             public Type visitClassType(ClassType t, Symbol sym) {
   240                 if (t.tsym == sym)
   241                     return t;
   242                 Type base = asSuper(sym.type, t.tsym);
   243                 if (base == null)
   244                     return null;
   245                 ListBuffer<Type> from = new ListBuffer<Type>();
   246                 ListBuffer<Type> to = new ListBuffer<Type>();
   247                 try {
   248                     adapt(base, t, from, to);
   249                 } catch (AdaptFailure ex) {
   250                     return null;
   251                 }
   252                 Type res = subst(sym.type, from.toList(), to.toList());
   253                 if (!isSubtype(res, t))
   254                     return null;
   255                 ListBuffer<Type> openVars = new ListBuffer<Type>();
   256                 for (List<Type> l = sym.type.allparams();
   257                      l.nonEmpty(); l = l.tail)
   258                     if (res.contains(l.head) && !t.contains(l.head))
   259                         openVars.append(l.head);
   260                 if (openVars.nonEmpty()) {
   261                     if (t.isRaw()) {
   262                         // The subtype of a raw type is raw
   263                         res = erasure(res);
   264                     } else {
   265                         // Unbound type arguments default to ?
   266                         List<Type> opens = openVars.toList();
   267                         ListBuffer<Type> qs = new ListBuffer<Type>();
   268                         for (List<Type> iter = opens; iter.nonEmpty(); iter = iter.tail) {
   269                             qs.append(new WildcardType(syms.objectType, BoundKind.UNBOUND, syms.boundClass, (TypeVar) iter.head.unannotatedType()));
   270                         }
   271                         res = subst(res, opens, qs.toList());
   272                     }
   273                 }
   274                 return res;
   275             }
   277             @Override
   278             public Type visitErrorType(ErrorType t, Symbol sym) {
   279                 return t;
   280             }
   281         };
   282     // </editor-fold>
   284     // <editor-fold defaultstate="collapsed" desc="isConvertible">
   285     /**
   286      * Is t a subtype of or convertible via boxing/unboxing
   287      * conversion to s?
   288      */
   289     public boolean isConvertible(Type t, Type s, Warner warn) {
   290         if (t.hasTag(ERROR)) {
   291             return true;
   292         }
   293         boolean tPrimitive = t.isPrimitive();
   294         boolean sPrimitive = s.isPrimitive();
   295         if (tPrimitive == sPrimitive) {
   296             return isSubtypeUnchecked(t, s, warn);
   297         }
   298         if (!allowBoxing) return false;
   299         return tPrimitive
   300             ? isSubtype(boxedClass(t).type, s)
   301             : isSubtype(unboxedType(t), s);
   302     }
   304     /**
   305      * Is t a subtype of or convertible via boxing/unboxing
   306      * conversions to s?
   307      */
   308     public boolean isConvertible(Type t, Type s) {
   309         return isConvertible(t, s, noWarnings);
   310     }
   311     // </editor-fold>
   313     // <editor-fold defaultstate="collapsed" desc="findSam">
   315     /**
   316      * Exception used to report a function descriptor lookup failure. The exception
   317      * wraps a diagnostic that can be used to generate more details error
   318      * messages.
   319      */
   320     public static class FunctionDescriptorLookupError extends RuntimeException {
   321         private static final long serialVersionUID = 0;
   323         JCDiagnostic diagnostic;
   325         FunctionDescriptorLookupError() {
   326             this.diagnostic = null;
   327         }
   329         FunctionDescriptorLookupError setMessage(JCDiagnostic diag) {
   330             this.diagnostic = diag;
   331             return this;
   332         }
   334         public JCDiagnostic getDiagnostic() {
   335             return diagnostic;
   336         }
   337     }
   339     /**
   340      * A cache that keeps track of function descriptors associated with given
   341      * functional interfaces.
   342      */
   343     class DescriptorCache {
   345         private WeakHashMap<TypeSymbol, Entry> _map = new WeakHashMap<TypeSymbol, Entry>();
   347         class FunctionDescriptor {
   348             Symbol descSym;
   350             FunctionDescriptor(Symbol descSym) {
   351                 this.descSym = descSym;
   352             }
   354             public Symbol getSymbol() {
   355                 return descSym;
   356             }
   358             public Type getType(Type site) {
   359                 site = removeWildcards(site);
   360                 if (!chk.checkValidGenericType(site)) {
   361                     //if the inferred functional interface type is not well-formed,
   362                     //or if it's not a subtype of the original target, issue an error
   363                     throw failure(diags.fragment("no.suitable.functional.intf.inst", site));
   364                 }
   365                 return memberType(site, descSym);
   366             }
   367         }
   369         class Entry {
   370             final FunctionDescriptor cachedDescRes;
   371             final int prevMark;
   373             public Entry(FunctionDescriptor cachedDescRes,
   374                     int prevMark) {
   375                 this.cachedDescRes = cachedDescRes;
   376                 this.prevMark = prevMark;
   377             }
   379             boolean matches(int mark) {
   380                 return  this.prevMark == mark;
   381             }
   382         }
   384         FunctionDescriptor get(TypeSymbol origin) throws FunctionDescriptorLookupError {
   385             Entry e = _map.get(origin);
   386             CompoundScope members = membersClosure(origin.type, false);
   387             if (e == null ||
   388                     !e.matches(members.getMark())) {
   389                 FunctionDescriptor descRes = findDescriptorInternal(origin, members);
   390                 _map.put(origin, new Entry(descRes, members.getMark()));
   391                 return descRes;
   392             }
   393             else {
   394                 return e.cachedDescRes;
   395             }
   396         }
   398         /**
   399          * Compute the function descriptor associated with a given functional interface
   400          */
   401         public FunctionDescriptor findDescriptorInternal(TypeSymbol origin,
   402                 CompoundScope membersCache) throws FunctionDescriptorLookupError {
   403             if (!origin.isInterface() || (origin.flags() & ANNOTATION) != 0) {
   404                 //t must be an interface
   405                 throw failure("not.a.functional.intf", origin);
   406             }
   408             final ListBuffer<Symbol> abstracts = new ListBuffer<>();
   409             for (Symbol sym : membersCache.getElements(new DescriptorFilter(origin))) {
   410                 Type mtype = memberType(origin.type, sym);
   411                 if (abstracts.isEmpty() ||
   412                         (sym.name == abstracts.first().name &&
   413                         overrideEquivalent(mtype, memberType(origin.type, abstracts.first())))) {
   414                     abstracts.append(sym);
   415                 } else {
   416                     //the target method(s) should be the only abstract members of t
   417                     throw failure("not.a.functional.intf.1",  origin,
   418                             diags.fragment("incompatible.abstracts", Kinds.kindName(origin), origin));
   419                 }
   420             }
   421             if (abstracts.isEmpty()) {
   422                 //t must define a suitable non-generic method
   423                 throw failure("not.a.functional.intf.1", origin,
   424                             diags.fragment("no.abstracts", Kinds.kindName(origin), origin));
   425             } else if (abstracts.size() == 1) {
   426                 return new FunctionDescriptor(abstracts.first());
   427             } else { // size > 1
   428                 FunctionDescriptor descRes = mergeDescriptors(origin, abstracts.toList());
   429                 if (descRes == null) {
   430                     //we can get here if the functional interface is ill-formed
   431                     ListBuffer<JCDiagnostic> descriptors = new ListBuffer<>();
   432                     for (Symbol desc : abstracts) {
   433                         String key = desc.type.getThrownTypes().nonEmpty() ?
   434                                 "descriptor.throws" : "descriptor";
   435                         descriptors.append(diags.fragment(key, desc.name,
   436                                 desc.type.getParameterTypes(),
   437                                 desc.type.getReturnType(),
   438                                 desc.type.getThrownTypes()));
   439                     }
   440                     JCDiagnostic.MultilineDiagnostic incompatibleDescriptors =
   441                             new JCDiagnostic.MultilineDiagnostic(diags.fragment("incompatible.descs.in.functional.intf",
   442                             Kinds.kindName(origin), origin), descriptors.toList());
   443                     throw failure(incompatibleDescriptors);
   444                 }
   445                 return descRes;
   446             }
   447         }
   449         /**
   450          * Compute a synthetic type for the target descriptor given a list
   451          * of override-equivalent methods in the functional interface type.
   452          * The resulting method type is a method type that is override-equivalent
   453          * and return-type substitutable with each method in the original list.
   454          */
   455         private FunctionDescriptor mergeDescriptors(TypeSymbol origin, List<Symbol> methodSyms) {
   456             //pick argument types - simply take the signature that is a
   457             //subsignature of all other signatures in the list (as per JLS 8.4.2)
   458             List<Symbol> mostSpecific = List.nil();
   459             outer: for (Symbol msym1 : methodSyms) {
   460                 Type mt1 = memberType(origin.type, msym1);
   461                 for (Symbol msym2 : methodSyms) {
   462                     Type mt2 = memberType(origin.type, msym2);
   463                     if (!isSubSignature(mt1, mt2)) {
   464                         continue outer;
   465                     }
   466                 }
   467                 mostSpecific = mostSpecific.prepend(msym1);
   468             }
   469             if (mostSpecific.isEmpty()) {
   470                 return null;
   471             }
   474             //pick return types - this is done in two phases: (i) first, the most
   475             //specific return type is chosen using strict subtyping; if this fails,
   476             //a second attempt is made using return type substitutability (see JLS 8.4.5)
   477             boolean phase2 = false;
   478             Symbol bestSoFar = null;
   479             while (bestSoFar == null) {
   480                 outer: for (Symbol msym1 : mostSpecific) {
   481                     Type mt1 = memberType(origin.type, msym1);
   482                     for (Symbol msym2 : methodSyms) {
   483                         Type mt2 = memberType(origin.type, msym2);
   484                         if (phase2 ?
   485                                 !returnTypeSubstitutable(mt1, mt2) :
   486                                 !isSubtypeInternal(mt1.getReturnType(), mt2.getReturnType())) {
   487                             continue outer;
   488                         }
   489                     }
   490                     bestSoFar = msym1;
   491                 }
   492                 if (phase2) {
   493                     break;
   494                 } else {
   495                     phase2 = true;
   496                 }
   497             }
   498             if (bestSoFar == null) return null;
   500             //merge thrown types - form the intersection of all the thrown types in
   501             //all the signatures in the list
   502             boolean toErase = !bestSoFar.type.hasTag(FORALL);
   503             List<Type> thrown = null;
   504             Type mt1 = memberType(origin.type, bestSoFar);
   505             for (Symbol msym2 : methodSyms) {
   506                 Type mt2 = memberType(origin.type, msym2);
   507                 List<Type> thrown_mt2 = mt2.getThrownTypes();
   508                 if (toErase) {
   509                     thrown_mt2 = erasure(thrown_mt2);
   510                 } else {
   511                     /* If bestSoFar is generic then all the methods are generic.
   512                      * The opposite is not true: a non generic method can override
   513                      * a generic method (raw override) so it's safe to cast mt1 and
   514                      * mt2 to ForAll.
   515                      */
   516                     ForAll fa1 = (ForAll)mt1;
   517                     ForAll fa2 = (ForAll)mt2;
   518                     thrown_mt2 = subst(thrown_mt2, fa2.tvars, fa1.tvars);
   519                 }
   520                 thrown = (thrown == null) ?
   521                     thrown_mt2 :
   522                     chk.intersect(thrown_mt2, thrown);
   523             }
   525             final List<Type> thrown1 = thrown;
   526             return new FunctionDescriptor(bestSoFar) {
   527                 @Override
   528                 public Type getType(Type origin) {
   529                     Type mt = memberType(origin, getSymbol());
   530                     return createMethodTypeWithThrown(mt, thrown1);
   531                 }
   532             };
   533         }
   535         boolean isSubtypeInternal(Type s, Type t) {
   536             return (s.isPrimitive() && t.isPrimitive()) ?
   537                     isSameType(t, s) :
   538                     isSubtype(s, t);
   539         }
   541         FunctionDescriptorLookupError failure(String msg, Object... args) {
   542             return failure(diags.fragment(msg, args));
   543         }
   545         FunctionDescriptorLookupError failure(JCDiagnostic diag) {
   546             return functionDescriptorLookupError.setMessage(diag);
   547         }
   548     }
   550     private DescriptorCache descCache = new DescriptorCache();
   552     /**
   553      * Find the method descriptor associated to this class symbol - if the
   554      * symbol 'origin' is not a functional interface, an exception is thrown.
   555      */
   556     public Symbol findDescriptorSymbol(TypeSymbol origin) throws FunctionDescriptorLookupError {
   557         return descCache.get(origin).getSymbol();
   558     }
   560     /**
   561      * Find the type of the method descriptor associated to this class symbol -
   562      * if the symbol 'origin' is not a functional interface, an exception is thrown.
   563      */
   564     public Type findDescriptorType(Type origin) throws FunctionDescriptorLookupError {
   565         return descCache.get(origin.tsym).getType(origin);
   566     }
   568     /**
   569      * Is given type a functional interface?
   570      */
   571     public boolean isFunctionalInterface(TypeSymbol tsym) {
   572         try {
   573             findDescriptorSymbol(tsym);
   574             return true;
   575         } catch (FunctionDescriptorLookupError ex) {
   576             return false;
   577         }
   578     }
   580     public boolean isFunctionalInterface(Type site) {
   581         try {
   582             findDescriptorType(site);
   583             return true;
   584         } catch (FunctionDescriptorLookupError ex) {
   585             return false;
   586         }
   587     }
   589     public Type removeWildcards(Type site) {
   590         Type capturedSite = capture(site);
   591         if (capturedSite != site) {
   592             Type formalInterface = site.tsym.type;
   593             ListBuffer<Type> typeargs = new ListBuffer<>();
   594             List<Type> actualTypeargs = site.getTypeArguments();
   595             List<Type> capturedTypeargs = capturedSite.getTypeArguments();
   596             //simply replace the wildcards with its bound
   597             for (Type t : formalInterface.getTypeArguments()) {
   598                 if (actualTypeargs.head.hasTag(WILDCARD)) {
   599                     WildcardType wt = (WildcardType)actualTypeargs.head.unannotatedType();
   600                     Type bound;
   601                     switch (wt.kind) {
   602                         case EXTENDS:
   603                         case UNBOUND:
   604                             CapturedType capVar = (CapturedType)capturedTypeargs.head.unannotatedType();
   605                             //use declared bound if it doesn't depend on formal type-args
   606                             bound = capVar.bound.containsAny(capturedSite.getTypeArguments()) ?
   607                                     wt.type : capVar.bound;
   608                             break;
   609                         default:
   610                             bound = wt.type;
   611                     }
   612                     typeargs.append(bound);
   613                 } else {
   614                     typeargs.append(actualTypeargs.head);
   615                 }
   616                 actualTypeargs = actualTypeargs.tail;
   617                 capturedTypeargs = capturedTypeargs.tail;
   618             }
   619             return subst(formalInterface, formalInterface.getTypeArguments(), typeargs.toList());
   620         } else {
   621             return site;
   622         }
   623     }
   625     /**
   626      * Create a symbol for a class that implements a given functional interface
   627      * and overrides its functional descriptor. This routine is used for two
   628      * main purposes: (i) checking well-formedness of a functional interface;
   629      * (ii) perform functional interface bridge calculation.
   630      */
   631     public ClassSymbol makeFunctionalInterfaceClass(Env<AttrContext> env, Name name, List<Type> targets, long cflags) {
   632         if (targets.isEmpty()) {
   633             return null;
   634         }
   635         Symbol descSym = findDescriptorSymbol(targets.head.tsym);
   636         Type descType = findDescriptorType(targets.head);
   637         ClassSymbol csym = new ClassSymbol(cflags, name, env.enclClass.sym.outermostClass());
   638         csym.completer = null;
   639         csym.members_field = new Scope(csym);
   640         MethodSymbol instDescSym = new MethodSymbol(descSym.flags(), descSym.name, descType, csym);
   641         csym.members_field.enter(instDescSym);
   642         Type.ClassType ctype = new Type.ClassType(Type.noType, List.<Type>nil(), csym);
   643         ctype.supertype_field = syms.objectType;
   644         ctype.interfaces_field = targets;
   645         csym.type = ctype;
   646         csym.sourcefile = ((ClassSymbol)csym.owner).sourcefile;
   647         return csym;
   648     }
   650     /**
   651      * Find the minimal set of methods that are overridden by the functional
   652      * descriptor in 'origin'. All returned methods are assumed to have different
   653      * erased signatures.
   654      */
   655     public List<Symbol> functionalInterfaceBridges(TypeSymbol origin) {
   656         Assert.check(isFunctionalInterface(origin));
   657         Symbol descSym = findDescriptorSymbol(origin);
   658         CompoundScope members = membersClosure(origin.type, false);
   659         ListBuffer<Symbol> overridden = new ListBuffer<>();
   660         outer: for (Symbol m2 : members.getElementsByName(descSym.name, bridgeFilter)) {
   661             if (m2 == descSym) continue;
   662             else if (descSym.overrides(m2, origin, Types.this, false)) {
   663                 for (Symbol m3 : overridden) {
   664                     if (isSameType(m3.erasure(Types.this), m2.erasure(Types.this)) ||
   665                             (m3.overrides(m2, origin, Types.this, false) &&
   666                             (pendingBridges((ClassSymbol)origin, m3.enclClass()) ||
   667                             (((MethodSymbol)m2).binaryImplementation((ClassSymbol)m3.owner, Types.this) != null)))) {
   668                         continue outer;
   669                     }
   670                 }
   671                 overridden.add(m2);
   672             }
   673         }
   674         return overridden.toList();
   675     }
   676     //where
   677         private Filter<Symbol> bridgeFilter = new Filter<Symbol>() {
   678             public boolean accepts(Symbol t) {
   679                 return t.kind == Kinds.MTH &&
   680                         t.name != names.init &&
   681                         t.name != names.clinit &&
   682                         (t.flags() & SYNTHETIC) == 0;
   683             }
   684         };
   685         private boolean pendingBridges(ClassSymbol origin, TypeSymbol s) {
   686             //a symbol will be completed from a classfile if (a) symbol has
   687             //an associated file object with CLASS kind and (b) the symbol has
   688             //not been entered
   689             if (origin.classfile != null &&
   690                     origin.classfile.getKind() == JavaFileObject.Kind.CLASS &&
   691                     enter.getEnv(origin) == null) {
   692                 return false;
   693             }
   694             if (origin == s) {
   695                 return true;
   696             }
   697             for (Type t : interfaces(origin.type)) {
   698                 if (pendingBridges((ClassSymbol)t.tsym, s)) {
   699                     return true;
   700                 }
   701             }
   702             return false;
   703         }
   704     // </editor-fold>
   706    /**
   707     * Scope filter used to skip methods that should be ignored (such as methods
   708     * overridden by j.l.Object) during function interface conversion interface check
   709     */
   710     class DescriptorFilter implements Filter<Symbol> {
   712        TypeSymbol origin;
   714        DescriptorFilter(TypeSymbol origin) {
   715            this.origin = origin;
   716        }
   718        @Override
   719        public boolean accepts(Symbol sym) {
   720            return sym.kind == Kinds.MTH &&
   721                    (sym.flags() & (ABSTRACT | DEFAULT)) == ABSTRACT &&
   722                    !overridesObjectMethod(origin, sym) &&
   723                    (interfaceCandidates(origin.type, (MethodSymbol)sym).head.flags() & DEFAULT) == 0;
   724        }
   725     };
   727     // <editor-fold defaultstate="collapsed" desc="isSubtype">
   728     /**
   729      * Is t an unchecked subtype of s?
   730      */
   731     public boolean isSubtypeUnchecked(Type t, Type s) {
   732         return isSubtypeUnchecked(t, s, noWarnings);
   733     }
   734     /**
   735      * Is t an unchecked subtype of s?
   736      */
   737     public boolean isSubtypeUnchecked(Type t, Type s, Warner warn) {
   738         boolean result = isSubtypeUncheckedInternal(t, s, warn);
   739         if (result) {
   740             checkUnsafeVarargsConversion(t, s, warn);
   741         }
   742         return result;
   743     }
   744     //where
   745         private boolean isSubtypeUncheckedInternal(Type t, Type s, Warner warn) {
   746             if (t.hasTag(ARRAY) && s.hasTag(ARRAY)) {
   747                 t = t.unannotatedType();
   748                 s = s.unannotatedType();
   749                 if (((ArrayType)t).elemtype.isPrimitive()) {
   750                     return isSameType(elemtype(t), elemtype(s));
   751                 } else {
   752                     return isSubtypeUnchecked(elemtype(t), elemtype(s), warn);
   753                 }
   754             } else if (isSubtype(t, s)) {
   755                 return true;
   756             } else if (t.hasTag(TYPEVAR)) {
   757                 return isSubtypeUnchecked(t.getUpperBound(), s, warn);
   758             } else if (!s.isRaw()) {
   759                 Type t2 = asSuper(t, s.tsym);
   760                 if (t2 != null && t2.isRaw()) {
   761                     if (isReifiable(s)) {
   762                         warn.silentWarn(LintCategory.UNCHECKED);
   763                     } else {
   764                         warn.warn(LintCategory.UNCHECKED);
   765                     }
   766                     return true;
   767                 }
   768             }
   769             return false;
   770         }
   772         private void checkUnsafeVarargsConversion(Type t, Type s, Warner warn) {
   773             if (!t.hasTag(ARRAY) || isReifiable(t)) {
   774                 return;
   775             }
   776             t = t.unannotatedType();
   777             s = s.unannotatedType();
   778             ArrayType from = (ArrayType)t;
   779             boolean shouldWarn = false;
   780             switch (s.getTag()) {
   781                 case ARRAY:
   782                     ArrayType to = (ArrayType)s;
   783                     shouldWarn = from.isVarargs() &&
   784                             !to.isVarargs() &&
   785                             !isReifiable(from);
   786                     break;
   787                 case CLASS:
   788                     shouldWarn = from.isVarargs();
   789                     break;
   790             }
   791             if (shouldWarn) {
   792                 warn.warn(LintCategory.VARARGS);
   793             }
   794         }
   796     /**
   797      * Is t a subtype of s?<br>
   798      * (not defined for Method and ForAll types)
   799      */
   800     final public boolean isSubtype(Type t, Type s) {
   801         return isSubtype(t, s, true);
   802     }
   803     final public boolean isSubtypeNoCapture(Type t, Type s) {
   804         return isSubtype(t, s, false);
   805     }
   806     public boolean isSubtype(Type t, Type s, boolean capture) {
   807         if (t == s)
   808             return true;
   810         t = t.unannotatedType();
   811         s = s.unannotatedType();
   813         if (t == s)
   814             return true;
   816         if (s.isPartial())
   817             return isSuperType(s, t);
   819         if (s.isCompound()) {
   820             for (Type s2 : interfaces(s).prepend(supertype(s))) {
   821                 if (!isSubtype(t, s2, capture))
   822                     return false;
   823             }
   824             return true;
   825         }
   827         // Generally, if 's' is a type variable, recur on lower bound; but
   828         // for inference variables and intersections, we need to keep 's'
   829         // (see JLS 4.10.2 for intersections and 18.2.3 for inference vars)
   830         if (!t.hasTag(UNDETVAR) && !t.isCompound()) {
   831             // TODO: JDK-8039198, bounds checking sometimes passes in a wildcard as s
   832             Type lower = cvarLowerBound(wildLowerBound(s));
   833             if (s != lower)
   834                 return isSubtype(capture ? capture(t) : t, lower, false);
   835         }
   837         return isSubtype.visit(capture ? capture(t) : t, s);
   838     }
   839     // where
   840         private TypeRelation isSubtype = new TypeRelation()
   841         {
   842             @Override
   843             public Boolean visitType(Type t, Type s) {
   844                 switch (t.getTag()) {
   845                  case BYTE:
   846                      return (!s.hasTag(CHAR) && t.getTag().isSubRangeOf(s.getTag()));
   847                  case CHAR:
   848                      return (!s.hasTag(SHORT) && t.getTag().isSubRangeOf(s.getTag()));
   849                  case SHORT: case INT: case LONG:
   850                  case FLOAT: case DOUBLE:
   851                      return t.getTag().isSubRangeOf(s.getTag());
   852                  case BOOLEAN: case VOID:
   853                      return t.hasTag(s.getTag());
   854                  case TYPEVAR:
   855                      return isSubtypeNoCapture(t.getUpperBound(), s);
   856                  case BOT:
   857                      return
   858                          s.hasTag(BOT) || s.hasTag(CLASS) ||
   859                          s.hasTag(ARRAY) || s.hasTag(TYPEVAR);
   860                  case WILDCARD: //we shouldn't be here - avoids crash (see 7034495)
   861                  case NONE:
   862                      return false;
   863                  default:
   864                      throw new AssertionError("isSubtype " + t.getTag());
   865                  }
   866             }
   868             private Set<TypePair> cache = new HashSet<TypePair>();
   870             private boolean containsTypeRecursive(Type t, Type s) {
   871                 TypePair pair = new TypePair(t, s);
   872                 if (cache.add(pair)) {
   873                     try {
   874                         return containsType(t.getTypeArguments(),
   875                                             s.getTypeArguments());
   876                     } finally {
   877                         cache.remove(pair);
   878                     }
   879                 } else {
   880                     return containsType(t.getTypeArguments(),
   881                                         rewriteSupers(s).getTypeArguments());
   882                 }
   883             }
   885             private Type rewriteSupers(Type t) {
   886                 if (!t.isParameterized())
   887                     return t;
   888                 ListBuffer<Type> from = new ListBuffer<>();
   889                 ListBuffer<Type> to = new ListBuffer<>();
   890                 adaptSelf(t, from, to);
   891                 if (from.isEmpty())
   892                     return t;
   893                 ListBuffer<Type> rewrite = new ListBuffer<>();
   894                 boolean changed = false;
   895                 for (Type orig : to.toList()) {
   896                     Type s = rewriteSupers(orig);
   897                     if (s.isSuperBound() && !s.isExtendsBound()) {
   898                         s = new WildcardType(syms.objectType,
   899                                              BoundKind.UNBOUND,
   900                                              syms.boundClass);
   901                         changed = true;
   902                     } else if (s != orig) {
   903                         s = new WildcardType(wildUpperBound(s),
   904                                              BoundKind.EXTENDS,
   905                                              syms.boundClass);
   906                         changed = true;
   907                     }
   908                     rewrite.append(s);
   909                 }
   910                 if (changed)
   911                     return subst(t.tsym.type, from.toList(), rewrite.toList());
   912                 else
   913                     return t;
   914             }
   916             @Override
   917             public Boolean visitClassType(ClassType t, Type s) {
   918                 Type sup = asSuper(t, s.tsym);
   919                 if (sup == null) return false;
   920                 // If t is an intersection, sup might not be a class type
   921                 if (!sup.hasTag(CLASS)) return isSubtypeNoCapture(sup, s);
   922                 return sup.tsym == s.tsym
   923                      // Check type variable containment
   924                     && (!s.isParameterized() || containsTypeRecursive(s, sup))
   925                     && isSubtypeNoCapture(sup.getEnclosingType(),
   926                                           s.getEnclosingType());
   927             }
   929             @Override
   930             public Boolean visitArrayType(ArrayType t, Type s) {
   931                 if (s.hasTag(ARRAY)) {
   932                     if (t.elemtype.isPrimitive())
   933                         return isSameType(t.elemtype, elemtype(s));
   934                     else
   935                         return isSubtypeNoCapture(t.elemtype, elemtype(s));
   936                 }
   938                 if (s.hasTag(CLASS)) {
   939                     Name sname = s.tsym.getQualifiedName();
   940                     return sname == names.java_lang_Object
   941                         || sname == names.java_lang_Cloneable
   942                         || sname == names.java_io_Serializable;
   943                 }
   945                 return false;
   946             }
   948             @Override
   949             public Boolean visitUndetVar(UndetVar t, Type s) {
   950                 //todo: test against origin needed? or replace with substitution?
   951                 if (t == s || t.qtype == s || s.hasTag(ERROR) || s.hasTag(UNKNOWN)) {
   952                     return true;
   953                 } else if (s.hasTag(BOT)) {
   954                     //if 's' is 'null' there's no instantiated type U for which
   955                     //U <: s (but 'null' itself, which is not a valid type)
   956                     return false;
   957                 }
   959                 t.addBound(InferenceBound.UPPER, s, Types.this);
   960                 return true;
   961             }
   963             @Override
   964             public Boolean visitErrorType(ErrorType t, Type s) {
   965                 return true;
   966             }
   967         };
   969     /**
   970      * Is t a subtype of every type in given list `ts'?<br>
   971      * (not defined for Method and ForAll types)<br>
   972      * Allows unchecked conversions.
   973      */
   974     public boolean isSubtypeUnchecked(Type t, List<Type> ts, Warner warn) {
   975         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
   976             if (!isSubtypeUnchecked(t, l.head, warn))
   977                 return false;
   978         return true;
   979     }
   981     /**
   982      * Are corresponding elements of ts subtypes of ss?  If lists are
   983      * of different length, return false.
   984      */
   985     public boolean isSubtypes(List<Type> ts, List<Type> ss) {
   986         while (ts.tail != null && ss.tail != null
   987                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   988                isSubtype(ts.head, ss.head)) {
   989             ts = ts.tail;
   990             ss = ss.tail;
   991         }
   992         return ts.tail == null && ss.tail == null;
   993         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   994     }
   996     /**
   997      * Are corresponding elements of ts subtypes of ss, allowing
   998      * unchecked conversions?  If lists are of different length,
   999      * return false.
  1000      **/
  1001     public boolean isSubtypesUnchecked(List<Type> ts, List<Type> ss, Warner warn) {
  1002         while (ts.tail != null && ss.tail != null
  1003                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
  1004                isSubtypeUnchecked(ts.head, ss.head, warn)) {
  1005             ts = ts.tail;
  1006             ss = ss.tail;
  1008         return ts.tail == null && ss.tail == null;
  1009         /*inlined: ts.isEmpty() && ss.isEmpty();*/
  1011     // </editor-fold>
  1013     // <editor-fold defaultstate="collapsed" desc="isSuperType">
  1014     /**
  1015      * Is t a supertype of s?
  1016      */
  1017     public boolean isSuperType(Type t, Type s) {
  1018         switch (t.getTag()) {
  1019         case ERROR:
  1020             return true;
  1021         case UNDETVAR: {
  1022             UndetVar undet = (UndetVar)t;
  1023             if (t == s ||
  1024                 undet.qtype == s ||
  1025                 s.hasTag(ERROR) ||
  1026                 s.hasTag(BOT)) {
  1027                 return true;
  1029             undet.addBound(InferenceBound.LOWER, s, this);
  1030             return true;
  1032         default:
  1033             return isSubtype(s, t);
  1036     // </editor-fold>
  1038     // <editor-fold defaultstate="collapsed" desc="isSameType">
  1039     /**
  1040      * Are corresponding elements of the lists the same type?  If
  1041      * lists are of different length, return false.
  1042      */
  1043     public boolean isSameTypes(List<Type> ts, List<Type> ss) {
  1044         return isSameTypes(ts, ss, false);
  1046     public boolean isSameTypes(List<Type> ts, List<Type> ss, boolean strict) {
  1047         while (ts.tail != null && ss.tail != null
  1048                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
  1049                isSameType(ts.head, ss.head, strict)) {
  1050             ts = ts.tail;
  1051             ss = ss.tail;
  1053         return ts.tail == null && ss.tail == null;
  1054         /*inlined: ts.isEmpty() && ss.isEmpty();*/
  1057     /**
  1058     * A polymorphic signature method (JLS SE 7, 8.4.1) is a method that
  1059     * (i) is declared in the java.lang.invoke.MethodHandle class, (ii) takes
  1060     * a single variable arity parameter (iii) whose declared type is Object[],
  1061     * (iv) has a return type of Object and (v) is native.
  1062     */
  1063    public boolean isSignaturePolymorphic(MethodSymbol msym) {
  1064        List<Type> argtypes = msym.type.getParameterTypes();
  1065        return (msym.flags_field & NATIVE) != 0 &&
  1066                msym.owner == syms.methodHandleType.tsym &&
  1067                argtypes.tail.tail == null &&
  1068                argtypes.head.hasTag(TypeTag.ARRAY) &&
  1069                msym.type.getReturnType().tsym == syms.objectType.tsym &&
  1070                ((ArrayType)argtypes.head).elemtype.tsym == syms.objectType.tsym;
  1073     /**
  1074      * Is t the same type as s?
  1075      */
  1076     public boolean isSameType(Type t, Type s) {
  1077         return isSameType(t, s, false);
  1079     public boolean isSameType(Type t, Type s, boolean strict) {
  1080         return strict ?
  1081                 isSameTypeStrict.visit(t, s) :
  1082                 isSameTypeLoose.visit(t, s);
  1084     public boolean isSameAnnotatedType(Type t, Type s) {
  1085         return isSameAnnotatedType.visit(t, s);
  1087     // where
  1088         abstract class SameTypeVisitor extends TypeRelation {
  1090             public Boolean visitType(Type t, Type s) {
  1091                 if (t == s)
  1092                     return true;
  1094                 if (s.isPartial())
  1095                     return visit(s, t);
  1097                 switch (t.getTag()) {
  1098                 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
  1099                 case DOUBLE: case BOOLEAN: case VOID: case BOT: case NONE:
  1100                     return t.hasTag(s.getTag());
  1101                 case TYPEVAR: {
  1102                     if (s.hasTag(TYPEVAR)) {
  1103                         //type-substitution does not preserve type-var types
  1104                         //check that type var symbols and bounds are indeed the same
  1105                         return sameTypeVars((TypeVar)t.unannotatedType(), (TypeVar)s.unannotatedType());
  1107                     else {
  1108                         //special case for s == ? super X, where upper(s) = u
  1109                         //check that u == t, where u has been set by Type.withTypeVar
  1110                         return s.isSuperBound() &&
  1111                                 !s.isExtendsBound() &&
  1112                                 visit(t, wildUpperBound(s));
  1115                 default:
  1116                     throw new AssertionError("isSameType " + t.getTag());
  1120             abstract boolean sameTypeVars(TypeVar tv1, TypeVar tv2);
  1122             @Override
  1123             public Boolean visitWildcardType(WildcardType t, Type s) {
  1124                 if (s.isPartial())
  1125                     return visit(s, t);
  1126                 else
  1127                     return false;
  1130             @Override
  1131             public Boolean visitClassType(ClassType t, Type s) {
  1132                 if (t == s)
  1133                     return true;
  1135                 if (s.isPartial())
  1136                     return visit(s, t);
  1138                 if (s.isSuperBound() && !s.isExtendsBound())
  1139                     return visit(t, wildUpperBound(s)) && visit(t, wildLowerBound(s));
  1141                 if (t.isCompound() && s.isCompound()) {
  1142                     if (!visit(supertype(t), supertype(s)))
  1143                         return false;
  1145                     HashSet<UniqueType> set = new HashSet<UniqueType>();
  1146                     for (Type x : interfaces(t))
  1147                         set.add(new UniqueType(x.unannotatedType(), Types.this));
  1148                     for (Type x : interfaces(s)) {
  1149                         if (!set.remove(new UniqueType(x.unannotatedType(), Types.this)))
  1150                             return false;
  1152                     return (set.isEmpty());
  1154                 return t.tsym == s.tsym
  1155                     && visit(t.getEnclosingType(), s.getEnclosingType())
  1156                     && containsTypes(t.getTypeArguments(), s.getTypeArguments());
  1159             abstract protected boolean containsTypes(List<Type> ts1, List<Type> ts2);
  1161             @Override
  1162             public Boolean visitArrayType(ArrayType t, Type s) {
  1163                 if (t == s)
  1164                     return true;
  1166                 if (s.isPartial())
  1167                     return visit(s, t);
  1169                 return s.hasTag(ARRAY)
  1170                     && containsTypeEquivalent(t.elemtype, elemtype(s));
  1173             @Override
  1174             public Boolean visitMethodType(MethodType t, Type s) {
  1175                 // isSameType for methods does not take thrown
  1176                 // exceptions into account!
  1177                 return hasSameArgs(t, s) && visit(t.getReturnType(), s.getReturnType());
  1180             @Override
  1181             public Boolean visitPackageType(PackageType t, Type s) {
  1182                 return t == s;
  1185             @Override
  1186             public Boolean visitForAll(ForAll t, Type s) {
  1187                 if (!s.hasTag(FORALL)) {
  1188                     return false;
  1191                 ForAll forAll = (ForAll)s;
  1192                 return hasSameBounds(t, forAll)
  1193                     && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
  1196             @Override
  1197             public Boolean visitUndetVar(UndetVar t, Type s) {
  1198                 if (s.hasTag(WILDCARD)) {
  1199                     // FIXME, this might be leftovers from before capture conversion
  1200                     return false;
  1203                 if (t == s || t.qtype == s || s.hasTag(ERROR) || s.hasTag(UNKNOWN)) {
  1204                     return true;
  1207                 t.addBound(InferenceBound.EQ, s, Types.this);
  1209                 return true;
  1212             @Override
  1213             public Boolean visitErrorType(ErrorType t, Type s) {
  1214                 return true;
  1218         /**
  1219          * Standard type-equality relation - type variables are considered
  1220          * equals if they share the same type symbol.
  1221          */
  1222         TypeRelation isSameTypeLoose = new LooseSameTypeVisitor();
  1224         private class LooseSameTypeVisitor extends SameTypeVisitor {
  1226             /** cache of the type-variable pairs being (recursively) tested. */
  1227             private Set<TypePair> cache = new HashSet<>();
  1229             @Override
  1230             boolean sameTypeVars(TypeVar tv1, TypeVar tv2) {
  1231                 return tv1.tsym == tv2.tsym && checkSameBounds(tv1, tv2);
  1233             @Override
  1234             protected boolean containsTypes(List<Type> ts1, List<Type> ts2) {
  1235                 return containsTypeEquivalent(ts1, ts2);
  1238             /**
  1239              * Since type-variable bounds can be recursive, we need to protect against
  1240              * infinite loops - where the same bounds are checked over and over recursively.
  1241              */
  1242             private boolean checkSameBounds(TypeVar tv1, TypeVar tv2) {
  1243                 TypePair p = new TypePair(tv1, tv2, true);
  1244                 if (cache.add(p)) {
  1245                     try {
  1246                         return visit(tv1.getUpperBound(), tv2.getUpperBound());
  1247                     } finally {
  1248                         cache.remove(p);
  1250                 } else {
  1251                     return false;
  1254         };
  1256         /**
  1257          * Strict type-equality relation - type variables are considered
  1258          * equals if they share the same object identity.
  1259          */
  1260         TypeRelation isSameTypeStrict = new SameTypeVisitor() {
  1261             @Override
  1262             boolean sameTypeVars(TypeVar tv1, TypeVar tv2) {
  1263                 return tv1 == tv2;
  1265             @Override
  1266             protected boolean containsTypes(List<Type> ts1, List<Type> ts2) {
  1267                 return isSameTypes(ts1, ts2, true);
  1270             @Override
  1271             public Boolean visitWildcardType(WildcardType t, Type s) {
  1272                 if (!s.hasTag(WILDCARD)) {
  1273                     return false;
  1274                 } else {
  1275                     WildcardType t2 = (WildcardType)s.unannotatedType();
  1276                     return t.kind == t2.kind &&
  1277                             isSameType(t.type, t2.type, true);
  1280         };
  1282         /**
  1283          * A version of LooseSameTypeVisitor that takes AnnotatedTypes
  1284          * into account.
  1285          */
  1286         TypeRelation isSameAnnotatedType = new LooseSameTypeVisitor() {
  1287             @Override
  1288             public Boolean visitAnnotatedType(AnnotatedType t, Type s) {
  1289                 if (!s.isAnnotated())
  1290                     return false;
  1291                 if (!t.getAnnotationMirrors().containsAll(s.getAnnotationMirrors()))
  1292                     return false;
  1293                 if (!s.getAnnotationMirrors().containsAll(t.getAnnotationMirrors()))
  1294                     return false;
  1295                 return visit(t.unannotatedType(), s);
  1297         };
  1298     // </editor-fold>
  1300     // <editor-fold defaultstate="collapsed" desc="Contains Type">
  1301     public boolean containedBy(Type t, Type s) {
  1302         switch (t.getTag()) {
  1303         case UNDETVAR:
  1304             if (s.hasTag(WILDCARD)) {
  1305                 UndetVar undetvar = (UndetVar)t;
  1306                 WildcardType wt = (WildcardType)s.unannotatedType();
  1307                 switch(wt.kind) {
  1308                     case UNBOUND: //similar to ? extends Object
  1309                     case EXTENDS: {
  1310                         Type bound = wildUpperBound(s);
  1311                         undetvar.addBound(InferenceBound.UPPER, bound, this);
  1312                         break;
  1314                     case SUPER: {
  1315                         Type bound = wildLowerBound(s);
  1316                         undetvar.addBound(InferenceBound.LOWER, bound, this);
  1317                         break;
  1320                 return true;
  1321             } else {
  1322                 return isSameType(t, s);
  1324         case ERROR:
  1325             return true;
  1326         default:
  1327             return containsType(s, t);
  1331     boolean containsType(List<Type> ts, List<Type> ss) {
  1332         while (ts.nonEmpty() && ss.nonEmpty()
  1333                && containsType(ts.head, ss.head)) {
  1334             ts = ts.tail;
  1335             ss = ss.tail;
  1337         return ts.isEmpty() && ss.isEmpty();
  1340     /**
  1341      * Check if t contains s.
  1343      * <p>T contains S if:
  1345      * <p>{@code L(T) <: L(S) && U(S) <: U(T)}
  1347      * <p>This relation is only used by ClassType.isSubtype(), that
  1348      * is,
  1350      * <p>{@code C<S> <: C<T> if T contains S.}
  1352      * <p>Because of F-bounds, this relation can lead to infinite
  1353      * recursion.  Thus we must somehow break that recursion.  Notice
  1354      * that containsType() is only called from ClassType.isSubtype().
  1355      * Since the arguments have already been checked against their
  1356      * bounds, we know:
  1358      * <p>{@code U(S) <: U(T) if T is "super" bound (U(T) *is* the bound)}
  1360      * <p>{@code L(T) <: L(S) if T is "extends" bound (L(T) is bottom)}
  1362      * @param t a type
  1363      * @param s a type
  1364      */
  1365     public boolean containsType(Type t, Type s) {
  1366         return containsType.visit(t, s);
  1368     // where
  1369         private TypeRelation containsType = new TypeRelation() {
  1371             public Boolean visitType(Type t, Type s) {
  1372                 if (s.isPartial())
  1373                     return containedBy(s, t);
  1374                 else
  1375                     return isSameType(t, s);
  1378 //            void debugContainsType(WildcardType t, Type s) {
  1379 //                System.err.println();
  1380 //                System.err.format(" does %s contain %s?%n", t, s);
  1381 //                System.err.format(" %s U(%s) <: U(%s) %s = %s%n",
  1382 //                                  wildUpperBound(s), s, t, wildUpperBound(t),
  1383 //                                  t.isSuperBound()
  1384 //                                  || isSubtypeNoCapture(wildUpperBound(s), wildUpperBound(t)));
  1385 //                System.err.format(" %s L(%s) <: L(%s) %s = %s%n",
  1386 //                                  wildLowerBound(t), t, s, wildLowerBound(s),
  1387 //                                  t.isExtendsBound()
  1388 //                                  || isSubtypeNoCapture(wildLowerBound(t), wildLowerBound(s)));
  1389 //                System.err.println();
  1390 //            }
  1392             @Override
  1393             public Boolean visitWildcardType(WildcardType t, Type s) {
  1394                 if (s.isPartial())
  1395                     return containedBy(s, t);
  1396                 else {
  1397 //                    debugContainsType(t, s);
  1398                     return isSameWildcard(t, s)
  1399                         || isCaptureOf(s, t)
  1400                         || ((t.isExtendsBound() || isSubtypeNoCapture(wildLowerBound(t), cvarLowerBound(wildLowerBound(s)))) &&
  1401                             // TODO: JDK-8039214, cvarUpperBound call here is incorrect
  1402                             (t.isSuperBound() || isSubtypeNoCapture(cvarUpperBound(wildUpperBound(s)), wildUpperBound(t))));
  1406             @Override
  1407             public Boolean visitUndetVar(UndetVar t, Type s) {
  1408                 if (!s.hasTag(WILDCARD)) {
  1409                     return isSameType(t, s);
  1410                 } else {
  1411                     return false;
  1415             @Override
  1416             public Boolean visitErrorType(ErrorType t, Type s) {
  1417                 return true;
  1419         };
  1421     public boolean isCaptureOf(Type s, WildcardType t) {
  1422         if (!s.hasTag(TYPEVAR) || !((TypeVar)s.unannotatedType()).isCaptured())
  1423             return false;
  1424         return isSameWildcard(t, ((CapturedType)s.unannotatedType()).wildcard);
  1427     public boolean isSameWildcard(WildcardType t, Type s) {
  1428         if (!s.hasTag(WILDCARD))
  1429             return false;
  1430         WildcardType w = (WildcardType)s.unannotatedType();
  1431         return w.kind == t.kind && w.type == t.type;
  1434     public boolean containsTypeEquivalent(List<Type> ts, List<Type> ss) {
  1435         while (ts.nonEmpty() && ss.nonEmpty()
  1436                && containsTypeEquivalent(ts.head, ss.head)) {
  1437             ts = ts.tail;
  1438             ss = ss.tail;
  1440         return ts.isEmpty() && ss.isEmpty();
  1442     // </editor-fold>
  1444     /**
  1445      * Can t and s be compared for equality?  Any primitive ==
  1446      * primitive or primitive == object comparisons here are an error.
  1447      * Unboxing and correct primitive == primitive comparisons are
  1448      * already dealt with in Attr.visitBinary.
  1450      */
  1451     public boolean isEqualityComparable(Type s, Type t, Warner warn) {
  1452         if (t.isNumeric() && s.isNumeric())
  1453             return true;
  1455         boolean tPrimitive = t.isPrimitive();
  1456         boolean sPrimitive = s.isPrimitive();
  1457         if (!tPrimitive && !sPrimitive) {
  1458             return isCastable(s, t, warn) || isCastable(t, s, warn);
  1459         } else {
  1460             return false;
  1464     // <editor-fold defaultstate="collapsed" desc="isCastable">
  1465     public boolean isCastable(Type t, Type s) {
  1466         return isCastable(t, s, noWarnings);
  1469     /**
  1470      * Is t is castable to s?<br>
  1471      * s is assumed to be an erased type.<br>
  1472      * (not defined for Method and ForAll types).
  1473      */
  1474     public boolean isCastable(Type t, Type s, Warner warn) {
  1475         if (t == s)
  1476             return true;
  1478         if (t.isPrimitive() != s.isPrimitive())
  1479             return allowBoxing && (
  1480                     isConvertible(t, s, warn)
  1481                     || (allowObjectToPrimitiveCast &&
  1482                         s.isPrimitive() &&
  1483                         isSubtype(boxedClass(s).type, t)));
  1484         if (warn != warnStack.head) {
  1485             try {
  1486                 warnStack = warnStack.prepend(warn);
  1487                 checkUnsafeVarargsConversion(t, s, warn);
  1488                 return isCastable.visit(t,s);
  1489             } finally {
  1490                 warnStack = warnStack.tail;
  1492         } else {
  1493             return isCastable.visit(t,s);
  1496     // where
  1497         private TypeRelation isCastable = new TypeRelation() {
  1499             public Boolean visitType(Type t, Type s) {
  1500                 if (s.hasTag(ERROR))
  1501                     return true;
  1503                 switch (t.getTag()) {
  1504                 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
  1505                 case DOUBLE:
  1506                     return s.isNumeric();
  1507                 case BOOLEAN:
  1508                     return s.hasTag(BOOLEAN);
  1509                 case VOID:
  1510                     return false;
  1511                 case BOT:
  1512                     return isSubtype(t, s);
  1513                 default:
  1514                     throw new AssertionError();
  1518             @Override
  1519             public Boolean visitWildcardType(WildcardType t, Type s) {
  1520                 return isCastable(wildUpperBound(t), s, warnStack.head);
  1523             @Override
  1524             public Boolean visitClassType(ClassType t, Type s) {
  1525                 if (s.hasTag(ERROR) || s.hasTag(BOT))
  1526                     return true;
  1528                 if (s.hasTag(TYPEVAR)) {
  1529                     if (isCastable(t, s.getUpperBound(), noWarnings)) {
  1530                         warnStack.head.warn(LintCategory.UNCHECKED);
  1531                         return true;
  1532                     } else {
  1533                         return false;
  1537                 if (t.isCompound() || s.isCompound()) {
  1538                     return !t.isCompound() ?
  1539                             visitIntersectionType((IntersectionClassType)s.unannotatedType(), t, true) :
  1540                             visitIntersectionType((IntersectionClassType)t.unannotatedType(), s, false);
  1543                 if (s.hasTag(CLASS) || s.hasTag(ARRAY)) {
  1544                     boolean upcast;
  1545                     if ((upcast = isSubtype(erasure(t), erasure(s)))
  1546                         || isSubtype(erasure(s), erasure(t))) {
  1547                         if (!upcast && s.hasTag(ARRAY)) {
  1548                             if (!isReifiable(s))
  1549                                 warnStack.head.warn(LintCategory.UNCHECKED);
  1550                             return true;
  1551                         } else if (s.isRaw()) {
  1552                             return true;
  1553                         } else if (t.isRaw()) {
  1554                             if (!isUnbounded(s))
  1555                                 warnStack.head.warn(LintCategory.UNCHECKED);
  1556                             return true;
  1558                         // Assume |a| <: |b|
  1559                         final Type a = upcast ? t : s;
  1560                         final Type b = upcast ? s : t;
  1561                         final boolean HIGH = true;
  1562                         final boolean LOW = false;
  1563                         final boolean DONT_REWRITE_TYPEVARS = false;
  1564                         Type aHigh = rewriteQuantifiers(a, HIGH, DONT_REWRITE_TYPEVARS);
  1565                         Type aLow  = rewriteQuantifiers(a, LOW,  DONT_REWRITE_TYPEVARS);
  1566                         Type bHigh = rewriteQuantifiers(b, HIGH, DONT_REWRITE_TYPEVARS);
  1567                         Type bLow  = rewriteQuantifiers(b, LOW,  DONT_REWRITE_TYPEVARS);
  1568                         Type lowSub = asSub(bLow, aLow.tsym);
  1569                         Type highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
  1570                         if (highSub == null) {
  1571                             final boolean REWRITE_TYPEVARS = true;
  1572                             aHigh = rewriteQuantifiers(a, HIGH, REWRITE_TYPEVARS);
  1573                             aLow  = rewriteQuantifiers(a, LOW,  REWRITE_TYPEVARS);
  1574                             bHigh = rewriteQuantifiers(b, HIGH, REWRITE_TYPEVARS);
  1575                             bLow  = rewriteQuantifiers(b, LOW,  REWRITE_TYPEVARS);
  1576                             lowSub = asSub(bLow, aLow.tsym);
  1577                             highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
  1579                         if (highSub != null) {
  1580                             if (!(a.tsym == highSub.tsym && a.tsym == lowSub.tsym)) {
  1581                                 Assert.error(a.tsym + " != " + highSub.tsym + " != " + lowSub.tsym);
  1583                             if (!disjointTypes(aHigh.allparams(), highSub.allparams())
  1584                                 && !disjointTypes(aHigh.allparams(), lowSub.allparams())
  1585                                 && !disjointTypes(aLow.allparams(), highSub.allparams())
  1586                                 && !disjointTypes(aLow.allparams(), lowSub.allparams())) {
  1587                                 if (upcast ? giveWarning(a, b) :
  1588                                     giveWarning(b, a))
  1589                                     warnStack.head.warn(LintCategory.UNCHECKED);
  1590                                 return true;
  1593                         if (isReifiable(s))
  1594                             return isSubtypeUnchecked(a, b);
  1595                         else
  1596                             return isSubtypeUnchecked(a, b, warnStack.head);
  1599                     // Sidecast
  1600                     if (s.hasTag(CLASS)) {
  1601                         if ((s.tsym.flags() & INTERFACE) != 0) {
  1602                             return ((t.tsym.flags() & FINAL) == 0)
  1603                                 ? sideCast(t, s, warnStack.head)
  1604                                 : sideCastFinal(t, s, warnStack.head);
  1605                         } else if ((t.tsym.flags() & INTERFACE) != 0) {
  1606                             return ((s.tsym.flags() & FINAL) == 0)
  1607                                 ? sideCast(t, s, warnStack.head)
  1608                                 : sideCastFinal(t, s, warnStack.head);
  1609                         } else {
  1610                             // unrelated class types
  1611                             return false;
  1615                 return false;
  1618             boolean visitIntersectionType(IntersectionClassType ict, Type s, boolean reverse) {
  1619                 Warner warn = noWarnings;
  1620                 for (Type c : ict.getComponents()) {
  1621                     warn.clear();
  1622                     if (reverse ? !isCastable(s, c, warn) : !isCastable(c, s, warn))
  1623                         return false;
  1625                 if (warn.hasLint(LintCategory.UNCHECKED))
  1626                     warnStack.head.warn(LintCategory.UNCHECKED);
  1627                 return true;
  1630             @Override
  1631             public Boolean visitArrayType(ArrayType t, Type s) {
  1632                 switch (s.getTag()) {
  1633                 case ERROR:
  1634                 case BOT:
  1635                     return true;
  1636                 case TYPEVAR:
  1637                     if (isCastable(s, t, noWarnings)) {
  1638                         warnStack.head.warn(LintCategory.UNCHECKED);
  1639                         return true;
  1640                     } else {
  1641                         return false;
  1643                 case CLASS:
  1644                     return isSubtype(t, s);
  1645                 case ARRAY:
  1646                     if (elemtype(t).isPrimitive() || elemtype(s).isPrimitive()) {
  1647                         return elemtype(t).hasTag(elemtype(s).getTag());
  1648                     } else {
  1649                         return visit(elemtype(t), elemtype(s));
  1651                 default:
  1652                     return false;
  1656             @Override
  1657             public Boolean visitTypeVar(TypeVar t, Type s) {
  1658                 switch (s.getTag()) {
  1659                 case ERROR:
  1660                 case BOT:
  1661                     return true;
  1662                 case TYPEVAR:
  1663                     if (isSubtype(t, s)) {
  1664                         return true;
  1665                     } else if (isCastable(t.bound, s, noWarnings)) {
  1666                         warnStack.head.warn(LintCategory.UNCHECKED);
  1667                         return true;
  1668                     } else {
  1669                         return false;
  1671                 default:
  1672                     return isCastable(t.bound, s, warnStack.head);
  1676             @Override
  1677             public Boolean visitErrorType(ErrorType t, Type s) {
  1678                 return true;
  1680         };
  1681     // </editor-fold>
  1683     // <editor-fold defaultstate="collapsed" desc="disjointTypes">
  1684     public boolean disjointTypes(List<Type> ts, List<Type> ss) {
  1685         while (ts.tail != null && ss.tail != null) {
  1686             if (disjointType(ts.head, ss.head)) return true;
  1687             ts = ts.tail;
  1688             ss = ss.tail;
  1690         return false;
  1693     /**
  1694      * Two types or wildcards are considered disjoint if it can be
  1695      * proven that no type can be contained in both. It is
  1696      * conservative in that it is allowed to say that two types are
  1697      * not disjoint, even though they actually are.
  1699      * The type {@code C<X>} is castable to {@code C<Y>} exactly if
  1700      * {@code X} and {@code Y} are not disjoint.
  1701      */
  1702     public boolean disjointType(Type t, Type s) {
  1703         return disjointType.visit(t, s);
  1705     // where
  1706         private TypeRelation disjointType = new TypeRelation() {
  1708             private Set<TypePair> cache = new HashSet<TypePair>();
  1710             @Override
  1711             public Boolean visitType(Type t, Type s) {
  1712                 if (s.hasTag(WILDCARD))
  1713                     return visit(s, t);
  1714                 else
  1715                     return notSoftSubtypeRecursive(t, s) || notSoftSubtypeRecursive(s, t);
  1718             private boolean isCastableRecursive(Type t, Type s) {
  1719                 TypePair pair = new TypePair(t, s);
  1720                 if (cache.add(pair)) {
  1721                     try {
  1722                         return Types.this.isCastable(t, s);
  1723                     } finally {
  1724                         cache.remove(pair);
  1726                 } else {
  1727                     return true;
  1731             private boolean notSoftSubtypeRecursive(Type t, Type s) {
  1732                 TypePair pair = new TypePair(t, s);
  1733                 if (cache.add(pair)) {
  1734                     try {
  1735                         return Types.this.notSoftSubtype(t, s);
  1736                     } finally {
  1737                         cache.remove(pair);
  1739                 } else {
  1740                     return false;
  1744             @Override
  1745             public Boolean visitWildcardType(WildcardType t, Type s) {
  1746                 if (t.isUnbound())
  1747                     return false;
  1749                 if (!s.hasTag(WILDCARD)) {
  1750                     if (t.isExtendsBound())
  1751                         return notSoftSubtypeRecursive(s, t.type);
  1752                     else
  1753                         return notSoftSubtypeRecursive(t.type, s);
  1756                 if (s.isUnbound())
  1757                     return false;
  1759                 if (t.isExtendsBound()) {
  1760                     if (s.isExtendsBound())
  1761                         return !isCastableRecursive(t.type, wildUpperBound(s));
  1762                     else if (s.isSuperBound())
  1763                         return notSoftSubtypeRecursive(wildLowerBound(s), t.type);
  1764                 } else if (t.isSuperBound()) {
  1765                     if (s.isExtendsBound())
  1766                         return notSoftSubtypeRecursive(t.type, wildUpperBound(s));
  1768                 return false;
  1770         };
  1771     // </editor-fold>
  1773     // <editor-fold defaultstate="collapsed" desc="cvarLowerBounds">
  1774     public List<Type> cvarLowerBounds(List<Type> ts) {
  1775         return map(ts, cvarLowerBoundMapping);
  1777     private final Mapping cvarLowerBoundMapping = new Mapping("cvarLowerBound") {
  1778             public Type apply(Type t) {
  1779                 return cvarLowerBound(t);
  1781         };
  1782     // </editor-fold>
  1784     // <editor-fold defaultstate="collapsed" desc="notSoftSubtype">
  1785     /**
  1786      * This relation answers the question: is impossible that
  1787      * something of type `t' can be a subtype of `s'? This is
  1788      * different from the question "is `t' not a subtype of `s'?"
  1789      * when type variables are involved: Integer is not a subtype of T
  1790      * where {@code <T extends Number>} but it is not true that Integer cannot
  1791      * possibly be a subtype of T.
  1792      */
  1793     public boolean notSoftSubtype(Type t, Type s) {
  1794         if (t == s) return false;
  1795         if (t.hasTag(TYPEVAR)) {
  1796             TypeVar tv = (TypeVar) t;
  1797             return !isCastable(tv.bound,
  1798                                relaxBound(s),
  1799                                noWarnings);
  1801         if (!s.hasTag(WILDCARD))
  1802             s = cvarUpperBound(s);
  1804         return !isSubtype(t, relaxBound(s));
  1807     private Type relaxBound(Type t) {
  1808         if (t.hasTag(TYPEVAR)) {
  1809             while (t.hasTag(TYPEVAR))
  1810                 t = t.getUpperBound();
  1811             t = rewriteQuantifiers(t, true, true);
  1813         return t;
  1815     // </editor-fold>
  1817     // <editor-fold defaultstate="collapsed" desc="isReifiable">
  1818     public boolean isReifiable(Type t) {
  1819         return isReifiable.visit(t);
  1821     // where
  1822         private UnaryVisitor<Boolean> isReifiable = new UnaryVisitor<Boolean>() {
  1824             public Boolean visitType(Type t, Void ignored) {
  1825                 return true;
  1828             @Override
  1829             public Boolean visitClassType(ClassType t, Void ignored) {
  1830                 if (t.isCompound())
  1831                     return false;
  1832                 else {
  1833                     if (!t.isParameterized())
  1834                         return true;
  1836                     for (Type param : t.allparams()) {
  1837                         if (!param.isUnbound())
  1838                             return false;
  1840                     return true;
  1844             @Override
  1845             public Boolean visitArrayType(ArrayType t, Void ignored) {
  1846                 return visit(t.elemtype);
  1849             @Override
  1850             public Boolean visitTypeVar(TypeVar t, Void ignored) {
  1851                 return false;
  1853         };
  1854     // </editor-fold>
  1856     // <editor-fold defaultstate="collapsed" desc="Array Utils">
  1857     public boolean isArray(Type t) {
  1858         while (t.hasTag(WILDCARD))
  1859             t = wildUpperBound(t);
  1860         return t.hasTag(ARRAY);
  1863     /**
  1864      * The element type of an array.
  1865      */
  1866     public Type elemtype(Type t) {
  1867         switch (t.getTag()) {
  1868         case WILDCARD:
  1869             return elemtype(wildUpperBound(t));
  1870         case ARRAY:
  1871             t = t.unannotatedType();
  1872             return ((ArrayType)t).elemtype;
  1873         case FORALL:
  1874             return elemtype(((ForAll)t).qtype);
  1875         case ERROR:
  1876             return t;
  1877         default:
  1878             return null;
  1882     public Type elemtypeOrType(Type t) {
  1883         Type elemtype = elemtype(t);
  1884         return elemtype != null ?
  1885             elemtype :
  1886             t;
  1889     /**
  1890      * Mapping to take element type of an arraytype
  1891      */
  1892     private Mapping elemTypeFun = new Mapping ("elemTypeFun") {
  1893         public Type apply(Type t) { return elemtype(t); }
  1894     };
  1896     /**
  1897      * The number of dimensions of an array type.
  1898      */
  1899     public int dimensions(Type t) {
  1900         int result = 0;
  1901         while (t.hasTag(ARRAY)) {
  1902             result++;
  1903             t = elemtype(t);
  1905         return result;
  1908     /**
  1909      * Returns an ArrayType with the component type t
  1911      * @param t The component type of the ArrayType
  1912      * @return the ArrayType for the given component
  1913      */
  1914     public ArrayType makeArrayType(Type t) {
  1915         if (t.hasTag(VOID) || t.hasTag(PACKAGE)) {
  1916             Assert.error("Type t must not be a VOID or PACKAGE type, " + t.toString());
  1918         return new ArrayType(t, syms.arrayClass);
  1920     // </editor-fold>
  1922     // <editor-fold defaultstate="collapsed" desc="asSuper">
  1923     /**
  1924      * Return the (most specific) base type of t that starts with the
  1925      * given symbol.  If none exists, return null.
  1927      * @param t a type
  1928      * @param sym a symbol
  1929      */
  1930     public Type asSuper(Type t, Symbol sym) {
  1931         /* Some examples:
  1933          * (Enum<E>, Comparable) => Comparable<E>
  1934          * (c.s.s.d.AttributeTree.ValueKind, Enum) => Enum<c.s.s.d.AttributeTree.ValueKind>
  1935          * (c.s.s.t.ExpressionTree, c.s.s.t.Tree) => c.s.s.t.Tree
  1936          * (j.u.List<capture#160 of ? extends c.s.s.d.DocTree>, Iterable) =>
  1937          *     Iterable<capture#160 of ? extends c.s.s.d.DocTree>
  1938          */
  1939         if (sym.type == syms.objectType) { //optimization
  1940             return syms.objectType;
  1942         return asSuper.visit(t, sym);
  1944     // where
  1945         private SimpleVisitor<Type,Symbol> asSuper = new SimpleVisitor<Type,Symbol>() {
  1947             public Type visitType(Type t, Symbol sym) {
  1948                 return null;
  1951             @Override
  1952             public Type visitClassType(ClassType t, Symbol sym) {
  1953                 if (t.tsym == sym)
  1954                     return t;
  1956                 Type st = supertype(t);
  1957                 if (st.hasTag(CLASS) || st.hasTag(TYPEVAR)) {
  1958                     Type x = asSuper(st, sym);
  1959                     if (x != null)
  1960                         return x;
  1962                 if ((sym.flags() & INTERFACE) != 0) {
  1963                     for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
  1964                         if (!l.head.hasTag(ERROR)) {
  1965                             Type x = asSuper(l.head, sym);
  1966                             if (x != null)
  1967                                 return x;
  1971                 return null;
  1974             @Override
  1975             public Type visitArrayType(ArrayType t, Symbol sym) {
  1976                 return isSubtype(t, sym.type) ? sym.type : null;
  1979             @Override
  1980             public Type visitTypeVar(TypeVar t, Symbol sym) {
  1981                 if (t.tsym == sym)
  1982                     return t;
  1983                 else
  1984                     return asSuper(t.bound, sym);
  1987             @Override
  1988             public Type visitErrorType(ErrorType t, Symbol sym) {
  1989                 return t;
  1991         };
  1993     /**
  1994      * Return the base type of t or any of its outer types that starts
  1995      * with the given symbol.  If none exists, return null.
  1997      * @param t a type
  1998      * @param sym a symbol
  1999      */
  2000     public Type asOuterSuper(Type t, Symbol sym) {
  2001         switch (t.getTag()) {
  2002         case CLASS:
  2003             do {
  2004                 Type s = asSuper(t, sym);
  2005                 if (s != null) return s;
  2006                 t = t.getEnclosingType();
  2007             } while (t.hasTag(CLASS));
  2008             return null;
  2009         case ARRAY:
  2010             return isSubtype(t, sym.type) ? sym.type : null;
  2011         case TYPEVAR:
  2012             return asSuper(t, sym);
  2013         case ERROR:
  2014             return t;
  2015         default:
  2016             return null;
  2020     /**
  2021      * Return the base type of t or any of its enclosing types that
  2022      * starts with the given symbol.  If none exists, return null.
  2024      * @param t a type
  2025      * @param sym a symbol
  2026      */
  2027     public Type asEnclosingSuper(Type t, Symbol sym) {
  2028         switch (t.getTag()) {
  2029         case CLASS:
  2030             do {
  2031                 Type s = asSuper(t, sym);
  2032                 if (s != null) return s;
  2033                 Type outer = t.getEnclosingType();
  2034                 t = (outer.hasTag(CLASS)) ? outer :
  2035                     (t.tsym.owner.enclClass() != null) ? t.tsym.owner.enclClass().type :
  2036                     Type.noType;
  2037             } while (t.hasTag(CLASS));
  2038             return null;
  2039         case ARRAY:
  2040             return isSubtype(t, sym.type) ? sym.type : null;
  2041         case TYPEVAR:
  2042             return asSuper(t, sym);
  2043         case ERROR:
  2044             return t;
  2045         default:
  2046             return null;
  2049     // </editor-fold>
  2051     // <editor-fold defaultstate="collapsed" desc="memberType">
  2052     /**
  2053      * The type of given symbol, seen as a member of t.
  2055      * @param t a type
  2056      * @param sym a symbol
  2057      */
  2058     public Type memberType(Type t, Symbol sym) {
  2059         return (sym.flags() & STATIC) != 0
  2060             ? sym.type
  2061             : memberType.visit(t, sym);
  2063     // where
  2064         private SimpleVisitor<Type,Symbol> memberType = new SimpleVisitor<Type,Symbol>() {
  2066             public Type visitType(Type t, Symbol sym) {
  2067                 return sym.type;
  2070             @Override
  2071             public Type visitWildcardType(WildcardType t, Symbol sym) {
  2072                 return memberType(wildUpperBound(t), sym);
  2075             @Override
  2076             public Type visitClassType(ClassType t, Symbol sym) {
  2077                 Symbol owner = sym.owner;
  2078                 long flags = sym.flags();
  2079                 if (((flags & STATIC) == 0) && owner.type.isParameterized()) {
  2080                     Type base = asOuterSuper(t, owner);
  2081                     //if t is an intersection type T = CT & I1 & I2 ... & In
  2082                     //its supertypes CT, I1, ... In might contain wildcards
  2083                     //so we need to go through capture conversion
  2084                     base = t.isCompound() ? capture(base) : base;
  2085                     if (base != null) {
  2086                         List<Type> ownerParams = owner.type.allparams();
  2087                         List<Type> baseParams = base.allparams();
  2088                         if (ownerParams.nonEmpty()) {
  2089                             if (baseParams.isEmpty()) {
  2090                                 // then base is a raw type
  2091                                 return erasure(sym.type);
  2092                             } else {
  2093                                 return subst(sym.type, ownerParams, baseParams);
  2098                 return sym.type;
  2101             @Override
  2102             public Type visitTypeVar(TypeVar t, Symbol sym) {
  2103                 return memberType(t.bound, sym);
  2106             @Override
  2107             public Type visitErrorType(ErrorType t, Symbol sym) {
  2108                 return t;
  2110         };
  2111     // </editor-fold>
  2113     // <editor-fold defaultstate="collapsed" desc="isAssignable">
  2114     public boolean isAssignable(Type t, Type s) {
  2115         return isAssignable(t, s, noWarnings);
  2118     /**
  2119      * Is t assignable to s?<br>
  2120      * Equivalent to subtype except for constant values and raw
  2121      * types.<br>
  2122      * (not defined for Method and ForAll types)
  2123      */
  2124     public boolean isAssignable(Type t, Type s, Warner warn) {
  2125         if (t.hasTag(ERROR))
  2126             return true;
  2127         if (t.getTag().isSubRangeOf(INT) && t.constValue() != null) {
  2128             int value = ((Number)t.constValue()).intValue();
  2129             switch (s.getTag()) {
  2130             case BYTE:
  2131                 if (Byte.MIN_VALUE <= value && value <= Byte.MAX_VALUE)
  2132                     return true;
  2133                 break;
  2134             case CHAR:
  2135                 if (Character.MIN_VALUE <= value && value <= Character.MAX_VALUE)
  2136                     return true;
  2137                 break;
  2138             case SHORT:
  2139                 if (Short.MIN_VALUE <= value && value <= Short.MAX_VALUE)
  2140                     return true;
  2141                 break;
  2142             case INT:
  2143                 return true;
  2144             case CLASS:
  2145                 switch (unboxedType(s).getTag()) {
  2146                 case BYTE:
  2147                 case CHAR:
  2148                 case SHORT:
  2149                     return isAssignable(t, unboxedType(s), warn);
  2151                 break;
  2154         return isConvertible(t, s, warn);
  2156     // </editor-fold>
  2158     // <editor-fold defaultstate="collapsed" desc="erasure">
  2159     /**
  2160      * The erasure of t {@code |t|} -- the type that results when all
  2161      * type parameters in t are deleted.
  2162      */
  2163     public Type erasure(Type t) {
  2164         return eraseNotNeeded(t)? t : erasure(t, false);
  2166     //where
  2167     private boolean eraseNotNeeded(Type t) {
  2168         // We don't want to erase primitive types and String type as that
  2169         // operation is idempotent. Also, erasing these could result in loss
  2170         // of information such as constant values attached to such types.
  2171         return (t.isPrimitive()) || (syms.stringType.tsym == t.tsym);
  2174     private Type erasure(Type t, boolean recurse) {
  2175         if (t.isPrimitive())
  2176             return t; /* fast special case */
  2177         else
  2178             return erasure.visit(t, recurse);
  2180     // where
  2181         private SimpleVisitor<Type, Boolean> erasure = new SimpleVisitor<Type, Boolean>() {
  2182             public Type visitType(Type t, Boolean recurse) {
  2183                 if (t.isPrimitive())
  2184                     return t; /*fast special case*/
  2185                 else
  2186                     return t.map(recurse ? erasureRecFun : erasureFun);
  2189             @Override
  2190             public Type visitWildcardType(WildcardType t, Boolean recurse) {
  2191                 return erasure(wildUpperBound(t), recurse);
  2194             @Override
  2195             public Type visitClassType(ClassType t, Boolean recurse) {
  2196                 Type erased = t.tsym.erasure(Types.this);
  2197                 if (recurse) {
  2198                     erased = new ErasedClassType(erased.getEnclosingType(),erased.tsym);
  2200                 return erased;
  2203             @Override
  2204             public Type visitTypeVar(TypeVar t, Boolean recurse) {
  2205                 return erasure(t.bound, recurse);
  2208             @Override
  2209             public Type visitErrorType(ErrorType t, Boolean recurse) {
  2210                 return t;
  2213             @Override
  2214             public Type visitAnnotatedType(AnnotatedType t, Boolean recurse) {
  2215                 Type erased = erasure(t.unannotatedType(), recurse);
  2216                 if (erased.isAnnotated()) {
  2217                     // This can only happen when the underlying type is a
  2218                     // type variable and the upper bound of it is annotated.
  2219                     // The annotation on the type variable overrides the one
  2220                     // on the bound.
  2221                     erased = ((AnnotatedType)erased).unannotatedType();
  2223                 return erased.annotatedType(t.getAnnotationMirrors());
  2225         };
  2227     private Mapping erasureFun = new Mapping ("erasure") {
  2228             public Type apply(Type t) { return erasure(t); }
  2229         };
  2231     private Mapping erasureRecFun = new Mapping ("erasureRecursive") {
  2232         public Type apply(Type t) { return erasureRecursive(t); }
  2233     };
  2235     public List<Type> erasure(List<Type> ts) {
  2236         return Type.map(ts, erasureFun);
  2239     public Type erasureRecursive(Type t) {
  2240         return erasure(t, true);
  2243     public List<Type> erasureRecursive(List<Type> ts) {
  2244         return Type.map(ts, erasureRecFun);
  2246     // </editor-fold>
  2248     // <editor-fold defaultstate="collapsed" desc="makeCompoundType">
  2249     /**
  2250      * Make a compound type from non-empty list of types.  The list should be
  2251      * ordered according to {@link Symbol#precedes(TypeSymbol,Types)}.
  2253      * @param bounds            the types from which the compound type is formed
  2254      * @param supertype         is objectType if all bounds are interfaces,
  2255      *                          null otherwise.
  2256      */
  2257     public Type makeCompoundType(List<Type> bounds) {
  2258         return makeCompoundType(bounds, bounds.head.tsym.isInterface());
  2260     public Type makeCompoundType(List<Type> bounds, boolean allInterfaces) {
  2261         Assert.check(bounds.nonEmpty());
  2262         Type firstExplicitBound = bounds.head;
  2263         if (allInterfaces) {
  2264             bounds = bounds.prepend(syms.objectType);
  2266         ClassSymbol bc =
  2267             new ClassSymbol(ABSTRACT|PUBLIC|SYNTHETIC|COMPOUND|ACYCLIC,
  2268                             Type.moreInfo
  2269                                 ? names.fromString(bounds.toString())
  2270                                 : names.empty,
  2271                             null,
  2272                             syms.noSymbol);
  2273         bc.type = new IntersectionClassType(bounds, bc, allInterfaces);
  2274         bc.erasure_field = (bounds.head.hasTag(TYPEVAR)) ?
  2275                 syms.objectType : // error condition, recover
  2276                 erasure(firstExplicitBound);
  2277         bc.members_field = new Scope(bc);
  2278         return bc.type;
  2281     /**
  2282      * A convenience wrapper for {@link #makeCompoundType(List)}; the
  2283      * arguments are converted to a list and passed to the other
  2284      * method.  Note that this might cause a symbol completion.
  2285      * Hence, this version of makeCompoundType may not be called
  2286      * during a classfile read.
  2287      */
  2288     public Type makeCompoundType(Type bound1, Type bound2) {
  2289         return makeCompoundType(List.of(bound1, bound2));
  2291     // </editor-fold>
  2293     // <editor-fold defaultstate="collapsed" desc="supertype">
  2294     public Type supertype(Type t) {
  2295         return supertype.visit(t);
  2297     // where
  2298         private UnaryVisitor<Type> supertype = new UnaryVisitor<Type>() {
  2300             public Type visitType(Type t, Void ignored) {
  2301                 // A note on wildcards: there is no good way to
  2302                 // determine a supertype for a super bounded wildcard.
  2303                 return Type.noType;
  2306             @Override
  2307             public Type visitClassType(ClassType t, Void ignored) {
  2308                 if (t.supertype_field == null) {
  2309                     Type supertype = ((ClassSymbol)t.tsym).getSuperclass();
  2310                     // An interface has no superclass; its supertype is Object.
  2311                     if (t.isInterface())
  2312                         supertype = ((ClassType)t.tsym.type).supertype_field;
  2313                     if (t.supertype_field == null) {
  2314                         List<Type> actuals = classBound(t).allparams();
  2315                         List<Type> formals = t.tsym.type.allparams();
  2316                         if (t.hasErasedSupertypes()) {
  2317                             t.supertype_field = erasureRecursive(supertype);
  2318                         } else if (formals.nonEmpty()) {
  2319                             t.supertype_field = subst(supertype, formals, actuals);
  2321                         else {
  2322                             t.supertype_field = supertype;
  2326                 return t.supertype_field;
  2329             /**
  2330              * The supertype is always a class type. If the type
  2331              * variable's bounds start with a class type, this is also
  2332              * the supertype.  Otherwise, the supertype is
  2333              * java.lang.Object.
  2334              */
  2335             @Override
  2336             public Type visitTypeVar(TypeVar t, Void ignored) {
  2337                 if (t.bound.hasTag(TYPEVAR) ||
  2338                     (!t.bound.isCompound() && !t.bound.isInterface())) {
  2339                     return t.bound;
  2340                 } else {
  2341                     return supertype(t.bound);
  2345             @Override
  2346             public Type visitArrayType(ArrayType t, Void ignored) {
  2347                 if (t.elemtype.isPrimitive() || isSameType(t.elemtype, syms.objectType))
  2348                     return arraySuperType();
  2349                 else
  2350                     return new ArrayType(supertype(t.elemtype), t.tsym);
  2353             @Override
  2354             public Type visitErrorType(ErrorType t, Void ignored) {
  2355                 return Type.noType;
  2357         };
  2358     // </editor-fold>
  2360     // <editor-fold defaultstate="collapsed" desc="interfaces">
  2361     /**
  2362      * Return the interfaces implemented by this class.
  2363      */
  2364     public List<Type> interfaces(Type t) {
  2365         return interfaces.visit(t);
  2367     // where
  2368         private UnaryVisitor<List<Type>> interfaces = new UnaryVisitor<List<Type>>() {
  2370             public List<Type> visitType(Type t, Void ignored) {
  2371                 return List.nil();
  2374             @Override
  2375             public List<Type> visitClassType(ClassType t, Void ignored) {
  2376                 if (t.interfaces_field == null) {
  2377                     List<Type> interfaces = ((ClassSymbol)t.tsym).getInterfaces();
  2378                     if (t.interfaces_field == null) {
  2379                         // If t.interfaces_field is null, then t must
  2380                         // be a parameterized type (not to be confused
  2381                         // with a generic type declaration).
  2382                         // Terminology:
  2383                         //    Parameterized type: List<String>
  2384                         //    Generic type declaration: class List<E> { ... }
  2385                         // So t corresponds to List<String> and
  2386                         // t.tsym.type corresponds to List<E>.
  2387                         // The reason t must be parameterized type is
  2388                         // that completion will happen as a side
  2389                         // effect of calling
  2390                         // ClassSymbol.getInterfaces.  Since
  2391                         // t.interfaces_field is null after
  2392                         // completion, we can assume that t is not the
  2393                         // type of a class/interface declaration.
  2394                         Assert.check(t != t.tsym.type, t);
  2395                         List<Type> actuals = t.allparams();
  2396                         List<Type> formals = t.tsym.type.allparams();
  2397                         if (t.hasErasedSupertypes()) {
  2398                             t.interfaces_field = erasureRecursive(interfaces);
  2399                         } else if (formals.nonEmpty()) {
  2400                             t.interfaces_field = subst(interfaces, formals, actuals);
  2402                         else {
  2403                             t.interfaces_field = interfaces;
  2407                 return t.interfaces_field;
  2410             @Override
  2411             public List<Type> visitTypeVar(TypeVar t, Void ignored) {
  2412                 if (t.bound.isCompound())
  2413                     return interfaces(t.bound);
  2415                 if (t.bound.isInterface())
  2416                     return List.of(t.bound);
  2418                 return List.nil();
  2420         };
  2422     public List<Type> directSupertypes(Type t) {
  2423         return directSupertypes.visit(t);
  2425     // where
  2426         private final UnaryVisitor<List<Type>> directSupertypes = new UnaryVisitor<List<Type>>() {
  2428             public List<Type> visitType(final Type type, final Void ignored) {
  2429                 if (!type.isCompound()) {
  2430                     final Type sup = supertype(type);
  2431                     return (sup == Type.noType || sup == type || sup == null)
  2432                         ? interfaces(type)
  2433                         : interfaces(type).prepend(sup);
  2434                 } else {
  2435                     return visitIntersectionType((IntersectionClassType) type);
  2439             private List<Type> visitIntersectionType(final IntersectionClassType it) {
  2440                 return it.getExplicitComponents();
  2443         };
  2445     public boolean isDirectSuperInterface(TypeSymbol isym, TypeSymbol origin) {
  2446         for (Type i2 : interfaces(origin.type)) {
  2447             if (isym == i2.tsym) return true;
  2449         return false;
  2451     // </editor-fold>
  2453     // <editor-fold defaultstate="collapsed" desc="isDerivedRaw">
  2454     Map<Type,Boolean> isDerivedRawCache = new HashMap<Type,Boolean>();
  2456     public boolean isDerivedRaw(Type t) {
  2457         Boolean result = isDerivedRawCache.get(t);
  2458         if (result == null) {
  2459             result = isDerivedRawInternal(t);
  2460             isDerivedRawCache.put(t, result);
  2462         return result;
  2465     public boolean isDerivedRawInternal(Type t) {
  2466         if (t.isErroneous())
  2467             return false;
  2468         return
  2469             t.isRaw() ||
  2470             supertype(t) != Type.noType && isDerivedRaw(supertype(t)) ||
  2471             isDerivedRaw(interfaces(t));
  2474     public boolean isDerivedRaw(List<Type> ts) {
  2475         List<Type> l = ts;
  2476         while (l.nonEmpty() && !isDerivedRaw(l.head)) l = l.tail;
  2477         return l.nonEmpty();
  2479     // </editor-fold>
  2481     // <editor-fold defaultstate="collapsed" desc="setBounds">
  2482     /**
  2483      * Set the bounds field of the given type variable to reflect a
  2484      * (possibly multiple) list of bounds.
  2485      * @param t                 a type variable
  2486      * @param bounds            the bounds, must be nonempty
  2487      * @param supertype         is objectType if all bounds are interfaces,
  2488      *                          null otherwise.
  2489      */
  2490     public void setBounds(TypeVar t, List<Type> bounds) {
  2491         setBounds(t, bounds, bounds.head.tsym.isInterface());
  2494     /**
  2495      * Same as {@link #setBounds(Type.TypeVar,List,Type)}, except that
  2496      * third parameter is computed directly, as follows: if all
  2497      * all bounds are interface types, the computed supertype is Object,
  2498      * otherwise the supertype is simply left null (in this case, the supertype
  2499      * is assumed to be the head of the bound list passed as second argument).
  2500      * Note that this check might cause a symbol completion. Hence, this version of
  2501      * setBounds may not be called during a classfile read.
  2502      */
  2503     public void setBounds(TypeVar t, List<Type> bounds, boolean allInterfaces) {
  2504         t.bound = bounds.tail.isEmpty() ?
  2505                 bounds.head :
  2506                 makeCompoundType(bounds, allInterfaces);
  2507         t.rank_field = -1;
  2509     // </editor-fold>
  2511     // <editor-fold defaultstate="collapsed" desc="getBounds">
  2512     /**
  2513      * Return list of bounds of the given type variable.
  2514      */
  2515     public List<Type> getBounds(TypeVar t) {
  2516         if (t.bound.hasTag(NONE))
  2517             return List.nil();
  2518         else if (t.bound.isErroneous() || !t.bound.isCompound())
  2519             return List.of(t.bound);
  2520         else if ((erasure(t).tsym.flags() & INTERFACE) == 0)
  2521             return interfaces(t).prepend(supertype(t));
  2522         else
  2523             // No superclass was given in bounds.
  2524             // In this case, supertype is Object, erasure is first interface.
  2525             return interfaces(t);
  2527     // </editor-fold>
  2529     // <editor-fold defaultstate="collapsed" desc="classBound">
  2530     /**
  2531      * If the given type is a (possibly selected) type variable,
  2532      * return the bounding class of this type, otherwise return the
  2533      * type itself.
  2534      */
  2535     public Type classBound(Type t) {
  2536         return classBound.visit(t);
  2538     // where
  2539         private UnaryVisitor<Type> classBound = new UnaryVisitor<Type>() {
  2541             public Type visitType(Type t, Void ignored) {
  2542                 return t;
  2545             @Override
  2546             public Type visitClassType(ClassType t, Void ignored) {
  2547                 Type outer1 = classBound(t.getEnclosingType());
  2548                 if (outer1 != t.getEnclosingType())
  2549                     return new ClassType(outer1, t.getTypeArguments(), t.tsym);
  2550                 else
  2551                     return t;
  2554             @Override
  2555             public Type visitTypeVar(TypeVar t, Void ignored) {
  2556                 return classBound(supertype(t));
  2559             @Override
  2560             public Type visitErrorType(ErrorType t, Void ignored) {
  2561                 return t;
  2563         };
  2564     // </editor-fold>
  2566     // <editor-fold defaultstate="collapsed" desc="sub signature / override equivalence">
  2567     /**
  2568      * Returns true iff the first signature is a <em>sub
  2569      * signature</em> of the other.  This is <b>not</b> an equivalence
  2570      * relation.
  2572      * @jls section 8.4.2.
  2573      * @see #overrideEquivalent(Type t, Type s)
  2574      * @param t first signature (possibly raw).
  2575      * @param s second signature (could be subjected to erasure).
  2576      * @return true if t is a sub signature of s.
  2577      */
  2578     public boolean isSubSignature(Type t, Type s) {
  2579         return isSubSignature(t, s, true);
  2582     public boolean isSubSignature(Type t, Type s, boolean strict) {
  2583         return hasSameArgs(t, s, strict) || hasSameArgs(t, erasure(s), strict);
  2586     /**
  2587      * Returns true iff these signatures are related by <em>override
  2588      * equivalence</em>.  This is the natural extension of
  2589      * isSubSignature to an equivalence relation.
  2591      * @jls section 8.4.2.
  2592      * @see #isSubSignature(Type t, Type s)
  2593      * @param t a signature (possible raw, could be subjected to
  2594      * erasure).
  2595      * @param s a signature (possible raw, could be subjected to
  2596      * erasure).
  2597      * @return true if either argument is a sub signature of the other.
  2598      */
  2599     public boolean overrideEquivalent(Type t, Type s) {
  2600         return hasSameArgs(t, s) ||
  2601             hasSameArgs(t, erasure(s)) || hasSameArgs(erasure(t), s);
  2604     public boolean overridesObjectMethod(TypeSymbol origin, Symbol msym) {
  2605         for (Scope.Entry e = syms.objectType.tsym.members().lookup(msym.name) ; e.scope != null ; e = e.next()) {
  2606             if (msym.overrides(e.sym, origin, Types.this, true)) {
  2607                 return true;
  2610         return false;
  2613     // <editor-fold defaultstate="collapsed" desc="Determining method implementation in given site">
  2614     class ImplementationCache {
  2616         private WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>> _map =
  2617                 new WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>>();
  2619         class Entry {
  2620             final MethodSymbol cachedImpl;
  2621             final Filter<Symbol> implFilter;
  2622             final boolean checkResult;
  2623             final int prevMark;
  2625             public Entry(MethodSymbol cachedImpl,
  2626                     Filter<Symbol> scopeFilter,
  2627                     boolean checkResult,
  2628                     int prevMark) {
  2629                 this.cachedImpl = cachedImpl;
  2630                 this.implFilter = scopeFilter;
  2631                 this.checkResult = checkResult;
  2632                 this.prevMark = prevMark;
  2635             boolean matches(Filter<Symbol> scopeFilter, boolean checkResult, int mark) {
  2636                 return this.implFilter == scopeFilter &&
  2637                         this.checkResult == checkResult &&
  2638                         this.prevMark == mark;
  2642         MethodSymbol get(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
  2643             SoftReference<Map<TypeSymbol, Entry>> ref_cache = _map.get(ms);
  2644             Map<TypeSymbol, Entry> cache = ref_cache != null ? ref_cache.get() : null;
  2645             if (cache == null) {
  2646                 cache = new HashMap<TypeSymbol, Entry>();
  2647                 _map.put(ms, new SoftReference<Map<TypeSymbol, Entry>>(cache));
  2649             Entry e = cache.get(origin);
  2650             CompoundScope members = membersClosure(origin.type, true);
  2651             if (e == null ||
  2652                     !e.matches(implFilter, checkResult, members.getMark())) {
  2653                 MethodSymbol impl = implementationInternal(ms, origin, checkResult, implFilter);
  2654                 cache.put(origin, new Entry(impl, implFilter, checkResult, members.getMark()));
  2655                 return impl;
  2657             else {
  2658                 return e.cachedImpl;
  2662         private MethodSymbol implementationInternal(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
  2663             for (Type t = origin.type; t.hasTag(CLASS) || t.hasTag(TYPEVAR); t = supertype(t)) {
  2664                 while (t.hasTag(TYPEVAR))
  2665                     t = t.getUpperBound();
  2666                 TypeSymbol c = t.tsym;
  2667                 for (Scope.Entry e = c.members().lookup(ms.name, implFilter);
  2668                      e.scope != null;
  2669                      e = e.next(implFilter)) {
  2670                     if (e.sym != null &&
  2671                              e.sym.overrides(ms, origin, Types.this, checkResult))
  2672                         return (MethodSymbol)e.sym;
  2675             return null;
  2679     private ImplementationCache implCache = new ImplementationCache();
  2681     public MethodSymbol implementation(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
  2682         return implCache.get(ms, origin, checkResult, implFilter);
  2684     // </editor-fold>
  2686     // <editor-fold defaultstate="collapsed" desc="compute transitive closure of all members in given site">
  2687     class MembersClosureCache extends SimpleVisitor<CompoundScope, Boolean> {
  2689         private WeakHashMap<TypeSymbol, Entry> _map =
  2690                 new WeakHashMap<TypeSymbol, Entry>();
  2692         class Entry {
  2693             final boolean skipInterfaces;
  2694             final CompoundScope compoundScope;
  2696             public Entry(boolean skipInterfaces, CompoundScope compoundScope) {
  2697                 this.skipInterfaces = skipInterfaces;
  2698                 this.compoundScope = compoundScope;
  2701             boolean matches(boolean skipInterfaces) {
  2702                 return this.skipInterfaces == skipInterfaces;
  2706         List<TypeSymbol> seenTypes = List.nil();
  2708         /** members closure visitor methods **/
  2710         public CompoundScope visitType(Type t, Boolean skipInterface) {
  2711             return null;
  2714         @Override
  2715         public CompoundScope visitClassType(ClassType t, Boolean skipInterface) {
  2716             if (seenTypes.contains(t.tsym)) {
  2717                 //this is possible when an interface is implemented in multiple
  2718                 //superclasses, or when a classs hierarchy is circular - in such
  2719                 //cases we don't need to recurse (empty scope is returned)
  2720                 return new CompoundScope(t.tsym);
  2722             try {
  2723                 seenTypes = seenTypes.prepend(t.tsym);
  2724                 ClassSymbol csym = (ClassSymbol)t.tsym;
  2725                 Entry e = _map.get(csym);
  2726                 if (e == null || !e.matches(skipInterface)) {
  2727                     CompoundScope membersClosure = new CompoundScope(csym);
  2728                     if (!skipInterface) {
  2729                         for (Type i : interfaces(t)) {
  2730                             membersClosure.addSubScope(visit(i, skipInterface));
  2733                     membersClosure.addSubScope(visit(supertype(t), skipInterface));
  2734                     membersClosure.addSubScope(csym.members());
  2735                     e = new Entry(skipInterface, membersClosure);
  2736                     _map.put(csym, e);
  2738                 return e.compoundScope;
  2740             finally {
  2741                 seenTypes = seenTypes.tail;
  2745         @Override
  2746         public CompoundScope visitTypeVar(TypeVar t, Boolean skipInterface) {
  2747             return visit(t.getUpperBound(), skipInterface);
  2751     private MembersClosureCache membersCache = new MembersClosureCache();
  2753     public CompoundScope membersClosure(Type site, boolean skipInterface) {
  2754         return membersCache.visit(site, skipInterface);
  2756     // </editor-fold>
  2759     //where
  2760     public List<MethodSymbol> interfaceCandidates(Type site, MethodSymbol ms) {
  2761         Filter<Symbol> filter = new MethodFilter(ms, site);
  2762         List<MethodSymbol> candidates = List.nil();
  2763             for (Symbol s : membersClosure(site, false).getElements(filter)) {
  2764                 if (!site.tsym.isInterface() && !s.owner.isInterface()) {
  2765                     return List.of((MethodSymbol)s);
  2766                 } else if (!candidates.contains(s)) {
  2767                     candidates = candidates.prepend((MethodSymbol)s);
  2770             return prune(candidates);
  2773     public List<MethodSymbol> prune(List<MethodSymbol> methods) {
  2774         ListBuffer<MethodSymbol> methodsMin = new ListBuffer<>();
  2775         for (MethodSymbol m1 : methods) {
  2776             boolean isMin_m1 = true;
  2777             for (MethodSymbol m2 : methods) {
  2778                 if (m1 == m2) continue;
  2779                 if (m2.owner != m1.owner &&
  2780                         asSuper(m2.owner.type, m1.owner) != null) {
  2781                     isMin_m1 = false;
  2782                     break;
  2785             if (isMin_m1)
  2786                 methodsMin.append(m1);
  2788         return methodsMin.toList();
  2790     // where
  2791             private class MethodFilter implements Filter<Symbol> {
  2793                 Symbol msym;
  2794                 Type site;
  2796                 MethodFilter(Symbol msym, Type site) {
  2797                     this.msym = msym;
  2798                     this.site = site;
  2801                 public boolean accepts(Symbol s) {
  2802                     return s.kind == Kinds.MTH &&
  2803                             s.name == msym.name &&
  2804                             (s.flags() & SYNTHETIC) == 0 &&
  2805                             s.isInheritedIn(site.tsym, Types.this) &&
  2806                             overrideEquivalent(memberType(site, s), memberType(site, msym));
  2808             };
  2809     // </editor-fold>
  2811     /**
  2812      * Does t have the same arguments as s?  It is assumed that both
  2813      * types are (possibly polymorphic) method types.  Monomorphic
  2814      * method types "have the same arguments", if their argument lists
  2815      * are equal.  Polymorphic method types "have the same arguments",
  2816      * if they have the same arguments after renaming all type
  2817      * variables of one to corresponding type variables in the other,
  2818      * where correspondence is by position in the type parameter list.
  2819      */
  2820     public boolean hasSameArgs(Type t, Type s) {
  2821         return hasSameArgs(t, s, true);
  2824     public boolean hasSameArgs(Type t, Type s, boolean strict) {
  2825         return hasSameArgs(t, s, strict ? hasSameArgs_strict : hasSameArgs_nonstrict);
  2828     private boolean hasSameArgs(Type t, Type s, TypeRelation hasSameArgs) {
  2829         return hasSameArgs.visit(t, s);
  2831     // where
  2832         private class HasSameArgs extends TypeRelation {
  2834             boolean strict;
  2836             public HasSameArgs(boolean strict) {
  2837                 this.strict = strict;
  2840             public Boolean visitType(Type t, Type s) {
  2841                 throw new AssertionError();
  2844             @Override
  2845             public Boolean visitMethodType(MethodType t, Type s) {
  2846                 return s.hasTag(METHOD)
  2847                     && containsTypeEquivalent(t.argtypes, s.getParameterTypes());
  2850             @Override
  2851             public Boolean visitForAll(ForAll t, Type s) {
  2852                 if (!s.hasTag(FORALL))
  2853                     return strict ? false : visitMethodType(t.asMethodType(), s);
  2855                 ForAll forAll = (ForAll)s;
  2856                 return hasSameBounds(t, forAll)
  2857                     && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
  2860             @Override
  2861             public Boolean visitErrorType(ErrorType t, Type s) {
  2862                 return false;
  2864         };
  2866         TypeRelation hasSameArgs_strict = new HasSameArgs(true);
  2867         TypeRelation hasSameArgs_nonstrict = new HasSameArgs(false);
  2869     // </editor-fold>
  2871     // <editor-fold defaultstate="collapsed" desc="subst">
  2872     public List<Type> subst(List<Type> ts,
  2873                             List<Type> from,
  2874                             List<Type> to) {
  2875         return new Subst(from, to).subst(ts);
  2878     /**
  2879      * Substitute all occurrences of a type in `from' with the
  2880      * corresponding type in `to' in 't'. Match lists `from' and `to'
  2881      * from the right: If lists have different length, discard leading
  2882      * elements of the longer list.
  2883      */
  2884     public Type subst(Type t, List<Type> from, List<Type> to) {
  2885         return new Subst(from, to).subst(t);
  2888     private class Subst extends UnaryVisitor<Type> {
  2889         List<Type> from;
  2890         List<Type> to;
  2892         public Subst(List<Type> from, List<Type> to) {
  2893             int fromLength = from.length();
  2894             int toLength = to.length();
  2895             while (fromLength > toLength) {
  2896                 fromLength--;
  2897                 from = from.tail;
  2899             while (fromLength < toLength) {
  2900                 toLength--;
  2901                 to = to.tail;
  2903             this.from = from;
  2904             this.to = to;
  2907         Type subst(Type t) {
  2908             if (from.tail == null)
  2909                 return t;
  2910             else
  2911                 return visit(t);
  2914         List<Type> subst(List<Type> ts) {
  2915             if (from.tail == null)
  2916                 return ts;
  2917             boolean wild = false;
  2918             if (ts.nonEmpty() && from.nonEmpty()) {
  2919                 Type head1 = subst(ts.head);
  2920                 List<Type> tail1 = subst(ts.tail);
  2921                 if (head1 != ts.head || tail1 != ts.tail)
  2922                     return tail1.prepend(head1);
  2924             return ts;
  2927         public Type visitType(Type t, Void ignored) {
  2928             return t;
  2931         @Override
  2932         public Type visitMethodType(MethodType t, Void ignored) {
  2933             List<Type> argtypes = subst(t.argtypes);
  2934             Type restype = subst(t.restype);
  2935             List<Type> thrown = subst(t.thrown);
  2936             if (argtypes == t.argtypes &&
  2937                 restype == t.restype &&
  2938                 thrown == t.thrown)
  2939                 return t;
  2940             else
  2941                 return new MethodType(argtypes, restype, thrown, t.tsym);
  2944         @Override
  2945         public Type visitTypeVar(TypeVar t, Void ignored) {
  2946             for (List<Type> from = this.from, to = this.to;
  2947                  from.nonEmpty();
  2948                  from = from.tail, to = to.tail) {
  2949                 if (t == from.head) {
  2950                     return to.head.withTypeVar(t);
  2953             return t;
  2956         @Override
  2957         public Type visitClassType(ClassType t, Void ignored) {
  2958             if (!t.isCompound()) {
  2959                 List<Type> typarams = t.getTypeArguments();
  2960                 List<Type> typarams1 = subst(typarams);
  2961                 Type outer = t.getEnclosingType();
  2962                 Type outer1 = subst(outer);
  2963                 if (typarams1 == typarams && outer1 == outer)
  2964                     return t;
  2965                 else
  2966                     return new ClassType(outer1, typarams1, t.tsym);
  2967             } else {
  2968                 Type st = subst(supertype(t));
  2969                 List<Type> is = subst(interfaces(t));
  2970                 if (st == supertype(t) && is == interfaces(t))
  2971                     return t;
  2972                 else
  2973                     return makeCompoundType(is.prepend(st));
  2977         @Override
  2978         public Type visitWildcardType(WildcardType t, Void ignored) {
  2979             Type bound = t.type;
  2980             if (t.kind != BoundKind.UNBOUND)
  2981                 bound = subst(bound);
  2982             if (bound == t.type) {
  2983                 return t;
  2984             } else {
  2985                 if (t.isExtendsBound() && bound.isExtendsBound())
  2986                     bound = wildUpperBound(bound);
  2987                 return new WildcardType(bound, t.kind, syms.boundClass, t.bound);
  2991         @Override
  2992         public Type visitArrayType(ArrayType t, Void ignored) {
  2993             Type elemtype = subst(t.elemtype);
  2994             if (elemtype == t.elemtype)
  2995                 return t;
  2996             else
  2997                 return new ArrayType(elemtype, t.tsym);
  3000         @Override
  3001         public Type visitForAll(ForAll t, Void ignored) {
  3002             if (Type.containsAny(to, t.tvars)) {
  3003                 //perform alpha-renaming of free-variables in 't'
  3004                 //if 'to' types contain variables that are free in 't'
  3005                 List<Type> freevars = newInstances(t.tvars);
  3006                 t = new ForAll(freevars,
  3007                         Types.this.subst(t.qtype, t.tvars, freevars));
  3009             List<Type> tvars1 = substBounds(t.tvars, from, to);
  3010             Type qtype1 = subst(t.qtype);
  3011             if (tvars1 == t.tvars && qtype1 == t.qtype) {
  3012                 return t;
  3013             } else if (tvars1 == t.tvars) {
  3014                 return new ForAll(tvars1, qtype1);
  3015             } else {
  3016                 return new ForAll(tvars1, Types.this.subst(qtype1, t.tvars, tvars1));
  3020         @Override
  3021         public Type visitErrorType(ErrorType t, Void ignored) {
  3022             return t;
  3026     public List<Type> substBounds(List<Type> tvars,
  3027                                   List<Type> from,
  3028                                   List<Type> to) {
  3029         if (tvars.isEmpty())
  3030             return tvars;
  3031         ListBuffer<Type> newBoundsBuf = new ListBuffer<>();
  3032         boolean changed = false;
  3033         // calculate new bounds
  3034         for (Type t : tvars) {
  3035             TypeVar tv = (TypeVar) t;
  3036             Type bound = subst(tv.bound, from, to);
  3037             if (bound != tv.bound)
  3038                 changed = true;
  3039             newBoundsBuf.append(bound);
  3041         if (!changed)
  3042             return tvars;
  3043         ListBuffer<Type> newTvars = new ListBuffer<>();
  3044         // create new type variables without bounds
  3045         for (Type t : tvars) {
  3046             newTvars.append(new TypeVar(t.tsym, null, syms.botType));
  3048         // the new bounds should use the new type variables in place
  3049         // of the old
  3050         List<Type> newBounds = newBoundsBuf.toList();
  3051         from = tvars;
  3052         to = newTvars.toList();
  3053         for (; !newBounds.isEmpty(); newBounds = newBounds.tail) {
  3054             newBounds.head = subst(newBounds.head, from, to);
  3056         newBounds = newBoundsBuf.toList();
  3057         // set the bounds of new type variables to the new bounds
  3058         for (Type t : newTvars.toList()) {
  3059             TypeVar tv = (TypeVar) t;
  3060             tv.bound = newBounds.head;
  3061             newBounds = newBounds.tail;
  3063         return newTvars.toList();
  3066     public TypeVar substBound(TypeVar t, List<Type> from, List<Type> to) {
  3067         Type bound1 = subst(t.bound, from, to);
  3068         if (bound1 == t.bound)
  3069             return t;
  3070         else {
  3071             // create new type variable without bounds
  3072             TypeVar tv = new TypeVar(t.tsym, null, syms.botType);
  3073             // the new bound should use the new type variable in place
  3074             // of the old
  3075             tv.bound = subst(bound1, List.<Type>of(t), List.<Type>of(tv));
  3076             return tv;
  3079     // </editor-fold>
  3081     // <editor-fold defaultstate="collapsed" desc="hasSameBounds">
  3082     /**
  3083      * Does t have the same bounds for quantified variables as s?
  3084      */
  3085     public boolean hasSameBounds(ForAll t, ForAll s) {
  3086         List<Type> l1 = t.tvars;
  3087         List<Type> l2 = s.tvars;
  3088         while (l1.nonEmpty() && l2.nonEmpty() &&
  3089                isSameType(l1.head.getUpperBound(),
  3090                           subst(l2.head.getUpperBound(),
  3091                                 s.tvars,
  3092                                 t.tvars))) {
  3093             l1 = l1.tail;
  3094             l2 = l2.tail;
  3096         return l1.isEmpty() && l2.isEmpty();
  3098     // </editor-fold>
  3100     // <editor-fold defaultstate="collapsed" desc="newInstances">
  3101     /** Create new vector of type variables from list of variables
  3102      *  changing all recursive bounds from old to new list.
  3103      */
  3104     public List<Type> newInstances(List<Type> tvars) {
  3105         List<Type> tvars1 = Type.map(tvars, newInstanceFun);
  3106         for (List<Type> l = tvars1; l.nonEmpty(); l = l.tail) {
  3107             TypeVar tv = (TypeVar) l.head;
  3108             tv.bound = subst(tv.bound, tvars, tvars1);
  3110         return tvars1;
  3112     private static final Mapping newInstanceFun = new Mapping("newInstanceFun") {
  3113             public Type apply(Type t) { return new TypeVar(t.tsym, t.getUpperBound(), t.getLowerBound()); }
  3114         };
  3115     // </editor-fold>
  3117     public Type createMethodTypeWithParameters(Type original, List<Type> newParams) {
  3118         return original.accept(methodWithParameters, newParams);
  3120     // where
  3121         private final MapVisitor<List<Type>> methodWithParameters = new MapVisitor<List<Type>>() {
  3122             public Type visitType(Type t, List<Type> newParams) {
  3123                 throw new IllegalArgumentException("Not a method type: " + t);
  3125             public Type visitMethodType(MethodType t, List<Type> newParams) {
  3126                 return new MethodType(newParams, t.restype, t.thrown, t.tsym);
  3128             public Type visitForAll(ForAll t, List<Type> newParams) {
  3129                 return new ForAll(t.tvars, t.qtype.accept(this, newParams));
  3131         };
  3133     public Type createMethodTypeWithThrown(Type original, List<Type> newThrown) {
  3134         return original.accept(methodWithThrown, newThrown);
  3136     // where
  3137         private final MapVisitor<List<Type>> methodWithThrown = new MapVisitor<List<Type>>() {
  3138             public Type visitType(Type t, List<Type> newThrown) {
  3139                 throw new IllegalArgumentException("Not a method type: " + t);
  3141             public Type visitMethodType(MethodType t, List<Type> newThrown) {
  3142                 return new MethodType(t.argtypes, t.restype, newThrown, t.tsym);
  3144             public Type visitForAll(ForAll t, List<Type> newThrown) {
  3145                 return new ForAll(t.tvars, t.qtype.accept(this, newThrown));
  3147         };
  3149     public Type createMethodTypeWithReturn(Type original, Type newReturn) {
  3150         return original.accept(methodWithReturn, newReturn);
  3152     // where
  3153         private final MapVisitor<Type> methodWithReturn = new MapVisitor<Type>() {
  3154             public Type visitType(Type t, Type newReturn) {
  3155                 throw new IllegalArgumentException("Not a method type: " + t);
  3157             public Type visitMethodType(MethodType t, Type newReturn) {
  3158                 return new MethodType(t.argtypes, newReturn, t.thrown, t.tsym);
  3160             public Type visitForAll(ForAll t, Type newReturn) {
  3161                 return new ForAll(t.tvars, t.qtype.accept(this, newReturn));
  3163         };
  3165     // <editor-fold defaultstate="collapsed" desc="createErrorType">
  3166     public Type createErrorType(Type originalType) {
  3167         return new ErrorType(originalType, syms.errSymbol);
  3170     public Type createErrorType(ClassSymbol c, Type originalType) {
  3171         return new ErrorType(c, originalType);
  3174     public Type createErrorType(Name name, TypeSymbol container, Type originalType) {
  3175         return new ErrorType(name, container, originalType);
  3177     // </editor-fold>
  3179     // <editor-fold defaultstate="collapsed" desc="rank">
  3180     /**
  3181      * The rank of a class is the length of the longest path between
  3182      * the class and java.lang.Object in the class inheritance
  3183      * graph. Undefined for all but reference types.
  3184      */
  3185     public int rank(Type t) {
  3186         t = t.unannotatedType();
  3187         switch(t.getTag()) {
  3188         case CLASS: {
  3189             ClassType cls = (ClassType)t;
  3190             if (cls.rank_field < 0) {
  3191                 Name fullname = cls.tsym.getQualifiedName();
  3192                 if (fullname == names.java_lang_Object)
  3193                     cls.rank_field = 0;
  3194                 else {
  3195                     int r = rank(supertype(cls));
  3196                     for (List<Type> l = interfaces(cls);
  3197                          l.nonEmpty();
  3198                          l = l.tail) {
  3199                         if (rank(l.head) > r)
  3200                             r = rank(l.head);
  3202                     cls.rank_field = r + 1;
  3205             return cls.rank_field;
  3207         case TYPEVAR: {
  3208             TypeVar tvar = (TypeVar)t;
  3209             if (tvar.rank_field < 0) {
  3210                 int r = rank(supertype(tvar));
  3211                 for (List<Type> l = interfaces(tvar);
  3212                      l.nonEmpty();
  3213                      l = l.tail) {
  3214                     if (rank(l.head) > r) r = rank(l.head);
  3216                 tvar.rank_field = r + 1;
  3218             return tvar.rank_field;
  3220         case ERROR:
  3221         case NONE:
  3222             return 0;
  3223         default:
  3224             throw new AssertionError();
  3227     // </editor-fold>
  3229     /**
  3230      * Helper method for generating a string representation of a given type
  3231      * accordingly to a given locale
  3232      */
  3233     public String toString(Type t, Locale locale) {
  3234         return Printer.createStandardPrinter(messages).visit(t, locale);
  3237     /**
  3238      * Helper method for generating a string representation of a given type
  3239      * accordingly to a given locale
  3240      */
  3241     public String toString(Symbol t, Locale locale) {
  3242         return Printer.createStandardPrinter(messages).visit(t, locale);
  3245     // <editor-fold defaultstate="collapsed" desc="toString">
  3246     /**
  3247      * This toString is slightly more descriptive than the one on Type.
  3249      * @deprecated Types.toString(Type t, Locale l) provides better support
  3250      * for localization
  3251      */
  3252     @Deprecated
  3253     public String toString(Type t) {
  3254         if (t.hasTag(FORALL)) {
  3255             ForAll forAll = (ForAll)t;
  3256             return typaramsString(forAll.tvars) + forAll.qtype;
  3258         return "" + t;
  3260     // where
  3261         private String typaramsString(List<Type> tvars) {
  3262             StringBuilder s = new StringBuilder();
  3263             s.append('<');
  3264             boolean first = true;
  3265             for (Type t : tvars) {
  3266                 if (!first) s.append(", ");
  3267                 first = false;
  3268                 appendTyparamString(((TypeVar)t.unannotatedType()), s);
  3270             s.append('>');
  3271             return s.toString();
  3273         private void appendTyparamString(TypeVar t, StringBuilder buf) {
  3274             buf.append(t);
  3275             if (t.bound == null ||
  3276                 t.bound.tsym.getQualifiedName() == names.java_lang_Object)
  3277                 return;
  3278             buf.append(" extends "); // Java syntax; no need for i18n
  3279             Type bound = t.bound;
  3280             if (!bound.isCompound()) {
  3281                 buf.append(bound);
  3282             } else if ((erasure(t).tsym.flags() & INTERFACE) == 0) {
  3283                 buf.append(supertype(t));
  3284                 for (Type intf : interfaces(t)) {
  3285                     buf.append('&');
  3286                     buf.append(intf);
  3288             } else {
  3289                 // No superclass was given in bounds.
  3290                 // In this case, supertype is Object, erasure is first interface.
  3291                 boolean first = true;
  3292                 for (Type intf : interfaces(t)) {
  3293                     if (!first) buf.append('&');
  3294                     first = false;
  3295                     buf.append(intf);
  3299     // </editor-fold>
  3301     // <editor-fold defaultstate="collapsed" desc="Determining least upper bounds of types">
  3302     /**
  3303      * A cache for closures.
  3305      * <p>A closure is a list of all the supertypes and interfaces of
  3306      * a class or interface type, ordered by ClassSymbol.precedes
  3307      * (that is, subclasses come first, arbitrary but fixed
  3308      * otherwise).
  3309      */
  3310     private Map<Type,List<Type>> closureCache = new HashMap<Type,List<Type>>();
  3312     /**
  3313      * Returns the closure of a class or interface type.
  3314      */
  3315     public List<Type> closure(Type t) {
  3316         List<Type> cl = closureCache.get(t);
  3317         if (cl == null) {
  3318             Type st = supertype(t);
  3319             if (!t.isCompound()) {
  3320                 if (st.hasTag(CLASS)) {
  3321                     cl = insert(closure(st), t);
  3322                 } else if (st.hasTag(TYPEVAR)) {
  3323                     cl = closure(st).prepend(t);
  3324                 } else {
  3325                     cl = List.of(t);
  3327             } else {
  3328                 cl = closure(supertype(t));
  3330             for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail)
  3331                 cl = union(cl, closure(l.head));
  3332             closureCache.put(t, cl);
  3334         return cl;
  3337     /**
  3338      * Insert a type in a closure
  3339      */
  3340     public List<Type> insert(List<Type> cl, Type t) {
  3341         if (cl.isEmpty()) {
  3342             return cl.prepend(t);
  3343         } else if (t.tsym == cl.head.tsym) {
  3344             return cl;
  3345         } else if (t.tsym.precedes(cl.head.tsym, this)) {
  3346             return cl.prepend(t);
  3347         } else {
  3348             // t comes after head, or the two are unrelated
  3349             return insert(cl.tail, t).prepend(cl.head);
  3353     /**
  3354      * Form the union of two closures
  3355      */
  3356     public List<Type> union(List<Type> cl1, List<Type> cl2) {
  3357         if (cl1.isEmpty()) {
  3358             return cl2;
  3359         } else if (cl2.isEmpty()) {
  3360             return cl1;
  3361         } else if (cl1.head.tsym == cl2.head.tsym) {
  3362             return union(cl1.tail, cl2.tail).prepend(cl1.head);
  3363         } else if (cl1.head.tsym.precedes(cl2.head.tsym, this)) {
  3364             return union(cl1.tail, cl2).prepend(cl1.head);
  3365         } else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) {
  3366             return union(cl1, cl2.tail).prepend(cl2.head);
  3367         } else {
  3368             // unrelated types
  3369             return union(cl1.tail, cl2).prepend(cl1.head);
  3373     /**
  3374      * Intersect two closures
  3375      */
  3376     public List<Type> intersect(List<Type> cl1, List<Type> cl2) {
  3377         if (cl1 == cl2)
  3378             return cl1;
  3379         if (cl1.isEmpty() || cl2.isEmpty())
  3380             return List.nil();
  3381         if (cl1.head.tsym.precedes(cl2.head.tsym, this))
  3382             return intersect(cl1.tail, cl2);
  3383         if (cl2.head.tsym.precedes(cl1.head.tsym, this))
  3384             return intersect(cl1, cl2.tail);
  3385         if (isSameType(cl1.head, cl2.head))
  3386             return intersect(cl1.tail, cl2.tail).prepend(cl1.head);
  3387         if (cl1.head.tsym == cl2.head.tsym &&
  3388             cl1.head.hasTag(CLASS) && cl2.head.hasTag(CLASS)) {
  3389             if (cl1.head.isParameterized() && cl2.head.isParameterized()) {
  3390                 Type merge = merge(cl1.head,cl2.head);
  3391                 return intersect(cl1.tail, cl2.tail).prepend(merge);
  3393             if (cl1.head.isRaw() || cl2.head.isRaw())
  3394                 return intersect(cl1.tail, cl2.tail).prepend(erasure(cl1.head));
  3396         return intersect(cl1.tail, cl2.tail);
  3398     // where
  3399         class TypePair {
  3400             final Type t1;
  3401             final Type t2;
  3402             boolean strict;
  3404             TypePair(Type t1, Type t2) {
  3405                 this(t1, t2, false);
  3408             TypePair(Type t1, Type t2, boolean strict) {
  3409                 this.t1 = t1;
  3410                 this.t2 = t2;
  3411                 this.strict = strict;
  3413             @Override
  3414             public int hashCode() {
  3415                 return 127 * Types.this.hashCode(t1) + Types.this.hashCode(t2);
  3417             @Override
  3418             public boolean equals(Object obj) {
  3419                 if (!(obj instanceof TypePair))
  3420                     return false;
  3421                 TypePair typePair = (TypePair)obj;
  3422                 return isSameType(t1, typePair.t1, strict)
  3423                     && isSameType(t2, typePair.t2, strict);
  3426         Set<TypePair> mergeCache = new HashSet<TypePair>();
  3427         private Type merge(Type c1, Type c2) {
  3428             ClassType class1 = (ClassType) c1;
  3429             List<Type> act1 = class1.getTypeArguments();
  3430             ClassType class2 = (ClassType) c2;
  3431             List<Type> act2 = class2.getTypeArguments();
  3432             ListBuffer<Type> merged = new ListBuffer<Type>();
  3433             List<Type> typarams = class1.tsym.type.getTypeArguments();
  3435             while (act1.nonEmpty() && act2.nonEmpty() && typarams.nonEmpty()) {
  3436                 if (containsType(act1.head, act2.head)) {
  3437                     merged.append(act1.head);
  3438                 } else if (containsType(act2.head, act1.head)) {
  3439                     merged.append(act2.head);
  3440                 } else {
  3441                     TypePair pair = new TypePair(c1, c2);
  3442                     Type m;
  3443                     if (mergeCache.add(pair)) {
  3444                         m = new WildcardType(lub(wildUpperBound(act1.head),
  3445                                                  wildUpperBound(act2.head)),
  3446                                              BoundKind.EXTENDS,
  3447                                              syms.boundClass);
  3448                         mergeCache.remove(pair);
  3449                     } else {
  3450                         m = new WildcardType(syms.objectType,
  3451                                              BoundKind.UNBOUND,
  3452                                              syms.boundClass);
  3454                     merged.append(m.withTypeVar(typarams.head));
  3456                 act1 = act1.tail;
  3457                 act2 = act2.tail;
  3458                 typarams = typarams.tail;
  3460             Assert.check(act1.isEmpty() && act2.isEmpty() && typarams.isEmpty());
  3461             return new ClassType(class1.getEnclosingType(), merged.toList(), class1.tsym);
  3464     /**
  3465      * Return the minimum type of a closure, a compound type if no
  3466      * unique minimum exists.
  3467      */
  3468     private Type compoundMin(List<Type> cl) {
  3469         if (cl.isEmpty()) return syms.objectType;
  3470         List<Type> compound = closureMin(cl);
  3471         if (compound.isEmpty())
  3472             return null;
  3473         else if (compound.tail.isEmpty())
  3474             return compound.head;
  3475         else
  3476             return makeCompoundType(compound);
  3479     /**
  3480      * Return the minimum types of a closure, suitable for computing
  3481      * compoundMin or glb.
  3482      */
  3483     private List<Type> closureMin(List<Type> cl) {
  3484         ListBuffer<Type> classes = new ListBuffer<>();
  3485         ListBuffer<Type> interfaces = new ListBuffer<>();
  3486         Set<Type> toSkip = new HashSet<>();
  3487         while (!cl.isEmpty()) {
  3488             Type current = cl.head;
  3489             boolean keep = !toSkip.contains(current);
  3490             if (keep && current.hasTag(TYPEVAR)) {
  3491                 // skip lower-bounded variables with a subtype in cl.tail
  3492                 for (Type t : cl.tail) {
  3493                     if (isSubtypeNoCapture(t, current)) {
  3494                         keep = false;
  3495                         break;
  3499             if (keep) {
  3500                 if (current.isInterface())
  3501                     interfaces.append(current);
  3502                 else
  3503                     classes.append(current);
  3504                 for (Type t : cl.tail) {
  3505                     // skip supertypes of 'current' in cl.tail
  3506                     if (isSubtypeNoCapture(current, t))
  3507                         toSkip.add(t);
  3510             cl = cl.tail;
  3512         return classes.appendList(interfaces).toList();
  3515     /**
  3516      * Return the least upper bound of pair of types.  if the lub does
  3517      * not exist return null.
  3518      */
  3519     public Type lub(Type t1, Type t2) {
  3520         return lub(List.of(t1, t2));
  3523     /**
  3524      * Return the least upper bound (lub) of set of types.  If the lub
  3525      * does not exist return the type of null (bottom).
  3526      */
  3527     public Type lub(List<Type> ts) {
  3528         final int ARRAY_BOUND = 1;
  3529         final int CLASS_BOUND = 2;
  3530         int boundkind = 0;
  3531         for (Type t : ts) {
  3532             switch (t.getTag()) {
  3533             case CLASS:
  3534                 boundkind |= CLASS_BOUND;
  3535                 break;
  3536             case ARRAY:
  3537                 boundkind |= ARRAY_BOUND;
  3538                 break;
  3539             case  TYPEVAR:
  3540                 do {
  3541                     t = t.getUpperBound();
  3542                 } while (t.hasTag(TYPEVAR));
  3543                 if (t.hasTag(ARRAY)) {
  3544                     boundkind |= ARRAY_BOUND;
  3545                 } else {
  3546                     boundkind |= CLASS_BOUND;
  3548                 break;
  3549             default:
  3550                 if (t.isPrimitive())
  3551                     return syms.errType;
  3554         switch (boundkind) {
  3555         case 0:
  3556             return syms.botType;
  3558         case ARRAY_BOUND:
  3559             // calculate lub(A[], B[])
  3560             List<Type> elements = Type.map(ts, elemTypeFun);
  3561             for (Type t : elements) {
  3562                 if (t.isPrimitive()) {
  3563                     // if a primitive type is found, then return
  3564                     // arraySuperType unless all the types are the
  3565                     // same
  3566                     Type first = ts.head;
  3567                     for (Type s : ts.tail) {
  3568                         if (!isSameType(first, s)) {
  3569                              // lub(int[], B[]) is Cloneable & Serializable
  3570                             return arraySuperType();
  3573                     // all the array types are the same, return one
  3574                     // lub(int[], int[]) is int[]
  3575                     return first;
  3578             // lub(A[], B[]) is lub(A, B)[]
  3579             return new ArrayType(lub(elements), syms.arrayClass);
  3581         case CLASS_BOUND:
  3582             // calculate lub(A, B)
  3583             while (!ts.head.hasTag(CLASS) && !ts.head.hasTag(TYPEVAR)) {
  3584                 ts = ts.tail;
  3586             Assert.check(!ts.isEmpty());
  3587             //step 1 - compute erased candidate set (EC)
  3588             List<Type> cl = erasedSupertypes(ts.head);
  3589             for (Type t : ts.tail) {
  3590                 if (t.hasTag(CLASS) || t.hasTag(TYPEVAR))
  3591                     cl = intersect(cl, erasedSupertypes(t));
  3593             //step 2 - compute minimal erased candidate set (MEC)
  3594             List<Type> mec = closureMin(cl);
  3595             //step 3 - for each element G in MEC, compute lci(Inv(G))
  3596             List<Type> candidates = List.nil();
  3597             for (Type erasedSupertype : mec) {
  3598                 List<Type> lci = List.of(asSuper(ts.head, erasedSupertype.tsym));
  3599                 for (Type t : ts) {
  3600                     lci = intersect(lci, List.of(asSuper(t, erasedSupertype.tsym)));
  3602                 candidates = candidates.appendList(lci);
  3604             //step 4 - let MEC be { G1, G2 ... Gn }, then we have that
  3605             //lub = lci(Inv(G1)) & lci(Inv(G2)) & ... & lci(Inv(Gn))
  3606             return compoundMin(candidates);
  3608         default:
  3609             // calculate lub(A, B[])
  3610             List<Type> classes = List.of(arraySuperType());
  3611             for (Type t : ts) {
  3612                 if (!t.hasTag(ARRAY)) // Filter out any arrays
  3613                     classes = classes.prepend(t);
  3615             // lub(A, B[]) is lub(A, arraySuperType)
  3616             return lub(classes);
  3619     // where
  3620         List<Type> erasedSupertypes(Type t) {
  3621             ListBuffer<Type> buf = new ListBuffer<>();
  3622             for (Type sup : closure(t)) {
  3623                 if (sup.hasTag(TYPEVAR)) {
  3624                     buf.append(sup);
  3625                 } else {
  3626                     buf.append(erasure(sup));
  3629             return buf.toList();
  3632         private Type arraySuperType = null;
  3633         private Type arraySuperType() {
  3634             // initialized lazily to avoid problems during compiler startup
  3635             if (arraySuperType == null) {
  3636                 synchronized (this) {
  3637                     if (arraySuperType == null) {
  3638                         // JLS 10.8: all arrays implement Cloneable and Serializable.
  3639                         arraySuperType = makeCompoundType(List.of(syms.serializableType,
  3640                                                                   syms.cloneableType), true);
  3644             return arraySuperType;
  3646     // </editor-fold>
  3648     // <editor-fold defaultstate="collapsed" desc="Greatest lower bound">
  3649     public Type glb(List<Type> ts) {
  3650         Type t1 = ts.head;
  3651         for (Type t2 : ts.tail) {
  3652             if (t1.isErroneous())
  3653                 return t1;
  3654             t1 = glb(t1, t2);
  3656         return t1;
  3658     //where
  3659     public Type glb(Type t, Type s) {
  3660         if (s == null)
  3661             return t;
  3662         else if (t.isPrimitive() || s.isPrimitive())
  3663             return syms.errType;
  3664         else if (isSubtypeNoCapture(t, s))
  3665             return t;
  3666         else if (isSubtypeNoCapture(s, t))
  3667             return s;
  3669         List<Type> closure = union(closure(t), closure(s));
  3670         return glbFlattened(closure, t);
  3672     //where
  3673     /**
  3674      * Perform glb for a list of non-primitive, non-error, non-compound types;
  3675      * redundant elements are removed.  Bounds should be ordered according to
  3676      * {@link Symbol#precedes(TypeSymbol,Types)}.
  3678      * @param flatBounds List of type to glb
  3679      * @param errT Original type to use if the result is an error type
  3680      */
  3681     private Type glbFlattened(List<Type> flatBounds, Type errT) {
  3682         List<Type> bounds = closureMin(flatBounds);
  3684         if (bounds.isEmpty()) {             // length == 0
  3685             return syms.objectType;
  3686         } else if (bounds.tail.isEmpty()) { // length == 1
  3687             return bounds.head;
  3688         } else {                            // length > 1
  3689             int classCount = 0;
  3690             List<Type> lowers = List.nil();
  3691             for (Type bound : bounds) {
  3692                 if (!bound.isInterface()) {
  3693                     classCount++;
  3694                     Type lower = cvarLowerBound(bound);
  3695                     if (bound != lower && !lower.hasTag(BOT))
  3696                         lowers = insert(lowers, lower);
  3699             if (classCount > 1) {
  3700                 if (lowers.isEmpty())
  3701                     return createErrorType(errT);
  3702                 else
  3703                     return glbFlattened(union(bounds, lowers), errT);
  3706         return makeCompoundType(bounds);
  3708     // </editor-fold>
  3710     // <editor-fold defaultstate="collapsed" desc="hashCode">
  3711     /**
  3712      * Compute a hash code on a type.
  3713      */
  3714     public int hashCode(Type t) {
  3715         return hashCode.visit(t);
  3717     // where
  3718         private static final UnaryVisitor<Integer> hashCode = new UnaryVisitor<Integer>() {
  3720             public Integer visitType(Type t, Void ignored) {
  3721                 return t.getTag().ordinal();
  3724             @Override
  3725             public Integer visitClassType(ClassType t, Void ignored) {
  3726                 int result = visit(t.getEnclosingType());
  3727                 result *= 127;
  3728                 result += t.tsym.flatName().hashCode();
  3729                 for (Type s : t.getTypeArguments()) {
  3730                     result *= 127;
  3731                     result += visit(s);
  3733                 return result;
  3736             @Override
  3737             public Integer visitMethodType(MethodType t, Void ignored) {
  3738                 int h = METHOD.ordinal();
  3739                 for (List<Type> thisargs = t.argtypes;
  3740                      thisargs.tail != null;
  3741                      thisargs = thisargs.tail)
  3742                     h = (h << 5) + visit(thisargs.head);
  3743                 return (h << 5) + visit(t.restype);
  3746             @Override
  3747             public Integer visitWildcardType(WildcardType t, Void ignored) {
  3748                 int result = t.kind.hashCode();
  3749                 if (t.type != null) {
  3750                     result *= 127;
  3751                     result += visit(t.type);
  3753                 return result;
  3756             @Override
  3757             public Integer visitArrayType(ArrayType t, Void ignored) {
  3758                 return visit(t.elemtype) + 12;
  3761             @Override
  3762             public Integer visitTypeVar(TypeVar t, Void ignored) {
  3763                 return System.identityHashCode(t.tsym);
  3766             @Override
  3767             public Integer visitUndetVar(UndetVar t, Void ignored) {
  3768                 return System.identityHashCode(t);
  3771             @Override
  3772             public Integer visitErrorType(ErrorType t, Void ignored) {
  3773                 return 0;
  3775         };
  3776     // </editor-fold>
  3778     // <editor-fold defaultstate="collapsed" desc="Return-Type-Substitutable">
  3779     /**
  3780      * Does t have a result that is a subtype of the result type of s,
  3781      * suitable for covariant returns?  It is assumed that both types
  3782      * are (possibly polymorphic) method types.  Monomorphic method
  3783      * types are handled in the obvious way.  Polymorphic method types
  3784      * require renaming all type variables of one to corresponding
  3785      * type variables in the other, where correspondence is by
  3786      * position in the type parameter list. */
  3787     public boolean resultSubtype(Type t, Type s, Warner warner) {
  3788         List<Type> tvars = t.getTypeArguments();
  3789         List<Type> svars = s.getTypeArguments();
  3790         Type tres = t.getReturnType();
  3791         Type sres = subst(s.getReturnType(), svars, tvars);
  3792         return covariantReturnType(tres, sres, warner);
  3795     /**
  3796      * Return-Type-Substitutable.
  3797      * @jls section 8.4.5
  3798      */
  3799     public boolean returnTypeSubstitutable(Type r1, Type r2) {
  3800         if (hasSameArgs(r1, r2))
  3801             return resultSubtype(r1, r2, noWarnings);
  3802         else
  3803             return covariantReturnType(r1.getReturnType(),
  3804                                        erasure(r2.getReturnType()),
  3805                                        noWarnings);
  3808     public boolean returnTypeSubstitutable(Type r1,
  3809                                            Type r2, Type r2res,
  3810                                            Warner warner) {
  3811         if (isSameType(r1.getReturnType(), r2res))
  3812             return true;
  3813         if (r1.getReturnType().isPrimitive() || r2res.isPrimitive())
  3814             return false;
  3816         if (hasSameArgs(r1, r2))
  3817             return covariantReturnType(r1.getReturnType(), r2res, warner);
  3818         if (!allowCovariantReturns)
  3819             return false;
  3820         if (isSubtypeUnchecked(r1.getReturnType(), r2res, warner))
  3821             return true;
  3822         if (!isSubtype(r1.getReturnType(), erasure(r2res)))
  3823             return false;
  3824         warner.warn(LintCategory.UNCHECKED);
  3825         return true;
  3828     /**
  3829      * Is t an appropriate return type in an overrider for a
  3830      * method that returns s?
  3831      */
  3832     public boolean covariantReturnType(Type t, Type s, Warner warner) {
  3833         return
  3834             isSameType(t, s) ||
  3835             allowCovariantReturns &&
  3836             !t.isPrimitive() &&
  3837             !s.isPrimitive() &&
  3838             isAssignable(t, s, warner);
  3840     // </editor-fold>
  3842     // <editor-fold defaultstate="collapsed" desc="Box/unbox support">
  3843     /**
  3844      * Return the class that boxes the given primitive.
  3845      */
  3846     public ClassSymbol boxedClass(Type t) {
  3847         return reader.enterClass(syms.boxedName[t.getTag().ordinal()]);
  3850     /**
  3851      * Return the boxed type if 't' is primitive, otherwise return 't' itself.
  3852      */
  3853     public Type boxedTypeOrType(Type t) {
  3854         return t.isPrimitive() ?
  3855             boxedClass(t).type :
  3856             t;
  3859     /**
  3860      * Return the primitive type corresponding to a boxed type.
  3861      */
  3862     public Type unboxedType(Type t) {
  3863         if (allowBoxing) {
  3864             for (int i=0; i<syms.boxedName.length; i++) {
  3865                 Name box = syms.boxedName[i];
  3866                 if (box != null &&
  3867                     asSuper(t, reader.enterClass(box)) != null)
  3868                     return syms.typeOfTag[i];
  3871         return Type.noType;
  3874     /**
  3875      * Return the unboxed type if 't' is a boxed class, otherwise return 't' itself.
  3876      */
  3877     public Type unboxedTypeOrType(Type t) {
  3878         Type unboxedType = unboxedType(t);
  3879         return unboxedType.hasTag(NONE) ? t : unboxedType;
  3881     // </editor-fold>
  3883     // <editor-fold defaultstate="collapsed" desc="Capture conversion">
  3884     /*
  3885      * JLS 5.1.10 Capture Conversion:
  3887      * Let G name a generic type declaration with n formal type
  3888      * parameters A1 ... An with corresponding bounds U1 ... Un. There
  3889      * exists a capture conversion from G<T1 ... Tn> to G<S1 ... Sn>,
  3890      * where, for 1 <= i <= n:
  3892      * + If Ti is a wildcard type argument (4.5.1) of the form ? then
  3893      *   Si is a fresh type variable whose upper bound is
  3894      *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is the null
  3895      *   type.
  3897      * + If Ti is a wildcard type argument of the form ? extends Bi,
  3898      *   then Si is a fresh type variable whose upper bound is
  3899      *   glb(Bi, Ui[A1 := S1, ..., An := Sn]) and whose lower bound is
  3900      *   the null type, where glb(V1,... ,Vm) is V1 & ... & Vm. It is
  3901      *   a compile-time error if for any two classes (not interfaces)
  3902      *   Vi and Vj,Vi is not a subclass of Vj or vice versa.
  3904      * + If Ti is a wildcard type argument of the form ? super Bi,
  3905      *   then Si is a fresh type variable whose upper bound is
  3906      *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is Bi.
  3908      * + Otherwise, Si = Ti.
  3910      * Capture conversion on any type other than a parameterized type
  3911      * (4.5) acts as an identity conversion (5.1.1). Capture
  3912      * conversions never require a special action at run time and
  3913      * therefore never throw an exception at run time.
  3915      * Capture conversion is not applied recursively.
  3916      */
  3917     /**
  3918      * Capture conversion as specified by the JLS.
  3919      */
  3921     public List<Type> capture(List<Type> ts) {
  3922         List<Type> buf = List.nil();
  3923         for (Type t : ts) {
  3924             buf = buf.prepend(capture(t));
  3926         return buf.reverse();
  3929     public Type capture(Type t) {
  3930         if (!t.hasTag(CLASS)) {
  3931             return t;
  3933         if (t.getEnclosingType() != Type.noType) {
  3934             Type capturedEncl = capture(t.getEnclosingType());
  3935             if (capturedEncl != t.getEnclosingType()) {
  3936                 Type type1 = memberType(capturedEncl, t.tsym);
  3937                 t = subst(type1, t.tsym.type.getTypeArguments(), t.getTypeArguments());
  3940         t = t.unannotatedType();
  3941         ClassType cls = (ClassType)t;
  3942         if (cls.isRaw() || !cls.isParameterized())
  3943             return cls;
  3945         ClassType G = (ClassType)cls.asElement().asType();
  3946         List<Type> A = G.getTypeArguments();
  3947         List<Type> T = cls.getTypeArguments();
  3948         List<Type> S = freshTypeVariables(T);
  3950         List<Type> currentA = A;
  3951         List<Type> currentT = T;
  3952         List<Type> currentS = S;
  3953         boolean captured = false;
  3954         while (!currentA.isEmpty() &&
  3955                !currentT.isEmpty() &&
  3956                !currentS.isEmpty()) {
  3957             if (currentS.head != currentT.head) {
  3958                 captured = true;
  3959                 WildcardType Ti = (WildcardType)currentT.head.unannotatedType();
  3960                 Type Ui = currentA.head.getUpperBound();
  3961                 CapturedType Si = (CapturedType)currentS.head.unannotatedType();
  3962                 if (Ui == null)
  3963                     Ui = syms.objectType;
  3964                 switch (Ti.kind) {
  3965                 case UNBOUND:
  3966                     Si.bound = subst(Ui, A, S);
  3967                     Si.lower = syms.botType;
  3968                     break;
  3969                 case EXTENDS:
  3970                     Si.bound = glb(Ti.getExtendsBound(), subst(Ui, A, S));
  3971                     Si.lower = syms.botType;
  3972                     break;
  3973                 case SUPER:
  3974                     Si.bound = subst(Ui, A, S);
  3975                     Si.lower = Ti.getSuperBound();
  3976                     break;
  3978                 Type tmpBound = Si.bound.hasTag(UNDETVAR) ? ((UndetVar)Si.bound).qtype : Si.bound;
  3979                 Type tmpLower = Si.lower.hasTag(UNDETVAR) ? ((UndetVar)Si.lower).qtype : Si.lower;
  3980                 if (!Si.bound.hasTag(ERROR) &&
  3981                     !Si.lower.hasTag(ERROR) &&
  3982                     isSameType(tmpBound, tmpLower, false)) {
  3983                     currentS.head = Si.bound;
  3986             currentA = currentA.tail;
  3987             currentT = currentT.tail;
  3988             currentS = currentS.tail;
  3990         if (!currentA.isEmpty() || !currentT.isEmpty() || !currentS.isEmpty())
  3991             return erasure(t); // some "rare" type involved
  3993         if (captured)
  3994             return new ClassType(cls.getEnclosingType(), S, cls.tsym);
  3995         else
  3996             return t;
  3998     // where
  3999         public List<Type> freshTypeVariables(List<Type> types) {
  4000             ListBuffer<Type> result = new ListBuffer<>();
  4001             for (Type t : types) {
  4002                 if (t.hasTag(WILDCARD)) {
  4003                     t = t.unannotatedType();
  4004                     Type bound = ((WildcardType)t).getExtendsBound();
  4005                     if (bound == null)
  4006                         bound = syms.objectType;
  4007                     result.append(new CapturedType(capturedName,
  4008                                                    syms.noSymbol,
  4009                                                    bound,
  4010                                                    syms.botType,
  4011                                                    (WildcardType)t));
  4012                 } else {
  4013                     result.append(t);
  4016             return result.toList();
  4018     // </editor-fold>
  4020     // <editor-fold defaultstate="collapsed" desc="Internal utility methods">
  4021     private boolean sideCast(Type from, Type to, Warner warn) {
  4022         // We are casting from type $from$ to type $to$, which are
  4023         // non-final unrelated types.  This method
  4024         // tries to reject a cast by transferring type parameters
  4025         // from $to$ to $from$ by common superinterfaces.
  4026         boolean reverse = false;
  4027         Type target = to;
  4028         if ((to.tsym.flags() & INTERFACE) == 0) {
  4029             Assert.check((from.tsym.flags() & INTERFACE) != 0);
  4030             reverse = true;
  4031             to = from;
  4032             from = target;
  4034         List<Type> commonSupers = superClosure(to, erasure(from));
  4035         boolean giveWarning = commonSupers.isEmpty();
  4036         // The arguments to the supers could be unified here to
  4037         // get a more accurate analysis
  4038         while (commonSupers.nonEmpty()) {
  4039             Type t1 = asSuper(from, commonSupers.head.tsym);
  4040             Type t2 = commonSupers.head; // same as asSuper(to, commonSupers.head.tsym);
  4041             if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
  4042                 return false;
  4043             giveWarning = giveWarning || (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2));
  4044             commonSupers = commonSupers.tail;
  4046         if (giveWarning && !isReifiable(reverse ? from : to))
  4047             warn.warn(LintCategory.UNCHECKED);
  4048         if (!allowCovariantReturns)
  4049             // reject if there is a common method signature with
  4050             // incompatible return types.
  4051             chk.checkCompatibleAbstracts(warn.pos(), from, to);
  4052         return true;
  4055     private boolean sideCastFinal(Type from, Type to, Warner warn) {
  4056         // We are casting from type $from$ to type $to$, which are
  4057         // unrelated types one of which is final and the other of
  4058         // which is an interface.  This method
  4059         // tries to reject a cast by transferring type parameters
  4060         // from the final class to the interface.
  4061         boolean reverse = false;
  4062         Type target = to;
  4063         if ((to.tsym.flags() & INTERFACE) == 0) {
  4064             Assert.check((from.tsym.flags() & INTERFACE) != 0);
  4065             reverse = true;
  4066             to = from;
  4067             from = target;
  4069         Assert.check((from.tsym.flags() & FINAL) != 0);
  4070         Type t1 = asSuper(from, to.tsym);
  4071         if (t1 == null) return false;
  4072         Type t2 = to;
  4073         if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
  4074             return false;
  4075         if (!allowCovariantReturns)
  4076             // reject if there is a common method signature with
  4077             // incompatible return types.
  4078             chk.checkCompatibleAbstracts(warn.pos(), from, to);
  4079         if (!isReifiable(target) &&
  4080             (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2)))
  4081             warn.warn(LintCategory.UNCHECKED);
  4082         return true;
  4085     private boolean giveWarning(Type from, Type to) {
  4086         List<Type> bounds = to.isCompound() ?
  4087                 ((IntersectionClassType)to.unannotatedType()).getComponents() : List.of(to);
  4088         for (Type b : bounds) {
  4089             Type subFrom = asSub(from, b.tsym);
  4090             if (b.isParameterized() &&
  4091                     (!(isUnbounded(b) ||
  4092                     isSubtype(from, b) ||
  4093                     ((subFrom != null) && containsType(b.allparams(), subFrom.allparams()))))) {
  4094                 return true;
  4097         return false;
  4100     private List<Type> superClosure(Type t, Type s) {
  4101         List<Type> cl = List.nil();
  4102         for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
  4103             if (isSubtype(s, erasure(l.head))) {
  4104                 cl = insert(cl, l.head);
  4105             } else {
  4106                 cl = union(cl, superClosure(l.head, s));
  4109         return cl;
  4112     private boolean containsTypeEquivalent(Type t, Type s) {
  4113         return
  4114             isSameType(t, s) || // shortcut
  4115             containsType(t, s) && containsType(s, t);
  4118     // <editor-fold defaultstate="collapsed" desc="adapt">
  4119     /**
  4120      * Adapt a type by computing a substitution which maps a source
  4121      * type to a target type.
  4123      * @param source    the source type
  4124      * @param target    the target type
  4125      * @param from      the type variables of the computed substitution
  4126      * @param to        the types of the computed substitution.
  4127      */
  4128     public void adapt(Type source,
  4129                        Type target,
  4130                        ListBuffer<Type> from,
  4131                        ListBuffer<Type> to) throws AdaptFailure {
  4132         new Adapter(from, to).adapt(source, target);
  4135     class Adapter extends SimpleVisitor<Void, Type> {
  4137         ListBuffer<Type> from;
  4138         ListBuffer<Type> to;
  4139         Map<Symbol,Type> mapping;
  4141         Adapter(ListBuffer<Type> from, ListBuffer<Type> to) {
  4142             this.from = from;
  4143             this.to = to;
  4144             mapping = new HashMap<Symbol,Type>();
  4147         public void adapt(Type source, Type target) throws AdaptFailure {
  4148             visit(source, target);
  4149             List<Type> fromList = from.toList();
  4150             List<Type> toList = to.toList();
  4151             while (!fromList.isEmpty()) {
  4152                 Type val = mapping.get(fromList.head.tsym);
  4153                 if (toList.head != val)
  4154                     toList.head = val;
  4155                 fromList = fromList.tail;
  4156                 toList = toList.tail;
  4160         @Override
  4161         public Void visitClassType(ClassType source, Type target) throws AdaptFailure {
  4162             if (target.hasTag(CLASS))
  4163                 adaptRecursive(source.allparams(), target.allparams());
  4164             return null;
  4167         @Override
  4168         public Void visitArrayType(ArrayType source, Type target) throws AdaptFailure {
  4169             if (target.hasTag(ARRAY))
  4170                 adaptRecursive(elemtype(source), elemtype(target));
  4171             return null;
  4174         @Override
  4175         public Void visitWildcardType(WildcardType source, Type target) throws AdaptFailure {
  4176             if (source.isExtendsBound())
  4177                 adaptRecursive(wildUpperBound(source), wildUpperBound(target));
  4178             else if (source.isSuperBound())
  4179                 adaptRecursive(wildLowerBound(source), wildLowerBound(target));
  4180             return null;
  4183         @Override
  4184         public Void visitTypeVar(TypeVar source, Type target) throws AdaptFailure {
  4185             // Check to see if there is
  4186             // already a mapping for $source$, in which case
  4187             // the old mapping will be merged with the new
  4188             Type val = mapping.get(source.tsym);
  4189             if (val != null) {
  4190                 if (val.isSuperBound() && target.isSuperBound()) {
  4191                     val = isSubtype(wildLowerBound(val), wildLowerBound(target))
  4192                         ? target : val;
  4193                 } else if (val.isExtendsBound() && target.isExtendsBound()) {
  4194                     val = isSubtype(wildUpperBound(val), wildUpperBound(target))
  4195                         ? val : target;
  4196                 } else if (!isSameType(val, target)) {
  4197                     throw new AdaptFailure();
  4199             } else {
  4200                 val = target;
  4201                 from.append(source);
  4202                 to.append(target);
  4204             mapping.put(source.tsym, val);
  4205             return null;
  4208         @Override
  4209         public Void visitType(Type source, Type target) {
  4210             return null;
  4213         private Set<TypePair> cache = new HashSet<TypePair>();
  4215         private void adaptRecursive(Type source, Type target) {
  4216             TypePair pair = new TypePair(source, target);
  4217             if (cache.add(pair)) {
  4218                 try {
  4219                     visit(source, target);
  4220                 } finally {
  4221                     cache.remove(pair);
  4226         private void adaptRecursive(List<Type> source, List<Type> target) {
  4227             if (source.length() == target.length()) {
  4228                 while (source.nonEmpty()) {
  4229                     adaptRecursive(source.head, target.head);
  4230                     source = source.tail;
  4231                     target = target.tail;
  4237     public static class AdaptFailure extends RuntimeException {
  4238         static final long serialVersionUID = -7490231548272701566L;
  4241     private void adaptSelf(Type t,
  4242                            ListBuffer<Type> from,
  4243                            ListBuffer<Type> to) {
  4244         try {
  4245             //if (t.tsym.type != t)
  4246                 adapt(t.tsym.type, t, from, to);
  4247         } catch (AdaptFailure ex) {
  4248             // Adapt should never fail calculating a mapping from
  4249             // t.tsym.type to t as there can be no merge problem.
  4250             throw new AssertionError(ex);
  4253     // </editor-fold>
  4255     /**
  4256      * Rewrite all type variables (universal quantifiers) in the given
  4257      * type to wildcards (existential quantifiers).  This is used to
  4258      * determine if a cast is allowed.  For example, if high is true
  4259      * and {@code T <: Number}, then {@code List<T>} is rewritten to
  4260      * {@code List<?  extends Number>}.  Since {@code List<Integer> <:
  4261      * List<? extends Number>} a {@code List<T>} can be cast to {@code
  4262      * List<Integer>} with a warning.
  4263      * @param t a type
  4264      * @param high if true return an upper bound; otherwise a lower
  4265      * bound
  4266      * @param rewriteTypeVars only rewrite captured wildcards if false;
  4267      * otherwise rewrite all type variables
  4268      * @return the type rewritten with wildcards (existential
  4269      * quantifiers) only
  4270      */
  4271     private Type rewriteQuantifiers(Type t, boolean high, boolean rewriteTypeVars) {
  4272         return new Rewriter(high, rewriteTypeVars).visit(t);
  4275     class Rewriter extends UnaryVisitor<Type> {
  4277         boolean high;
  4278         boolean rewriteTypeVars;
  4280         Rewriter(boolean high, boolean rewriteTypeVars) {
  4281             this.high = high;
  4282             this.rewriteTypeVars = rewriteTypeVars;
  4285         @Override
  4286         public Type visitClassType(ClassType t, Void s) {
  4287             ListBuffer<Type> rewritten = new ListBuffer<Type>();
  4288             boolean changed = false;
  4289             for (Type arg : t.allparams()) {
  4290                 Type bound = visit(arg);
  4291                 if (arg != bound) {
  4292                     changed = true;
  4294                 rewritten.append(bound);
  4296             if (changed)
  4297                 return subst(t.tsym.type,
  4298                         t.tsym.type.allparams(),
  4299                         rewritten.toList());
  4300             else
  4301                 return t;
  4304         public Type visitType(Type t, Void s) {
  4305             return t;
  4308         @Override
  4309         public Type visitCapturedType(CapturedType t, Void s) {
  4310             Type w_bound = t.wildcard.type;
  4311             Type bound = w_bound.contains(t) ?
  4312                         erasure(w_bound) :
  4313                         visit(w_bound);
  4314             return rewriteAsWildcardType(visit(bound), t.wildcard.bound, t.wildcard.kind);
  4317         @Override
  4318         public Type visitTypeVar(TypeVar t, Void s) {
  4319             if (rewriteTypeVars) {
  4320                 Type bound = t.bound.contains(t) ?
  4321                         erasure(t.bound) :
  4322                         visit(t.bound);
  4323                 return rewriteAsWildcardType(bound, t, EXTENDS);
  4324             } else {
  4325                 return t;
  4329         @Override
  4330         public Type visitWildcardType(WildcardType t, Void s) {
  4331             Type bound2 = visit(t.type);
  4332             return t.type == bound2 ? t : rewriteAsWildcardType(bound2, t.bound, t.kind);
  4335         private Type rewriteAsWildcardType(Type bound, TypeVar formal, BoundKind bk) {
  4336             switch (bk) {
  4337                case EXTENDS: return high ?
  4338                        makeExtendsWildcard(B(bound), formal) :
  4339                        makeExtendsWildcard(syms.objectType, formal);
  4340                case SUPER: return high ?
  4341                        makeSuperWildcard(syms.botType, formal) :
  4342                        makeSuperWildcard(B(bound), formal);
  4343                case UNBOUND: return makeExtendsWildcard(syms.objectType, formal);
  4344                default:
  4345                    Assert.error("Invalid bound kind " + bk);
  4346                    return null;
  4350         Type B(Type t) {
  4351             while (t.hasTag(WILDCARD)) {
  4352                 WildcardType w = (WildcardType)t.unannotatedType();
  4353                 t = high ?
  4354                     w.getExtendsBound() :
  4355                     w.getSuperBound();
  4356                 if (t == null) {
  4357                     t = high ? syms.objectType : syms.botType;
  4360             return t;
  4365     /**
  4366      * Create a wildcard with the given upper (extends) bound; create
  4367      * an unbounded wildcard if bound is Object.
  4369      * @param bound the upper bound
  4370      * @param formal the formal type parameter that will be
  4371      * substituted by the wildcard
  4372      */
  4373     private WildcardType makeExtendsWildcard(Type bound, TypeVar formal) {
  4374         if (bound == syms.objectType) {
  4375             return new WildcardType(syms.objectType,
  4376                                     BoundKind.UNBOUND,
  4377                                     syms.boundClass,
  4378                                     formal);
  4379         } else {
  4380             return new WildcardType(bound,
  4381                                     BoundKind.EXTENDS,
  4382                                     syms.boundClass,
  4383                                     formal);
  4387     /**
  4388      * Create a wildcard with the given lower (super) bound; create an
  4389      * unbounded wildcard if bound is bottom (type of {@code null}).
  4391      * @param bound the lower bound
  4392      * @param formal the formal type parameter that will be
  4393      * substituted by the wildcard
  4394      */
  4395     private WildcardType makeSuperWildcard(Type bound, TypeVar formal) {
  4396         if (bound.hasTag(BOT)) {
  4397             return new WildcardType(syms.objectType,
  4398                                     BoundKind.UNBOUND,
  4399                                     syms.boundClass,
  4400                                     formal);
  4401         } else {
  4402             return new WildcardType(bound,
  4403                                     BoundKind.SUPER,
  4404                                     syms.boundClass,
  4405                                     formal);
  4409     /**
  4410      * A wrapper for a type that allows use in sets.
  4411      */
  4412     public static class UniqueType {
  4413         public final Type type;
  4414         final Types types;
  4416         public UniqueType(Type type, Types types) {
  4417             this.type = type;
  4418             this.types = types;
  4421         public int hashCode() {
  4422             return types.hashCode(type);
  4425         public boolean equals(Object obj) {
  4426             return (obj instanceof UniqueType) &&
  4427                 types.isSameAnnotatedType(type, ((UniqueType)obj).type);
  4430         public String toString() {
  4431             return type.toString();
  4435     // </editor-fold>
  4437     // <editor-fold defaultstate="collapsed" desc="Visitors">
  4438     /**
  4439      * A default visitor for types.  All visitor methods except
  4440      * visitType are implemented by delegating to visitType.  Concrete
  4441      * subclasses must provide an implementation of visitType and can
  4442      * override other methods as needed.
  4444      * @param <R> the return type of the operation implemented by this
  4445      * visitor; use Void if no return type is needed.
  4446      * @param <S> the type of the second argument (the first being the
  4447      * type itself) of the operation implemented by this visitor; use
  4448      * Void if a second argument is not needed.
  4449      */
  4450     public static abstract class DefaultTypeVisitor<R,S> implements Type.Visitor<R,S> {
  4451         final public R visit(Type t, S s)               { return t.accept(this, s); }
  4452         public R visitClassType(ClassType t, S s)       { return visitType(t, s); }
  4453         public R visitWildcardType(WildcardType t, S s) { return visitType(t, s); }
  4454         public R visitArrayType(ArrayType t, S s)       { return visitType(t, s); }
  4455         public R visitMethodType(MethodType t, S s)     { return visitType(t, s); }
  4456         public R visitPackageType(PackageType t, S s)   { return visitType(t, s); }
  4457         public R visitTypeVar(TypeVar t, S s)           { return visitType(t, s); }
  4458         public R visitCapturedType(CapturedType t, S s) { return visitType(t, s); }
  4459         public R visitForAll(ForAll t, S s)             { return visitType(t, s); }
  4460         public R visitUndetVar(UndetVar t, S s)         { return visitType(t, s); }
  4461         public R visitErrorType(ErrorType t, S s)       { return visitType(t, s); }
  4462         // Pretend annotations don't exist
  4463         public R visitAnnotatedType(AnnotatedType t, S s) { return visit(t.unannotatedType(), s); }
  4466     /**
  4467      * A default visitor for symbols.  All visitor methods except
  4468      * visitSymbol are implemented by delegating to visitSymbol.  Concrete
  4469      * subclasses must provide an implementation of visitSymbol and can
  4470      * override other methods as needed.
  4472      * @param <R> the return type of the operation implemented by this
  4473      * visitor; use Void if no return type is needed.
  4474      * @param <S> the type of the second argument (the first being the
  4475      * symbol itself) of the operation implemented by this visitor; use
  4476      * Void if a second argument is not needed.
  4477      */
  4478     public static abstract class DefaultSymbolVisitor<R,S> implements Symbol.Visitor<R,S> {
  4479         final public R visit(Symbol s, S arg)                   { return s.accept(this, arg); }
  4480         public R visitClassSymbol(ClassSymbol s, S arg)         { return visitSymbol(s, arg); }
  4481         public R visitMethodSymbol(MethodSymbol s, S arg)       { return visitSymbol(s, arg); }
  4482         public R visitOperatorSymbol(OperatorSymbol s, S arg)   { return visitSymbol(s, arg); }
  4483         public R visitPackageSymbol(PackageSymbol s, S arg)     { return visitSymbol(s, arg); }
  4484         public R visitTypeSymbol(TypeSymbol s, S arg)           { return visitSymbol(s, arg); }
  4485         public R visitVarSymbol(VarSymbol s, S arg)             { return visitSymbol(s, arg); }
  4488     /**
  4489      * A <em>simple</em> visitor for types.  This visitor is simple as
  4490      * captured wildcards, for-all types (generic methods), and
  4491      * undetermined type variables (part of inference) are hidden.
  4492      * Captured wildcards are hidden by treating them as type
  4493      * variables and the rest are hidden by visiting their qtypes.
  4495      * @param <R> the return type of the operation implemented by this
  4496      * visitor; use Void if no return type is needed.
  4497      * @param <S> the type of the second argument (the first being the
  4498      * type itself) of the operation implemented by this visitor; use
  4499      * Void if a second argument is not needed.
  4500      */
  4501     public static abstract class SimpleVisitor<R,S> extends DefaultTypeVisitor<R,S> {
  4502         @Override
  4503         public R visitCapturedType(CapturedType t, S s) {
  4504             return visitTypeVar(t, s);
  4506         @Override
  4507         public R visitForAll(ForAll t, S s) {
  4508             return visit(t.qtype, s);
  4510         @Override
  4511         public R visitUndetVar(UndetVar t, S s) {
  4512             return visit(t.qtype, s);
  4516     /**
  4517      * A plain relation on types.  That is a 2-ary function on the
  4518      * form Type&nbsp;&times;&nbsp;Type&nbsp;&rarr;&nbsp;Boolean.
  4519      * <!-- In plain text: Type x Type -> Boolean -->
  4520      */
  4521     public static abstract class TypeRelation extends SimpleVisitor<Boolean,Type> {}
  4523     /**
  4524      * A convenience visitor for implementing operations that only
  4525      * require one argument (the type itself), that is, unary
  4526      * operations.
  4528      * @param <R> the return type of the operation implemented by this
  4529      * visitor; use Void if no return type is needed.
  4530      */
  4531     public static abstract class UnaryVisitor<R> extends SimpleVisitor<R,Void> {
  4532         final public R visit(Type t) { return t.accept(this, null); }
  4535     /**
  4536      * A visitor for implementing a mapping from types to types.  The
  4537      * default behavior of this class is to implement the identity
  4538      * mapping (mapping a type to itself).  This can be overridden in
  4539      * subclasses.
  4541      * @param <S> the type of the second argument (the first being the
  4542      * type itself) of this mapping; use Void if a second argument is
  4543      * not needed.
  4544      */
  4545     public static class MapVisitor<S> extends DefaultTypeVisitor<Type,S> {
  4546         final public Type visit(Type t) { return t.accept(this, null); }
  4547         public Type visitType(Type t, S s) { return t; }
  4549     // </editor-fold>
  4552     // <editor-fold defaultstate="collapsed" desc="Annotation support">
  4554     public RetentionPolicy getRetention(Attribute.Compound a) {
  4555         return getRetention(a.type.tsym);
  4558     public RetentionPolicy getRetention(Symbol sym) {
  4559         RetentionPolicy vis = RetentionPolicy.CLASS; // the default
  4560         Attribute.Compound c = sym.attribute(syms.retentionType.tsym);
  4561         if (c != null) {
  4562             Attribute value = c.member(names.value);
  4563             if (value != null && value instanceof Attribute.Enum) {
  4564                 Name levelName = ((Attribute.Enum)value).value.name;
  4565                 if (levelName == names.SOURCE) vis = RetentionPolicy.SOURCE;
  4566                 else if (levelName == names.CLASS) vis = RetentionPolicy.CLASS;
  4567                 else if (levelName == names.RUNTIME) vis = RetentionPolicy.RUNTIME;
  4568                 else ;// /* fail soft */ throw new AssertionError(levelName);
  4571         return vis;
  4573     // </editor-fold>
  4575     // <editor-fold defaultstate="collapsed" desc="Signature Generation">
  4577     public static abstract class SignatureGenerator {
  4579         private final Types types;
  4581         protected abstract void append(char ch);
  4582         protected abstract void append(byte[] ba);
  4583         protected abstract void append(Name name);
  4584         protected void classReference(ClassSymbol c) { /* by default: no-op */ }
  4586         protected SignatureGenerator(Types types) {
  4587             this.types = types;
  4590         /**
  4591          * Assemble signature of given type in string buffer.
  4592          */
  4593         public void assembleSig(Type type) {
  4594             type = type.unannotatedType();
  4595             switch (type.getTag()) {
  4596                 case BYTE:
  4597                     append('B');
  4598                     break;
  4599                 case SHORT:
  4600                     append('S');
  4601                     break;
  4602                 case CHAR:
  4603                     append('C');
  4604                     break;
  4605                 case INT:
  4606                     append('I');
  4607                     break;
  4608                 case LONG:
  4609                     append('J');
  4610                     break;
  4611                 case FLOAT:
  4612                     append('F');
  4613                     break;
  4614                 case DOUBLE:
  4615                     append('D');
  4616                     break;
  4617                 case BOOLEAN:
  4618                     append('Z');
  4619                     break;
  4620                 case VOID:
  4621                     append('V');
  4622                     break;
  4623                 case CLASS:
  4624                     append('L');
  4625                     assembleClassSig(type);
  4626                     append(';');
  4627                     break;
  4628                 case ARRAY:
  4629                     ArrayType at = (ArrayType) type;
  4630                     append('[');
  4631                     assembleSig(at.elemtype);
  4632                     break;
  4633                 case METHOD:
  4634                     MethodType mt = (MethodType) type;
  4635                     append('(');
  4636                     assembleSig(mt.argtypes);
  4637                     append(')');
  4638                     assembleSig(mt.restype);
  4639                     if (hasTypeVar(mt.thrown)) {
  4640                         for (List<Type> l = mt.thrown; l.nonEmpty(); l = l.tail) {
  4641                             append('^');
  4642                             assembleSig(l.head);
  4645                     break;
  4646                 case WILDCARD: {
  4647                     Type.WildcardType ta = (Type.WildcardType) type;
  4648                     switch (ta.kind) {
  4649                         case SUPER:
  4650                             append('-');
  4651                             assembleSig(ta.type);
  4652                             break;
  4653                         case EXTENDS:
  4654                             append('+');
  4655                             assembleSig(ta.type);
  4656                             break;
  4657                         case UNBOUND:
  4658                             append('*');
  4659                             break;
  4660                         default:
  4661                             throw new AssertionError(ta.kind);
  4663                     break;
  4665                 case TYPEVAR:
  4666                     append('T');
  4667                     append(type.tsym.name);
  4668                     append(';');
  4669                     break;
  4670                 case FORALL:
  4671                     Type.ForAll ft = (Type.ForAll) type;
  4672                     assembleParamsSig(ft.tvars);
  4673                     assembleSig(ft.qtype);
  4674                     break;
  4675                 default:
  4676                     throw new AssertionError("typeSig " + type.getTag());
  4680         public boolean hasTypeVar(List<Type> l) {
  4681             while (l.nonEmpty()) {
  4682                 if (l.head.hasTag(TypeTag.TYPEVAR)) {
  4683                     return true;
  4685                 l = l.tail;
  4687             return false;
  4690         public void assembleClassSig(Type type) {
  4691             type = type.unannotatedType();
  4692             ClassType ct = (ClassType) type;
  4693             ClassSymbol c = (ClassSymbol) ct.tsym;
  4694             classReference(c);
  4695             Type outer = ct.getEnclosingType();
  4696             if (outer.allparams().nonEmpty()) {
  4697                 boolean rawOuter =
  4698                         c.owner.kind == Kinds.MTH || // either a local class
  4699                         c.name == types.names.empty; // or anonymous
  4700                 assembleClassSig(rawOuter
  4701                         ? types.erasure(outer)
  4702                         : outer);
  4703                 append(rawOuter ? '$' : '.');
  4704                 Assert.check(c.flatname.startsWith(c.owner.enclClass().flatname));
  4705                 append(rawOuter
  4706                         ? c.flatname.subName(c.owner.enclClass().flatname.getByteLength() + 1, c.flatname.getByteLength())
  4707                         : c.name);
  4708             } else {
  4709                 append(externalize(c.flatname));
  4711             if (ct.getTypeArguments().nonEmpty()) {
  4712                 append('<');
  4713                 assembleSig(ct.getTypeArguments());
  4714                 append('>');
  4718         public void assembleParamsSig(List<Type> typarams) {
  4719             append('<');
  4720             for (List<Type> ts = typarams; ts.nonEmpty(); ts = ts.tail) {
  4721                 Type.TypeVar tvar = (Type.TypeVar) ts.head;
  4722                 append(tvar.tsym.name);
  4723                 List<Type> bounds = types.getBounds(tvar);
  4724                 if ((bounds.head.tsym.flags() & INTERFACE) != 0) {
  4725                     append(':');
  4727                 for (List<Type> l = bounds; l.nonEmpty(); l = l.tail) {
  4728                     append(':');
  4729                     assembleSig(l.head);
  4732             append('>');
  4735         private void assembleSig(List<Type> types) {
  4736             for (List<Type> ts = types; ts.nonEmpty(); ts = ts.tail) {
  4737                 assembleSig(ts.head);
  4741     // </editor-fold>

mercurial