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

Thu, 22 Aug 2013 10:22:44 +0100

author
vromero
date
Thu, 22 Aug 2013 10:22:44 +0100
changeset 1973
7a4717f3ea7b
parent 1919
3155e77d2676
child 2000
4a6acc42c3a1
permissions
-rw-r--r--

8022316: Generic throws, overriding and method reference
Reviewed-by: jjg, mcimadamore

     1 /*
     2  * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    26 package com.sun.tools.javac.code;
    28 import java.lang.ref.SoftReference;
    29 import java.util.HashSet;
    30 import java.util.HashMap;
    31 import java.util.Locale;
    32 import java.util.Map;
    33 import java.util.Set;
    34 import java.util.WeakHashMap;
    36 import javax.tools.JavaFileObject;
    38 import com.sun.tools.javac.code.Attribute.RetentionPolicy;
    39 import com.sun.tools.javac.code.Lint.LintCategory;
    40 import com.sun.tools.javac.code.Type.UndetVar.InferenceBound;
    41 import com.sun.tools.javac.comp.AttrContext;
    42 import com.sun.tools.javac.comp.Check;
    43 import com.sun.tools.javac.comp.Enter;
    44 import com.sun.tools.javac.comp.Env;
    45 import com.sun.tools.javac.jvm.ClassReader;
    46 import com.sun.tools.javac.util.*;
    47 import static com.sun.tools.javac.code.BoundKind.*;
    48 import static com.sun.tools.javac.code.Flags.*;
    49 import static com.sun.tools.javac.code.Scope.*;
    50 import static com.sun.tools.javac.code.Symbol.*;
    51 import static com.sun.tools.javac.code.Type.*;
    52 import static com.sun.tools.javac.code.TypeTag.*;
    53 import static com.sun.tools.javac.jvm.ClassFile.externalize;
    54 import static com.sun.tools.javac.util.ListBuffer.lb;
    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 boolean allowDefaultMethods;
    89     final ClassReader reader;
    90     final Check chk;
    91     final Enter enter;
    92     JCDiagnostic.Factory diags;
    93     List<Warner> warnStack = List.nil();
    94     final Name capturedName;
    95     private final FunctionDescriptorLookupError functionDescriptorLookupError;
    97     public final Warner noWarnings;
    99     // <editor-fold defaultstate="collapsed" desc="Instantiating">
   100     public static Types instance(Context context) {
   101         Types instance = context.get(typesKey);
   102         if (instance == null)
   103             instance = new Types(context);
   104         return instance;
   105     }
   107     protected Types(Context context) {
   108         context.put(typesKey, this);
   109         syms = Symtab.instance(context);
   110         names = Names.instance(context);
   111         Source source = Source.instance(context);
   112         allowBoxing = source.allowBoxing();
   113         allowCovariantReturns = source.allowCovariantReturns();
   114         allowObjectToPrimitiveCast = source.allowObjectToPrimitiveCast();
   115         allowDefaultMethods = source.allowDefaultMethods();
   116         reader = ClassReader.instance(context);
   117         chk = Check.instance(context);
   118         enter = Enter.instance(context);
   119         capturedName = names.fromString("<captured wildcard>");
   120         messages = JavacMessages.instance(context);
   121         diags = JCDiagnostic.Factory.instance(context);
   122         functionDescriptorLookupError = new FunctionDescriptorLookupError();
   123         noWarnings = new Warner(null);
   124     }
   125     // </editor-fold>
   127     // <editor-fold defaultstate="collapsed" desc="upperBound">
   128     /**
   129      * The "rvalue conversion".<br>
   130      * The upper bound of most types is the type
   131      * itself.  Wildcards, on the other hand have upper
   132      * and lower bounds.
   133      * @param t a type
   134      * @return the upper bound of the given type
   135      */
   136     public Type upperBound(Type t) {
   137         return upperBound.visit(t).unannotatedType();
   138     }
   139     // where
   140         private final MapVisitor<Void> upperBound = new MapVisitor<Void>() {
   142             @Override
   143             public Type visitWildcardType(WildcardType t, Void ignored) {
   144                 if (t.isSuperBound())
   145                     return t.bound == null ? syms.objectType : t.bound.bound;
   146                 else
   147                     return visit(t.type);
   148             }
   150             @Override
   151             public Type visitCapturedType(CapturedType t, Void ignored) {
   152                 return visit(t.bound);
   153             }
   154         };
   155     // </editor-fold>
   157     // <editor-fold defaultstate="collapsed" desc="lowerBound">
   158     /**
   159      * The "lvalue conversion".<br>
   160      * The lower bound of most types is the type
   161      * itself.  Wildcards, on the other hand have upper
   162      * and lower bounds.
   163      * @param t a type
   164      * @return the lower bound of the given type
   165      */
   166     public Type lowerBound(Type t) {
   167         return lowerBound.visit(t);
   168     }
   169     // where
   170         private final MapVisitor<Void> lowerBound = new MapVisitor<Void>() {
   172             @Override
   173             public Type visitWildcardType(WildcardType t, Void ignored) {
   174                 return t.isExtendsBound() ? syms.botType : visit(t.type);
   175             }
   177             @Override
   178             public Type visitCapturedType(CapturedType t, Void ignored) {
   179                 return visit(t.getLowerBound());
   180             }
   181         };
   182     // </editor-fold>
   184     // <editor-fold defaultstate="collapsed" desc="isUnbounded">
   185     /**
   186      * Checks that all the arguments to a class are unbounded
   187      * wildcards or something else that doesn't make any restrictions
   188      * on the arguments. If a class isUnbounded, a raw super- or
   189      * subclass can be cast to it without a warning.
   190      * @param t a type
   191      * @return true iff the given type is unbounded or raw
   192      */
   193     public boolean isUnbounded(Type t) {
   194         return isUnbounded.visit(t);
   195     }
   196     // where
   197         private final UnaryVisitor<Boolean> isUnbounded = new UnaryVisitor<Boolean>() {
   199             public Boolean visitType(Type t, Void ignored) {
   200                 return true;
   201             }
   203             @Override
   204             public Boolean visitClassType(ClassType t, Void ignored) {
   205                 List<Type> parms = t.tsym.type.allparams();
   206                 List<Type> args = t.allparams();
   207                 while (parms.nonEmpty()) {
   208                     WildcardType unb = new WildcardType(syms.objectType,
   209                                                         BoundKind.UNBOUND,
   210                                                         syms.boundClass,
   211                                                         (TypeVar)parms.head.unannotatedType());
   212                     if (!containsType(args.head, unb))
   213                         return false;
   214                     parms = parms.tail;
   215                     args = args.tail;
   216                 }
   217                 return true;
   218             }
   219         };
   220     // </editor-fold>
   222     // <editor-fold defaultstate="collapsed" desc="asSub">
   223     /**
   224      * Return the least specific subtype of t that starts with symbol
   225      * sym.  If none exists, return null.  The least specific subtype
   226      * is determined as follows:
   227      *
   228      * <p>If there is exactly one parameterized instance of sym that is a
   229      * subtype of t, that parameterized instance is returned.<br>
   230      * Otherwise, if the plain type or raw type `sym' is a subtype of
   231      * type t, the type `sym' itself is returned.  Otherwise, null is
   232      * returned.
   233      */
   234     public Type asSub(Type t, Symbol sym) {
   235         return asSub.visit(t, sym);
   236     }
   237     // where
   238         private final SimpleVisitor<Type,Symbol> asSub = new SimpleVisitor<Type,Symbol>() {
   240             public Type visitType(Type t, Symbol sym) {
   241                 return null;
   242             }
   244             @Override
   245             public Type visitClassType(ClassType t, Symbol sym) {
   246                 if (t.tsym == sym)
   247                     return t;
   248                 Type base = asSuper(sym.type, t.tsym);
   249                 if (base == null)
   250                     return null;
   251                 ListBuffer<Type> from = new ListBuffer<Type>();
   252                 ListBuffer<Type> to = new ListBuffer<Type>();
   253                 try {
   254                     adapt(base, t, from, to);
   255                 } catch (AdaptFailure ex) {
   256                     return null;
   257                 }
   258                 Type res = subst(sym.type, from.toList(), to.toList());
   259                 if (!isSubtype(res, t))
   260                     return null;
   261                 ListBuffer<Type> openVars = new ListBuffer<Type>();
   262                 for (List<Type> l = sym.type.allparams();
   263                      l.nonEmpty(); l = l.tail)
   264                     if (res.contains(l.head) && !t.contains(l.head))
   265                         openVars.append(l.head);
   266                 if (openVars.nonEmpty()) {
   267                     if (t.isRaw()) {
   268                         // The subtype of a raw type is raw
   269                         res = erasure(res);
   270                     } else {
   271                         // Unbound type arguments default to ?
   272                         List<Type> opens = openVars.toList();
   273                         ListBuffer<Type> qs = new ListBuffer<Type>();
   274                         for (List<Type> iter = opens; iter.nonEmpty(); iter = iter.tail) {
   275                             qs.append(new WildcardType(syms.objectType, BoundKind.UNBOUND, syms.boundClass, (TypeVar) iter.head.unannotatedType()));
   276                         }
   277                         res = subst(res, opens, qs.toList());
   278                     }
   279                 }
   280                 return res;
   281             }
   283             @Override
   284             public Type visitErrorType(ErrorType t, Symbol sym) {
   285                 return t;
   286             }
   287         };
   288     // </editor-fold>
   290     // <editor-fold defaultstate="collapsed" desc="isConvertible">
   291     /**
   292      * Is t a subtype of or convertible via boxing/unboxing
   293      * conversion to s?
   294      */
   295     public boolean isConvertible(Type t, Type s, Warner warn) {
   296         if (t.hasTag(ERROR)) {
   297             return true;
   298         }
   299         boolean tPrimitive = t.isPrimitive();
   300         boolean sPrimitive = s.isPrimitive();
   301         if (tPrimitive == sPrimitive) {
   302             return isSubtypeUnchecked(t, s, warn);
   303         }
   304         if (!allowBoxing) return false;
   305         return tPrimitive
   306             ? isSubtype(boxedClass(t).type, s)
   307             : isSubtype(unboxedType(t), s);
   308     }
   310     /**
   311      * Is t a subtype of or convertiable via boxing/unboxing
   312      * convertions to s?
   313      */
   314     public boolean isConvertible(Type t, Type s) {
   315         return isConvertible(t, s, noWarnings);
   316     }
   317     // </editor-fold>
   319     // <editor-fold defaultstate="collapsed" desc="findSam">
   321     /**
   322      * Exception used to report a function descriptor lookup failure. The exception
   323      * wraps a diagnostic that can be used to generate more details error
   324      * messages.
   325      */
   326     public static class FunctionDescriptorLookupError extends RuntimeException {
   327         private static final long serialVersionUID = 0;
   329         JCDiagnostic diagnostic;
   331         FunctionDescriptorLookupError() {
   332             this.diagnostic = null;
   333         }
   335         FunctionDescriptorLookupError setMessage(JCDiagnostic diag) {
   336             this.diagnostic = diag;
   337             return this;
   338         }
   340         public JCDiagnostic getDiagnostic() {
   341             return diagnostic;
   342         }
   343     }
   345     /**
   346      * A cache that keeps track of function descriptors associated with given
   347      * functional interfaces.
   348      */
   349     class DescriptorCache {
   351         private WeakHashMap<TypeSymbol, Entry> _map = new WeakHashMap<TypeSymbol, Entry>();
   353         class FunctionDescriptor {
   354             Symbol descSym;
   356             FunctionDescriptor(Symbol descSym) {
   357                 this.descSym = descSym;
   358             }
   360             public Symbol getSymbol() {
   361                 return descSym;
   362             }
   364             public Type getType(Type site) {
   365                 site = removeWildcards(site);
   366                 if (!chk.checkValidGenericType(site)) {
   367                     //if the inferred functional interface type is not well-formed,
   368                     //or if it's not a subtype of the original target, issue an error
   369                     throw failure(diags.fragment("no.suitable.functional.intf.inst", site));
   370                 }
   371                 return memberType(site, descSym);
   372             }
   373         }
   375         class Entry {
   376             final FunctionDescriptor cachedDescRes;
   377             final int prevMark;
   379             public Entry(FunctionDescriptor cachedDescRes,
   380                     int prevMark) {
   381                 this.cachedDescRes = cachedDescRes;
   382                 this.prevMark = prevMark;
   383             }
   385             boolean matches(int mark) {
   386                 return  this.prevMark == mark;
   387             }
   388         }
   390         FunctionDescriptor get(TypeSymbol origin) throws FunctionDescriptorLookupError {
   391             Entry e = _map.get(origin);
   392             CompoundScope members = membersClosure(origin.type, false);
   393             if (e == null ||
   394                     !e.matches(members.getMark())) {
   395                 FunctionDescriptor descRes = findDescriptorInternal(origin, members);
   396                 _map.put(origin, new Entry(descRes, members.getMark()));
   397                 return descRes;
   398             }
   399             else {
   400                 return e.cachedDescRes;
   401             }
   402         }
   404         /**
   405          * Compute the function descriptor associated with a given functional interface
   406          */
   407         public FunctionDescriptor findDescriptorInternal(TypeSymbol origin,
   408                 CompoundScope membersCache) throws FunctionDescriptorLookupError {
   409             if (!origin.isInterface() || (origin.flags() & ANNOTATION) != 0) {
   410                 //t must be an interface
   411                 throw failure("not.a.functional.intf", origin);
   412             }
   414             final ListBuffer<Symbol> abstracts = ListBuffer.lb();
   415             for (Symbol sym : membersCache.getElements(new DescriptorFilter(origin))) {
   416                 Type mtype = memberType(origin.type, sym);
   417                 if (abstracts.isEmpty() ||
   418                         (sym.name == abstracts.first().name &&
   419                         overrideEquivalent(mtype, memberType(origin.type, abstracts.first())))) {
   420                     abstracts.append(sym);
   421                 } else {
   422                     //the target method(s) should be the only abstract members of t
   423                     throw failure("not.a.functional.intf.1",  origin,
   424                             diags.fragment("incompatible.abstracts", Kinds.kindName(origin), origin));
   425                 }
   426             }
   427             if (abstracts.isEmpty()) {
   428                 //t must define a suitable non-generic method
   429                 throw failure("not.a.functional.intf.1", origin,
   430                             diags.fragment("no.abstracts", Kinds.kindName(origin), origin));
   431             } else if (abstracts.size() == 1) {
   432                 return new FunctionDescriptor(abstracts.first());
   433             } else { // size > 1
   434                 FunctionDescriptor descRes = mergeDescriptors(origin, abstracts.toList());
   435                 if (descRes == null) {
   436                     //we can get here if the functional interface is ill-formed
   437                     ListBuffer<JCDiagnostic> descriptors = ListBuffer.lb();
   438                     for (Symbol desc : abstracts) {
   439                         String key = desc.type.getThrownTypes().nonEmpty() ?
   440                                 "descriptor.throws" : "descriptor";
   441                         descriptors.append(diags.fragment(key, desc.name,
   442                                 desc.type.getParameterTypes(),
   443                                 desc.type.getReturnType(),
   444                                 desc.type.getThrownTypes()));
   445                     }
   446                     JCDiagnostic.MultilineDiagnostic incompatibleDescriptors =
   447                             new JCDiagnostic.MultilineDiagnostic(diags.fragment("incompatible.descs.in.functional.intf",
   448                             Kinds.kindName(origin), origin), descriptors.toList());
   449                     throw failure(incompatibleDescriptors);
   450                 }
   451                 return descRes;
   452             }
   453         }
   455         /**
   456          * Compute a synthetic type for the target descriptor given a list
   457          * of override-equivalent methods in the functional interface type.
   458          * The resulting method type is a method type that is override-equivalent
   459          * and return-type substitutable with each method in the original list.
   460          */
   461         private FunctionDescriptor mergeDescriptors(TypeSymbol origin, List<Symbol> methodSyms) {
   462             //pick argument types - simply take the signature that is a
   463             //subsignature of all other signatures in the list (as per JLS 8.4.2)
   464             List<Symbol> mostSpecific = List.nil();
   465             outer: for (Symbol msym1 : methodSyms) {
   466                 Type mt1 = memberType(origin.type, msym1);
   467                 for (Symbol msym2 : methodSyms) {
   468                     Type mt2 = memberType(origin.type, msym2);
   469                     if (!isSubSignature(mt1, mt2)) {
   470                         continue outer;
   471                     }
   472                 }
   473                 mostSpecific = mostSpecific.prepend(msym1);
   474             }
   475             if (mostSpecific.isEmpty()) {
   476                 return null;
   477             }
   480             //pick return types - this is done in two phases: (i) first, the most
   481             //specific return type is chosen using strict subtyping; if this fails,
   482             //a second attempt is made using return type substitutability (see JLS 8.4.5)
   483             boolean phase2 = false;
   484             Symbol bestSoFar = null;
   485             while (bestSoFar == null) {
   486                 outer: for (Symbol msym1 : mostSpecific) {
   487                     Type mt1 = memberType(origin.type, msym1);
   488                     for (Symbol msym2 : methodSyms) {
   489                         Type mt2 = memberType(origin.type, msym2);
   490                         if (phase2 ?
   491                                 !returnTypeSubstitutable(mt1, mt2) :
   492                                 !isSubtypeInternal(mt1.getReturnType(), mt2.getReturnType())) {
   493                             continue outer;
   494                         }
   495                     }
   496                     bestSoFar = msym1;
   497                 }
   498                 if (phase2) {
   499                     break;
   500                 } else {
   501                     phase2 = true;
   502                 }
   503             }
   504             if (bestSoFar == null) return null;
   506             //merge thrown types - form the intersection of all the thrown types in
   507             //all the signatures in the list
   508             boolean toErase = !bestSoFar.type.hasTag(FORALL);
   509             List<Type> thrown = null;
   510             Type mt1 = memberType(origin.type, bestSoFar);
   511             for (Symbol msym2 : methodSyms) {
   512                 Type mt2 = memberType(origin.type, msym2);
   513                 List<Type> thrown_mt2 = mt2.getThrownTypes();
   514                 if (toErase) {
   515                     thrown_mt2 = erasure(thrown_mt2);
   516                 } else {
   517                     /* If bestSoFar is generic then all the methods are generic.
   518                      * The opposite is not true: a non generic method can override
   519                      * a generic method (raw override) so it's safe to cast mt1 and
   520                      * mt2 to ForAll.
   521                      */
   522                     ForAll fa1 = (ForAll)mt1;
   523                     ForAll fa2 = (ForAll)mt2;
   524                     thrown_mt2 = subst(thrown_mt2, fa2.tvars, fa1.tvars);
   525                 }
   526                 thrown = (thrown == null) ?
   527                     thrown_mt2 :
   528                     chk.intersect(thrown_mt2, thrown);
   529             }
   531             final List<Type> thrown1 = thrown;
   532             return new FunctionDescriptor(bestSoFar) {
   533                 @Override
   534                 public Type getType(Type origin) {
   535                     Type mt = memberType(origin, getSymbol());
   536                     return createMethodTypeWithThrown(mt, thrown1);
   537                 }
   538             };
   539         }
   541         boolean isSubtypeInternal(Type s, Type t) {
   542             return (s.isPrimitive() && t.isPrimitive()) ?
   543                     isSameType(t, s) :
   544                     isSubtype(s, t);
   545         }
   547         FunctionDescriptorLookupError failure(String msg, Object... args) {
   548             return failure(diags.fragment(msg, args));
   549         }
   551         FunctionDescriptorLookupError failure(JCDiagnostic diag) {
   552             return functionDescriptorLookupError.setMessage(diag);
   553         }
   554     }
   556     private DescriptorCache descCache = new DescriptorCache();
   558     /**
   559      * Find the method descriptor associated to this class symbol - if the
   560      * symbol 'origin' is not a functional interface, an exception is thrown.
   561      */
   562     public Symbol findDescriptorSymbol(TypeSymbol origin) throws FunctionDescriptorLookupError {
   563         return descCache.get(origin).getSymbol();
   564     }
   566     /**
   567      * Find the type of the method descriptor associated to this class symbol -
   568      * if the symbol 'origin' is not a functional interface, an exception is thrown.
   569      */
   570     public Type findDescriptorType(Type origin) throws FunctionDescriptorLookupError {
   571         return descCache.get(origin.tsym).getType(origin);
   572     }
   574     /**
   575      * Is given type a functional interface?
   576      */
   577     public boolean isFunctionalInterface(TypeSymbol tsym) {
   578         try {
   579             findDescriptorSymbol(tsym);
   580             return true;
   581         } catch (FunctionDescriptorLookupError ex) {
   582             return false;
   583         }
   584     }
   586     public boolean isFunctionalInterface(Type site) {
   587         try {
   588             findDescriptorType(site);
   589             return true;
   590         } catch (FunctionDescriptorLookupError ex) {
   591             return false;
   592         }
   593     }
   595     public Type removeWildcards(Type site) {
   596         Type capturedSite = capture(site);
   597         if (capturedSite != site) {
   598             Type formalInterface = site.tsym.type;
   599             ListBuffer<Type> typeargs = ListBuffer.lb();
   600             List<Type> actualTypeargs = site.getTypeArguments();
   601             List<Type> capturedTypeargs = capturedSite.getTypeArguments();
   602             //simply replace the wildcards with its bound
   603             for (Type t : formalInterface.getTypeArguments()) {
   604                 if (actualTypeargs.head.hasTag(WILDCARD)) {
   605                     WildcardType wt = (WildcardType)actualTypeargs.head.unannotatedType();
   606                     Type bound;
   607                     switch (wt.kind) {
   608                         case EXTENDS:
   609                         case UNBOUND:
   610                             CapturedType capVar = (CapturedType)capturedTypeargs.head.unannotatedType();
   611                             //use declared bound if it doesn't depend on formal type-args
   612                             bound = capVar.bound.containsAny(capturedSite.getTypeArguments()) ?
   613                                     wt.type : capVar.bound;
   614                             break;
   615                         default:
   616                             bound = wt.type;
   617                     }
   618                     typeargs.append(bound);
   619                 } else {
   620                     typeargs.append(actualTypeargs.head);
   621                 }
   622                 actualTypeargs = actualTypeargs.tail;
   623                 capturedTypeargs = capturedTypeargs.tail;
   624             }
   625             return subst(formalInterface, formalInterface.getTypeArguments(), typeargs.toList());
   626         } else {
   627             return site;
   628         }
   629     }
   631     /**
   632      * Create a symbol for a class that implements a given functional interface
   633      * and overrides its functional descriptor. This routine is used for two
   634      * main purposes: (i) checking well-formedness of a functional interface;
   635      * (ii) perform functional interface bridge calculation.
   636      */
   637     public ClassSymbol makeFunctionalInterfaceClass(Env<AttrContext> env, Name name, List<Type> targets, long cflags) {
   638         if (targets.isEmpty() || !isFunctionalInterface(targets.head)) {
   639             return null;
   640         }
   641         Symbol descSym = findDescriptorSymbol(targets.head.tsym);
   642         Type descType = findDescriptorType(targets.head);
   643         ClassSymbol csym = new ClassSymbol(cflags, name, env.enclClass.sym.outermostClass());
   644         csym.completer = null;
   645         csym.members_field = new Scope(csym);
   646         MethodSymbol instDescSym = new MethodSymbol(descSym.flags(), descSym.name, descType, csym);
   647         csym.members_field.enter(instDescSym);
   648         Type.ClassType ctype = new Type.ClassType(Type.noType, List.<Type>nil(), csym);
   649         ctype.supertype_field = syms.objectType;
   650         ctype.interfaces_field = targets;
   651         csym.type = ctype;
   652         csym.sourcefile = ((ClassSymbol)csym.owner).sourcefile;
   653         return csym;
   654     }
   656     /**
   657      * Find the minimal set of methods that are overridden by the functional
   658      * descriptor in 'origin'. All returned methods are assumed to have different
   659      * erased signatures.
   660      */
   661     public List<Symbol> functionalInterfaceBridges(TypeSymbol origin) {
   662         Assert.check(isFunctionalInterface(origin));
   663         Symbol descSym = findDescriptorSymbol(origin);
   664         CompoundScope members = membersClosure(origin.type, false);
   665         ListBuffer<Symbol> overridden = ListBuffer.lb();
   666         outer: for (Symbol m2 : members.getElementsByName(descSym.name, bridgeFilter)) {
   667             if (m2 == descSym) continue;
   668             else if (descSym.overrides(m2, origin, Types.this, false)) {
   669                 for (Symbol m3 : overridden) {
   670                     if (isSameType(m3.erasure(Types.this), m2.erasure(Types.this)) ||
   671                             (m3.overrides(m2, origin, Types.this, false) &&
   672                             (pendingBridges((ClassSymbol)origin, m3.enclClass()) ||
   673                             (((MethodSymbol)m2).binaryImplementation((ClassSymbol)m3.owner, Types.this) != null)))) {
   674                         continue outer;
   675                     }
   676                 }
   677                 overridden.add(m2);
   678             }
   679         }
   680         return overridden.toList();
   681     }
   682     //where
   683         private Filter<Symbol> bridgeFilter = new Filter<Symbol>() {
   684             public boolean accepts(Symbol t) {
   685                 return t.kind == Kinds.MTH &&
   686                         t.name != names.init &&
   687                         t.name != names.clinit &&
   688                         (t.flags() & SYNTHETIC) == 0;
   689             }
   690         };
   691         private boolean pendingBridges(ClassSymbol origin, TypeSymbol s) {
   692             //a symbol will be completed from a classfile if (a) symbol has
   693             //an associated file object with CLASS kind and (b) the symbol has
   694             //not been entered
   695             if (origin.classfile != null &&
   696                     origin.classfile.getKind() == JavaFileObject.Kind.CLASS &&
   697                     enter.getEnv(origin) == null) {
   698                 return false;
   699             }
   700             if (origin == s) {
   701                 return true;
   702             }
   703             for (Type t : interfaces(origin.type)) {
   704                 if (pendingBridges((ClassSymbol)t.tsym, s)) {
   705                     return true;
   706                 }
   707             }
   708             return false;
   709         }
   710     // </editor-fold>
   712    /**
   713     * Scope filter used to skip methods that should be ignored (such as methods
   714     * overridden by j.l.Object) during function interface conversion interface check
   715     */
   716     class DescriptorFilter implements Filter<Symbol> {
   718        TypeSymbol origin;
   720        DescriptorFilter(TypeSymbol origin) {
   721            this.origin = origin;
   722        }
   724        @Override
   725        public boolean accepts(Symbol sym) {
   726            return sym.kind == Kinds.MTH &&
   727                    (sym.flags() & (ABSTRACT | DEFAULT)) == ABSTRACT &&
   728                    !overridesObjectMethod(origin, sym) &&
   729                    (interfaceCandidates(origin.type, (MethodSymbol)sym).head.flags() & DEFAULT) == 0;
   730        }
   731     };
   733     // <editor-fold defaultstate="collapsed" desc="isSubtype">
   734     /**
   735      * Is t an unchecked subtype of s?
   736      */
   737     public boolean isSubtypeUnchecked(Type t, Type s) {
   738         return isSubtypeUnchecked(t, s, noWarnings);
   739     }
   740     /**
   741      * Is t an unchecked subtype of s?
   742      */
   743     public boolean isSubtypeUnchecked(Type t, Type s, Warner warn) {
   744         boolean result = isSubtypeUncheckedInternal(t, s, warn);
   745         if (result) {
   746             checkUnsafeVarargsConversion(t, s, warn);
   747         }
   748         return result;
   749     }
   750     //where
   751         private boolean isSubtypeUncheckedInternal(Type t, Type s, Warner warn) {
   752             if (t.hasTag(ARRAY) && s.hasTag(ARRAY)) {
   753                 t = t.unannotatedType();
   754                 s = s.unannotatedType();
   755                 if (((ArrayType)t).elemtype.isPrimitive()) {
   756                     return isSameType(elemtype(t), elemtype(s));
   757                 } else {
   758                     return isSubtypeUnchecked(elemtype(t), elemtype(s), warn);
   759                 }
   760             } else if (isSubtype(t, s)) {
   761                 return true;
   762             } else if (t.hasTag(TYPEVAR)) {
   763                 return isSubtypeUnchecked(t.getUpperBound(), s, warn);
   764             } else if (!s.isRaw()) {
   765                 Type t2 = asSuper(t, s.tsym);
   766                 if (t2 != null && t2.isRaw()) {
   767                     if (isReifiable(s)) {
   768                         warn.silentWarn(LintCategory.UNCHECKED);
   769                     } else {
   770                         warn.warn(LintCategory.UNCHECKED);
   771                     }
   772                     return true;
   773                 }
   774             }
   775             return false;
   776         }
   778         private void checkUnsafeVarargsConversion(Type t, Type s, Warner warn) {
   779             if (!t.hasTag(ARRAY) || isReifiable(t)) {
   780                 return;
   781             }
   782             t = t.unannotatedType();
   783             s = s.unannotatedType();
   784             ArrayType from = (ArrayType)t;
   785             boolean shouldWarn = false;
   786             switch (s.getTag()) {
   787                 case ARRAY:
   788                     ArrayType to = (ArrayType)s;
   789                     shouldWarn = from.isVarargs() &&
   790                             !to.isVarargs() &&
   791                             !isReifiable(from);
   792                     break;
   793                 case CLASS:
   794                     shouldWarn = from.isVarargs();
   795                     break;
   796             }
   797             if (shouldWarn) {
   798                 warn.warn(LintCategory.VARARGS);
   799             }
   800         }
   802     /**
   803      * Is t a subtype of s?<br>
   804      * (not defined for Method and ForAll types)
   805      */
   806     final public boolean isSubtype(Type t, Type s) {
   807         return isSubtype(t, s, true);
   808     }
   809     final public boolean isSubtypeNoCapture(Type t, Type s) {
   810         return isSubtype(t, s, false);
   811     }
   812     public boolean isSubtype(Type t, Type s, boolean capture) {
   813         if (t == s)
   814             return true;
   816         t = t.unannotatedType();
   817         s = s.unannotatedType();
   819         if (t == s)
   820             return true;
   822         if (s.isPartial())
   823             return isSuperType(s, t);
   825         if (s.isCompound()) {
   826             for (Type s2 : interfaces(s).prepend(supertype(s))) {
   827                 if (!isSubtype(t, s2, capture))
   828                     return false;
   829             }
   830             return true;
   831         }
   833         Type lower = lowerBound(s);
   834         if (s != lower)
   835             return isSubtype(capture ? capture(t) : t, lower, false);
   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 = lb();
   889                 ListBuffer<Type> to = lb();
   890                 adaptSelf(t, from, to);
   891                 if (from.isEmpty())
   892                     return t;
   893                 ListBuffer<Type> rewrite = lb();
   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(upperBound(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                 return sup != null
   920                     && sup.tsym == s.tsym
   921                     // You're not allowed to write
   922                     //     Vector<Object> vec = new Vector<String>();
   923                     // But with wildcards you can write
   924                     //     Vector<? extends Object> vec = new Vector<String>();
   925                     // which means that subtype checking must be done
   926                     // here instead of same-type checking (via containsType).
   927                     && (!s.isParameterized() || containsTypeRecursive(s, sup))
   928                     && isSubtypeNoCapture(sup.getEnclosingType(),
   929                                           s.getEnclosingType());
   930             }
   932             @Override
   933             public Boolean visitArrayType(ArrayType t, Type s) {
   934                 if (s.hasTag(ARRAY)) {
   935                     if (t.elemtype.isPrimitive())
   936                         return isSameType(t.elemtype, elemtype(s));
   937                     else
   938                         return isSubtypeNoCapture(t.elemtype, elemtype(s));
   939                 }
   941                 if (s.hasTag(CLASS)) {
   942                     Name sname = s.tsym.getQualifiedName();
   943                     return sname == names.java_lang_Object
   944                         || sname == names.java_lang_Cloneable
   945                         || sname == names.java_io_Serializable;
   946                 }
   948                 return false;
   949             }
   951             @Override
   952             public Boolean visitUndetVar(UndetVar t, Type s) {
   953                 //todo: test against origin needed? or replace with substitution?
   954                 if (t == s || t.qtype == s || s.hasTag(ERROR) || s.hasTag(UNKNOWN)) {
   955                     return true;
   956                 } else if (s.hasTag(BOT)) {
   957                     //if 's' is 'null' there's no instantiated type U for which
   958                     //U <: s (but 'null' itself, which is not a valid type)
   959                     return false;
   960                 }
   962                 t.addBound(InferenceBound.UPPER, s, Types.this);
   963                 return true;
   964             }
   966             @Override
   967             public Boolean visitErrorType(ErrorType t, Type s) {
   968                 return true;
   969             }
   970         };
   972     /**
   973      * Is t a subtype of every type in given list `ts'?<br>
   974      * (not defined for Method and ForAll types)<br>
   975      * Allows unchecked conversions.
   976      */
   977     public boolean isSubtypeUnchecked(Type t, List<Type> ts, Warner warn) {
   978         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
   979             if (!isSubtypeUnchecked(t, l.head, warn))
   980                 return false;
   981         return true;
   982     }
   984     /**
   985      * Are corresponding elements of ts subtypes of ss?  If lists are
   986      * of different length, return false.
   987      */
   988     public boolean isSubtypes(List<Type> ts, List<Type> ss) {
   989         while (ts.tail != null && ss.tail != null
   990                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   991                isSubtype(ts.head, ss.head)) {
   992             ts = ts.tail;
   993             ss = ss.tail;
   994         }
   995         return ts.tail == null && ss.tail == null;
   996         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   997     }
   999     /**
  1000      * Are corresponding elements of ts subtypes of ss, allowing
  1001      * unchecked conversions?  If lists are of different length,
  1002      * return false.
  1003      **/
  1004     public boolean isSubtypesUnchecked(List<Type> ts, List<Type> ss, Warner warn) {
  1005         while (ts.tail != null && ss.tail != null
  1006                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
  1007                isSubtypeUnchecked(ts.head, ss.head, warn)) {
  1008             ts = ts.tail;
  1009             ss = ss.tail;
  1011         return ts.tail == null && ss.tail == null;
  1012         /*inlined: ts.isEmpty() && ss.isEmpty();*/
  1014     // </editor-fold>
  1016     // <editor-fold defaultstate="collapsed" desc="isSuperType">
  1017     /**
  1018      * Is t a supertype of s?
  1019      */
  1020     public boolean isSuperType(Type t, Type s) {
  1021         switch (t.getTag()) {
  1022         case ERROR:
  1023             return true;
  1024         case UNDETVAR: {
  1025             UndetVar undet = (UndetVar)t;
  1026             if (t == s ||
  1027                 undet.qtype == s ||
  1028                 s.hasTag(ERROR) ||
  1029                 s.hasTag(BOT)) {
  1030                 return true;
  1032             undet.addBound(InferenceBound.LOWER, s, this);
  1033             return true;
  1035         default:
  1036             return isSubtype(s, t);
  1039     // </editor-fold>
  1041     // <editor-fold defaultstate="collapsed" desc="isSameType">
  1042     /**
  1043      * Are corresponding elements of the lists the same type?  If
  1044      * lists are of different length, return false.
  1045      */
  1046     public boolean isSameTypes(List<Type> ts, List<Type> ss) {
  1047         return isSameTypes(ts, ss, false);
  1049     public boolean isSameTypes(List<Type> ts, List<Type> ss, boolean strict) {
  1050         while (ts.tail != null && ss.tail != null
  1051                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
  1052                isSameType(ts.head, ss.head, strict)) {
  1053             ts = ts.tail;
  1054             ss = ss.tail;
  1056         return ts.tail == null && ss.tail == null;
  1057         /*inlined: ts.isEmpty() && ss.isEmpty();*/
  1060     /**
  1061     * A polymorphic signature method (JLS SE 7, 8.4.1) is a method that
  1062     * (i) is declared in the java.lang.invoke.MethodHandle class, (ii) takes
  1063     * a single variable arity parameter (iii) whose declared type is Object[],
  1064     * (iv) has a return type of Object and (v) is native.
  1065     */
  1066    public boolean isSignaturePolymorphic(MethodSymbol msym) {
  1067        List<Type> argtypes = msym.type.getParameterTypes();
  1068        return (msym.flags_field & NATIVE) != 0 &&
  1069                msym.owner == syms.methodHandleType.tsym &&
  1070                argtypes.tail.tail == null &&
  1071                argtypes.head.hasTag(TypeTag.ARRAY) &&
  1072                msym.type.getReturnType().tsym == syms.objectType.tsym &&
  1073                ((ArrayType)argtypes.head).elemtype.tsym == syms.objectType.tsym;
  1076     /**
  1077      * Is t the same type as s?
  1078      */
  1079     public boolean isSameType(Type t, Type s) {
  1080         return isSameType(t, s, false);
  1082     public boolean isSameType(Type t, Type s, boolean strict) {
  1083         return strict ?
  1084                 isSameTypeStrict.visit(t, s) :
  1085                 isSameTypeLoose.visit(t, s);
  1087     public boolean isSameAnnotatedType(Type t, Type s) {
  1088         return isSameAnnotatedType.visit(t, s);
  1090     // where
  1091         abstract class SameTypeVisitor extends TypeRelation {
  1093             public Boolean visitType(Type t, Type s) {
  1094                 if (t == s)
  1095                     return true;
  1097                 if (s.isPartial())
  1098                     return visit(s, t);
  1100                 switch (t.getTag()) {
  1101                 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
  1102                 case DOUBLE: case BOOLEAN: case VOID: case BOT: case NONE:
  1103                     return t.hasTag(s.getTag());
  1104                 case TYPEVAR: {
  1105                     if (s.hasTag(TYPEVAR)) {
  1106                         //type-substitution does not preserve type-var types
  1107                         //check that type var symbols and bounds are indeed the same
  1108                         return sameTypeVars((TypeVar)t.unannotatedType(), (TypeVar)s.unannotatedType());
  1110                     else {
  1111                         //special case for s == ? super X, where upper(s) = u
  1112                         //check that u == t, where u has been set by Type.withTypeVar
  1113                         return s.isSuperBound() &&
  1114                                 !s.isExtendsBound() &&
  1115                                 visit(t, upperBound(s));
  1118                 default:
  1119                     throw new AssertionError("isSameType " + t.getTag());
  1123             abstract boolean sameTypeVars(TypeVar tv1, TypeVar tv2);
  1125             @Override
  1126             public Boolean visitWildcardType(WildcardType t, Type s) {
  1127                 if (s.isPartial())
  1128                     return visit(s, t);
  1129                 else
  1130                     return false;
  1133             @Override
  1134             public Boolean visitClassType(ClassType t, Type s) {
  1135                 if (t == s)
  1136                     return true;
  1138                 if (s.isPartial())
  1139                     return visit(s, t);
  1141                 if (s.isSuperBound() && !s.isExtendsBound())
  1142                     return visit(t, upperBound(s)) && visit(t, lowerBound(s));
  1144                 if (t.isCompound() && s.isCompound()) {
  1145                     if (!visit(supertype(t), supertype(s)))
  1146                         return false;
  1148                     HashSet<UniqueType> set = new HashSet<UniqueType>();
  1149                     for (Type x : interfaces(t))
  1150                         set.add(new UniqueType(x.unannotatedType(), Types.this));
  1151                     for (Type x : interfaces(s)) {
  1152                         if (!set.remove(new UniqueType(x.unannotatedType(), Types.this)))
  1153                             return false;
  1155                     return (set.isEmpty());
  1157                 return t.tsym == s.tsym
  1158                     && visit(t.getEnclosingType(), s.getEnclosingType())
  1159                     && containsTypes(t.getTypeArguments(), s.getTypeArguments());
  1162             abstract protected boolean containsTypes(List<Type> ts1, List<Type> ts2);
  1164             @Override
  1165             public Boolean visitArrayType(ArrayType t, Type s) {
  1166                 if (t == s)
  1167                     return true;
  1169                 if (s.isPartial())
  1170                     return visit(s, t);
  1172                 return s.hasTag(ARRAY)
  1173                     && containsTypeEquivalent(t.elemtype, elemtype(s));
  1176             @Override
  1177             public Boolean visitMethodType(MethodType t, Type s) {
  1178                 // isSameType for methods does not take thrown
  1179                 // exceptions into account!
  1180                 return hasSameArgs(t, s) && visit(t.getReturnType(), s.getReturnType());
  1183             @Override
  1184             public Boolean visitPackageType(PackageType t, Type s) {
  1185                 return t == s;
  1188             @Override
  1189             public Boolean visitForAll(ForAll t, Type s) {
  1190                 if (!s.hasTag(FORALL)) {
  1191                     return false;
  1194                 ForAll forAll = (ForAll)s;
  1195                 return hasSameBounds(t, forAll)
  1196                     && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
  1199             @Override
  1200             public Boolean visitUndetVar(UndetVar t, Type s) {
  1201                 if (s.hasTag(WILDCARD)) {
  1202                     // FIXME, this might be leftovers from before capture conversion
  1203                     return false;
  1206                 if (t == s || t.qtype == s || s.hasTag(ERROR) || s.hasTag(UNKNOWN)) {
  1207                     return true;
  1210                 t.addBound(InferenceBound.EQ, s, Types.this);
  1212                 return true;
  1215             @Override
  1216             public Boolean visitErrorType(ErrorType t, Type s) {
  1217                 return true;
  1221         /**
  1222          * Standard type-equality relation - type variables are considered
  1223          * equals if they share the same type symbol.
  1224          */
  1225         TypeRelation isSameTypeLoose = new LooseSameTypeVisitor();
  1227         private class LooseSameTypeVisitor extends SameTypeVisitor {
  1228             @Override
  1229             boolean sameTypeVars(TypeVar tv1, TypeVar tv2) {
  1230                 return tv1.tsym == tv2.tsym && visit(tv1.getUpperBound(), tv2.getUpperBound());
  1232             @Override
  1233             protected boolean containsTypes(List<Type> ts1, List<Type> ts2) {
  1234                 return containsTypeEquivalent(ts1, ts2);
  1236         };
  1238         /**
  1239          * Strict type-equality relation - type variables are considered
  1240          * equals if they share the same object identity.
  1241          */
  1242         TypeRelation isSameTypeStrict = new SameTypeVisitor() {
  1243             @Override
  1244             boolean sameTypeVars(TypeVar tv1, TypeVar tv2) {
  1245                 return tv1 == tv2;
  1247             @Override
  1248             protected boolean containsTypes(List<Type> ts1, List<Type> ts2) {
  1249                 return isSameTypes(ts1, ts2, true);
  1252             @Override
  1253             public Boolean visitWildcardType(WildcardType t, Type s) {
  1254                 if (!s.hasTag(WILDCARD)) {
  1255                     return false;
  1256                 } else {
  1257                     WildcardType t2 = (WildcardType)s.unannotatedType();
  1258                     return t.kind == t2.kind &&
  1259                             isSameType(t.type, t2.type, true);
  1262         };
  1264         /**
  1265          * A version of LooseSameTypeVisitor that takes AnnotatedTypes
  1266          * into account.
  1267          */
  1268         TypeRelation isSameAnnotatedType = new LooseSameTypeVisitor() {
  1269             @Override
  1270             public Boolean visitAnnotatedType(AnnotatedType t, Type s) {
  1271                 if (!s.isAnnotated())
  1272                     return false;
  1273                 if (!t.getAnnotationMirrors().containsAll(s.getAnnotationMirrors()))
  1274                     return false;
  1275                 if (!s.getAnnotationMirrors().containsAll(t.getAnnotationMirrors()))
  1276                     return false;
  1277                 return visit(t.underlyingType, s);
  1279         };
  1280     // </editor-fold>
  1282     // <editor-fold defaultstate="collapsed" desc="Contains Type">
  1283     public boolean containedBy(Type t, Type s) {
  1284         switch (t.getTag()) {
  1285         case UNDETVAR:
  1286             if (s.hasTag(WILDCARD)) {
  1287                 UndetVar undetvar = (UndetVar)t;
  1288                 WildcardType wt = (WildcardType)s.unannotatedType();
  1289                 switch(wt.kind) {
  1290                     case UNBOUND: //similar to ? extends Object
  1291                     case EXTENDS: {
  1292                         Type bound = upperBound(s);
  1293                         undetvar.addBound(InferenceBound.UPPER, bound, this);
  1294                         break;
  1296                     case SUPER: {
  1297                         Type bound = lowerBound(s);
  1298                         undetvar.addBound(InferenceBound.LOWER, bound, this);
  1299                         break;
  1302                 return true;
  1303             } else {
  1304                 return isSameType(t, s);
  1306         case ERROR:
  1307             return true;
  1308         default:
  1309             return containsType(s, t);
  1313     boolean containsType(List<Type> ts, List<Type> ss) {
  1314         while (ts.nonEmpty() && ss.nonEmpty()
  1315                && containsType(ts.head, ss.head)) {
  1316             ts = ts.tail;
  1317             ss = ss.tail;
  1319         return ts.isEmpty() && ss.isEmpty();
  1322     /**
  1323      * Check if t contains s.
  1325      * <p>T contains S if:
  1327      * <p>{@code L(T) <: L(S) && U(S) <: U(T)}
  1329      * <p>This relation is only used by ClassType.isSubtype(), that
  1330      * is,
  1332      * <p>{@code C<S> <: C<T> if T contains S.}
  1334      * <p>Because of F-bounds, this relation can lead to infinite
  1335      * recursion.  Thus we must somehow break that recursion.  Notice
  1336      * that containsType() is only called from ClassType.isSubtype().
  1337      * Since the arguments have already been checked against their
  1338      * bounds, we know:
  1340      * <p>{@code U(S) <: U(T) if T is "super" bound (U(T) *is* the bound)}
  1342      * <p>{@code L(T) <: L(S) if T is "extends" bound (L(T) is bottom)}
  1344      * @param t a type
  1345      * @param s a type
  1346      */
  1347     public boolean containsType(Type t, Type s) {
  1348         return containsType.visit(t, s);
  1350     // where
  1351         private TypeRelation containsType = new TypeRelation() {
  1353             private Type U(Type t) {
  1354                 while (t.hasTag(WILDCARD)) {
  1355                     WildcardType w = (WildcardType)t.unannotatedType();
  1356                     if (w.isSuperBound())
  1357                         return w.bound == null ? syms.objectType : w.bound.bound;
  1358                     else
  1359                         t = w.type;
  1361                 return t;
  1364             private Type L(Type t) {
  1365                 while (t.hasTag(WILDCARD)) {
  1366                     WildcardType w = (WildcardType)t.unannotatedType();
  1367                     if (w.isExtendsBound())
  1368                         return syms.botType;
  1369                     else
  1370                         t = w.type;
  1372                 return t;
  1375             public Boolean visitType(Type t, Type s) {
  1376                 if (s.isPartial())
  1377                     return containedBy(s, t);
  1378                 else
  1379                     return isSameType(t, s);
  1382 //            void debugContainsType(WildcardType t, Type s) {
  1383 //                System.err.println();
  1384 //                System.err.format(" does %s contain %s?%n", t, s);
  1385 //                System.err.format(" %s U(%s) <: U(%s) %s = %s%n",
  1386 //                                  upperBound(s), s, t, U(t),
  1387 //                                  t.isSuperBound()
  1388 //                                  || isSubtypeNoCapture(upperBound(s), U(t)));
  1389 //                System.err.format(" %s L(%s) <: L(%s) %s = %s%n",
  1390 //                                  L(t), t, s, lowerBound(s),
  1391 //                                  t.isExtendsBound()
  1392 //                                  || isSubtypeNoCapture(L(t), lowerBound(s)));
  1393 //                System.err.println();
  1394 //            }
  1396             @Override
  1397             public Boolean visitWildcardType(WildcardType t, Type s) {
  1398                 if (s.isPartial())
  1399                     return containedBy(s, t);
  1400                 else {
  1401 //                    debugContainsType(t, s);
  1402                     return isSameWildcard(t, s)
  1403                         || isCaptureOf(s, t)
  1404                         || ((t.isExtendsBound() || isSubtypeNoCapture(L(t), lowerBound(s))) &&
  1405                             (t.isSuperBound() || isSubtypeNoCapture(upperBound(s), U(t))));
  1409             @Override
  1410             public Boolean visitUndetVar(UndetVar t, Type s) {
  1411                 if (!s.hasTag(WILDCARD)) {
  1412                     return isSameType(t, s);
  1413                 } else {
  1414                     return false;
  1418             @Override
  1419             public Boolean visitErrorType(ErrorType t, Type s) {
  1420                 return true;
  1422         };
  1424     public boolean isCaptureOf(Type s, WildcardType t) {
  1425         if (!s.hasTag(TYPEVAR) || !((TypeVar)s.unannotatedType()).isCaptured())
  1426             return false;
  1427         return isSameWildcard(t, ((CapturedType)s.unannotatedType()).wildcard);
  1430     public boolean isSameWildcard(WildcardType t, Type s) {
  1431         if (!s.hasTag(WILDCARD))
  1432             return false;
  1433         WildcardType w = (WildcardType)s.unannotatedType();
  1434         return w.kind == t.kind && w.type == t.type;
  1437     public boolean containsTypeEquivalent(List<Type> ts, List<Type> ss) {
  1438         while (ts.nonEmpty() && ss.nonEmpty()
  1439                && containsTypeEquivalent(ts.head, ss.head)) {
  1440             ts = ts.tail;
  1441             ss = ss.tail;
  1443         return ts.isEmpty() && ss.isEmpty();
  1445     // </editor-fold>
  1447     /**
  1448      * Can t and s be compared for equality?  Any primitive ==
  1449      * primitive or primitive == object comparisons here are an error.
  1450      * Unboxing and correct primitive == primitive comparisons are
  1451      * already dealt with in Attr.visitBinary.
  1453      */
  1454     public boolean isEqualityComparable(Type s, Type t, Warner warn) {
  1455         if (t.isNumeric() && s.isNumeric())
  1456             return true;
  1458         boolean tPrimitive = t.isPrimitive();
  1459         boolean sPrimitive = s.isPrimitive();
  1460         if (!tPrimitive && !sPrimitive) {
  1461             return isCastable(s, t, warn) || isCastable(t, s, warn);
  1462         } else {
  1463             return false;
  1467     // <editor-fold defaultstate="collapsed" desc="isCastable">
  1468     public boolean isCastable(Type t, Type s) {
  1469         return isCastable(t, s, noWarnings);
  1472     /**
  1473      * Is t is castable to s?<br>
  1474      * s is assumed to be an erased type.<br>
  1475      * (not defined for Method and ForAll types).
  1476      */
  1477     public boolean isCastable(Type t, Type s, Warner warn) {
  1478         if (t == s)
  1479             return true;
  1481         if (t.isPrimitive() != s.isPrimitive())
  1482             return allowBoxing && (
  1483                     isConvertible(t, s, warn)
  1484                     || (allowObjectToPrimitiveCast &&
  1485                         s.isPrimitive() &&
  1486                         isSubtype(boxedClass(s).type, t)));
  1487         if (warn != warnStack.head) {
  1488             try {
  1489                 warnStack = warnStack.prepend(warn);
  1490                 checkUnsafeVarargsConversion(t, s, warn);
  1491                 return isCastable.visit(t,s);
  1492             } finally {
  1493                 warnStack = warnStack.tail;
  1495         } else {
  1496             return isCastable.visit(t,s);
  1499     // where
  1500         private TypeRelation isCastable = new TypeRelation() {
  1502             public Boolean visitType(Type t, Type s) {
  1503                 if (s.hasTag(ERROR))
  1504                     return true;
  1506                 switch (t.getTag()) {
  1507                 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
  1508                 case DOUBLE:
  1509                     return s.isNumeric();
  1510                 case BOOLEAN:
  1511                     return s.hasTag(BOOLEAN);
  1512                 case VOID:
  1513                     return false;
  1514                 case BOT:
  1515                     return isSubtype(t, s);
  1516                 default:
  1517                     throw new AssertionError();
  1521             @Override
  1522             public Boolean visitWildcardType(WildcardType t, Type s) {
  1523                 return isCastable(upperBound(t), s, warnStack.head);
  1526             @Override
  1527             public Boolean visitClassType(ClassType t, Type s) {
  1528                 if (s.hasTag(ERROR) || s.hasTag(BOT))
  1529                     return true;
  1531                 if (s.hasTag(TYPEVAR)) {
  1532                     if (isCastable(t, s.getUpperBound(), noWarnings)) {
  1533                         warnStack.head.warn(LintCategory.UNCHECKED);
  1534                         return true;
  1535                     } else {
  1536                         return false;
  1540                 if (t.isCompound() || s.isCompound()) {
  1541                     return !t.isCompound() ?
  1542                             visitIntersectionType((IntersectionClassType)s.unannotatedType(), t, true) :
  1543                             visitIntersectionType((IntersectionClassType)t.unannotatedType(), s, false);
  1546                 if (s.hasTag(CLASS) || s.hasTag(ARRAY)) {
  1547                     boolean upcast;
  1548                     if ((upcast = isSubtype(erasure(t), erasure(s)))
  1549                         || isSubtype(erasure(s), erasure(t))) {
  1550                         if (!upcast && s.hasTag(ARRAY)) {
  1551                             if (!isReifiable(s))
  1552                                 warnStack.head.warn(LintCategory.UNCHECKED);
  1553                             return true;
  1554                         } else if (s.isRaw()) {
  1555                             return true;
  1556                         } else if (t.isRaw()) {
  1557                             if (!isUnbounded(s))
  1558                                 warnStack.head.warn(LintCategory.UNCHECKED);
  1559                             return true;
  1561                         // Assume |a| <: |b|
  1562                         final Type a = upcast ? t : s;
  1563                         final Type b = upcast ? s : t;
  1564                         final boolean HIGH = true;
  1565                         final boolean LOW = false;
  1566                         final boolean DONT_REWRITE_TYPEVARS = false;
  1567                         Type aHigh = rewriteQuantifiers(a, HIGH, DONT_REWRITE_TYPEVARS);
  1568                         Type aLow  = rewriteQuantifiers(a, LOW,  DONT_REWRITE_TYPEVARS);
  1569                         Type bHigh = rewriteQuantifiers(b, HIGH, DONT_REWRITE_TYPEVARS);
  1570                         Type bLow  = rewriteQuantifiers(b, LOW,  DONT_REWRITE_TYPEVARS);
  1571                         Type lowSub = asSub(bLow, aLow.tsym);
  1572                         Type highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
  1573                         if (highSub == null) {
  1574                             final boolean REWRITE_TYPEVARS = true;
  1575                             aHigh = rewriteQuantifiers(a, HIGH, REWRITE_TYPEVARS);
  1576                             aLow  = rewriteQuantifiers(a, LOW,  REWRITE_TYPEVARS);
  1577                             bHigh = rewriteQuantifiers(b, HIGH, REWRITE_TYPEVARS);
  1578                             bLow  = rewriteQuantifiers(b, LOW,  REWRITE_TYPEVARS);
  1579                             lowSub = asSub(bLow, aLow.tsym);
  1580                             highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
  1582                         if (highSub != null) {
  1583                             if (!(a.tsym == highSub.tsym && a.tsym == lowSub.tsym)) {
  1584                                 Assert.error(a.tsym + " != " + highSub.tsym + " != " + lowSub.tsym);
  1586                             if (!disjointTypes(aHigh.allparams(), highSub.allparams())
  1587                                 && !disjointTypes(aHigh.allparams(), lowSub.allparams())
  1588                                 && !disjointTypes(aLow.allparams(), highSub.allparams())
  1589                                 && !disjointTypes(aLow.allparams(), lowSub.allparams())) {
  1590                                 if (upcast ? giveWarning(a, b) :
  1591                                     giveWarning(b, a))
  1592                                     warnStack.head.warn(LintCategory.UNCHECKED);
  1593                                 return true;
  1596                         if (isReifiable(s))
  1597                             return isSubtypeUnchecked(a, b);
  1598                         else
  1599                             return isSubtypeUnchecked(a, b, warnStack.head);
  1602                     // Sidecast
  1603                     if (s.hasTag(CLASS)) {
  1604                         if ((s.tsym.flags() & INTERFACE) != 0) {
  1605                             return ((t.tsym.flags() & FINAL) == 0)
  1606                                 ? sideCast(t, s, warnStack.head)
  1607                                 : sideCastFinal(t, s, warnStack.head);
  1608                         } else if ((t.tsym.flags() & INTERFACE) != 0) {
  1609                             return ((s.tsym.flags() & FINAL) == 0)
  1610                                 ? sideCast(t, s, warnStack.head)
  1611                                 : sideCastFinal(t, s, warnStack.head);
  1612                         } else {
  1613                             // unrelated class types
  1614                             return false;
  1618                 return false;
  1621             boolean visitIntersectionType(IntersectionClassType ict, Type s, boolean reverse) {
  1622                 Warner warn = noWarnings;
  1623                 for (Type c : ict.getComponents()) {
  1624                     warn.clear();
  1625                     if (reverse ? !isCastable(s, c, warn) : !isCastable(c, s, warn))
  1626                         return false;
  1628                 if (warn.hasLint(LintCategory.UNCHECKED))
  1629                     warnStack.head.warn(LintCategory.UNCHECKED);
  1630                 return true;
  1633             @Override
  1634             public Boolean visitArrayType(ArrayType t, Type s) {
  1635                 switch (s.getTag()) {
  1636                 case ERROR:
  1637                 case BOT:
  1638                     return true;
  1639                 case TYPEVAR:
  1640                     if (isCastable(s, t, noWarnings)) {
  1641                         warnStack.head.warn(LintCategory.UNCHECKED);
  1642                         return true;
  1643                     } else {
  1644                         return false;
  1646                 case CLASS:
  1647                     return isSubtype(t, s);
  1648                 case ARRAY:
  1649                     if (elemtype(t).isPrimitive() || elemtype(s).isPrimitive()) {
  1650                         return elemtype(t).hasTag(elemtype(s).getTag());
  1651                     } else {
  1652                         return visit(elemtype(t), elemtype(s));
  1654                 default:
  1655                     return false;
  1659             @Override
  1660             public Boolean visitTypeVar(TypeVar t, Type s) {
  1661                 switch (s.getTag()) {
  1662                 case ERROR:
  1663                 case BOT:
  1664                     return true;
  1665                 case TYPEVAR:
  1666                     if (isSubtype(t, s)) {
  1667                         return true;
  1668                     } else if (isCastable(t.bound, s, noWarnings)) {
  1669                         warnStack.head.warn(LintCategory.UNCHECKED);
  1670                         return true;
  1671                     } else {
  1672                         return false;
  1674                 default:
  1675                     return isCastable(t.bound, s, warnStack.head);
  1679             @Override
  1680             public Boolean visitErrorType(ErrorType t, Type s) {
  1681                 return true;
  1683         };
  1684     // </editor-fold>
  1686     // <editor-fold defaultstate="collapsed" desc="disjointTypes">
  1687     public boolean disjointTypes(List<Type> ts, List<Type> ss) {
  1688         while (ts.tail != null && ss.tail != null) {
  1689             if (disjointType(ts.head, ss.head)) return true;
  1690             ts = ts.tail;
  1691             ss = ss.tail;
  1693         return false;
  1696     /**
  1697      * Two types or wildcards are considered disjoint if it can be
  1698      * proven that no type can be contained in both. It is
  1699      * conservative in that it is allowed to say that two types are
  1700      * not disjoint, even though they actually are.
  1702      * The type {@code C<X>} is castable to {@code C<Y>} exactly if
  1703      * {@code X} and {@code Y} are not disjoint.
  1704      */
  1705     public boolean disjointType(Type t, Type s) {
  1706         return disjointType.visit(t, s);
  1708     // where
  1709         private TypeRelation disjointType = new TypeRelation() {
  1711             private Set<TypePair> cache = new HashSet<TypePair>();
  1713             @Override
  1714             public Boolean visitType(Type t, Type s) {
  1715                 if (s.hasTag(WILDCARD))
  1716                     return visit(s, t);
  1717                 else
  1718                     return notSoftSubtypeRecursive(t, s) || notSoftSubtypeRecursive(s, t);
  1721             private boolean isCastableRecursive(Type t, Type s) {
  1722                 TypePair pair = new TypePair(t, s);
  1723                 if (cache.add(pair)) {
  1724                     try {
  1725                         return Types.this.isCastable(t, s);
  1726                     } finally {
  1727                         cache.remove(pair);
  1729                 } else {
  1730                     return true;
  1734             private boolean notSoftSubtypeRecursive(Type t, Type s) {
  1735                 TypePair pair = new TypePair(t, s);
  1736                 if (cache.add(pair)) {
  1737                     try {
  1738                         return Types.this.notSoftSubtype(t, s);
  1739                     } finally {
  1740                         cache.remove(pair);
  1742                 } else {
  1743                     return false;
  1747             @Override
  1748             public Boolean visitWildcardType(WildcardType t, Type s) {
  1749                 if (t.isUnbound())
  1750                     return false;
  1752                 if (!s.hasTag(WILDCARD)) {
  1753                     if (t.isExtendsBound())
  1754                         return notSoftSubtypeRecursive(s, t.type);
  1755                     else
  1756                         return notSoftSubtypeRecursive(t.type, s);
  1759                 if (s.isUnbound())
  1760                     return false;
  1762                 if (t.isExtendsBound()) {
  1763                     if (s.isExtendsBound())
  1764                         return !isCastableRecursive(t.type, upperBound(s));
  1765                     else if (s.isSuperBound())
  1766                         return notSoftSubtypeRecursive(lowerBound(s), t.type);
  1767                 } else if (t.isSuperBound()) {
  1768                     if (s.isExtendsBound())
  1769                         return notSoftSubtypeRecursive(t.type, upperBound(s));
  1771                 return false;
  1773         };
  1774     // </editor-fold>
  1776     // <editor-fold defaultstate="collapsed" desc="lowerBoundArgtypes">
  1777     /**
  1778      * Returns the lower bounds of the formals of a method.
  1779      */
  1780     public List<Type> lowerBoundArgtypes(Type t) {
  1781         return lowerBounds(t.getParameterTypes());
  1783     public List<Type> lowerBounds(List<Type> ts) {
  1784         return map(ts, lowerBoundMapping);
  1786     private final Mapping lowerBoundMapping = new Mapping("lowerBound") {
  1787             public Type apply(Type t) {
  1788                 return lowerBound(t);
  1790         };
  1791     // </editor-fold>
  1793     // <editor-fold defaultstate="collapsed" desc="notSoftSubtype">
  1794     /**
  1795      * This relation answers the question: is impossible that
  1796      * something of type `t' can be a subtype of `s'? This is
  1797      * different from the question "is `t' not a subtype of `s'?"
  1798      * when type variables are involved: Integer is not a subtype of T
  1799      * where {@code <T extends Number>} but it is not true that Integer cannot
  1800      * possibly be a subtype of T.
  1801      */
  1802     public boolean notSoftSubtype(Type t, Type s) {
  1803         if (t == s) return false;
  1804         if (t.hasTag(TYPEVAR)) {
  1805             TypeVar tv = (TypeVar) t;
  1806             return !isCastable(tv.bound,
  1807                                relaxBound(s),
  1808                                noWarnings);
  1810         if (!s.hasTag(WILDCARD))
  1811             s = upperBound(s);
  1813         return !isSubtype(t, relaxBound(s));
  1816     private Type relaxBound(Type t) {
  1817         if (t.hasTag(TYPEVAR)) {
  1818             while (t.hasTag(TYPEVAR))
  1819                 t = t.getUpperBound();
  1820             t = rewriteQuantifiers(t, true, true);
  1822         return t;
  1824     // </editor-fold>
  1826     // <editor-fold defaultstate="collapsed" desc="isReifiable">
  1827     public boolean isReifiable(Type t) {
  1828         return isReifiable.visit(t);
  1830     // where
  1831         private UnaryVisitor<Boolean> isReifiable = new UnaryVisitor<Boolean>() {
  1833             public Boolean visitType(Type t, Void ignored) {
  1834                 return true;
  1837             @Override
  1838             public Boolean visitClassType(ClassType t, Void ignored) {
  1839                 if (t.isCompound())
  1840                     return false;
  1841                 else {
  1842                     if (!t.isParameterized())
  1843                         return true;
  1845                     for (Type param : t.allparams()) {
  1846                         if (!param.isUnbound())
  1847                             return false;
  1849                     return true;
  1853             @Override
  1854             public Boolean visitArrayType(ArrayType t, Void ignored) {
  1855                 return visit(t.elemtype);
  1858             @Override
  1859             public Boolean visitTypeVar(TypeVar t, Void ignored) {
  1860                 return false;
  1862         };
  1863     // </editor-fold>
  1865     // <editor-fold defaultstate="collapsed" desc="Array Utils">
  1866     public boolean isArray(Type t) {
  1867         while (t.hasTag(WILDCARD))
  1868             t = upperBound(t);
  1869         return t.hasTag(ARRAY);
  1872     /**
  1873      * The element type of an array.
  1874      */
  1875     public Type elemtype(Type t) {
  1876         switch (t.getTag()) {
  1877         case WILDCARD:
  1878             return elemtype(upperBound(t));
  1879         case ARRAY:
  1880             t = t.unannotatedType();
  1881             return ((ArrayType)t).elemtype;
  1882         case FORALL:
  1883             return elemtype(((ForAll)t).qtype);
  1884         case ERROR:
  1885             return t;
  1886         default:
  1887             return null;
  1891     public Type elemtypeOrType(Type t) {
  1892         Type elemtype = elemtype(t);
  1893         return elemtype != null ?
  1894             elemtype :
  1895             t;
  1898     /**
  1899      * Mapping to take element type of an arraytype
  1900      */
  1901     private Mapping elemTypeFun = new Mapping ("elemTypeFun") {
  1902         public Type apply(Type t) { return elemtype(t); }
  1903     };
  1905     /**
  1906      * The number of dimensions of an array type.
  1907      */
  1908     public int dimensions(Type t) {
  1909         int result = 0;
  1910         while (t.hasTag(ARRAY)) {
  1911             result++;
  1912             t = elemtype(t);
  1914         return result;
  1917     /**
  1918      * Returns an ArrayType with the component type t
  1920      * @param t The component type of the ArrayType
  1921      * @return the ArrayType for the given component
  1922      */
  1923     public ArrayType makeArrayType(Type t) {
  1924         if (t.hasTag(VOID) || t.hasTag(PACKAGE)) {
  1925             Assert.error("Type t must not be a VOID or PACKAGE type, " + t.toString());
  1927         return new ArrayType(t, syms.arrayClass);
  1929     // </editor-fold>
  1931     // <editor-fold defaultstate="collapsed" desc="asSuper">
  1932     /**
  1933      * Return the (most specific) base type of t that starts with the
  1934      * given symbol.  If none exists, return null.
  1936      * @param t a type
  1937      * @param sym a symbol
  1938      */
  1939     public Type asSuper(Type t, Symbol sym) {
  1940         return asSuper.visit(t, sym);
  1942     // where
  1943         private SimpleVisitor<Type,Symbol> asSuper = new SimpleVisitor<Type,Symbol>() {
  1945             public Type visitType(Type t, Symbol sym) {
  1946                 return null;
  1949             @Override
  1950             public Type visitClassType(ClassType t, Symbol sym) {
  1951                 if (t.tsym == sym)
  1952                     return t;
  1954                 Type st = supertype(t);
  1955                 if (st.hasTag(CLASS) || st.hasTag(TYPEVAR) || st.hasTag(ERROR)) {
  1956                     Type x = asSuper(st, sym);
  1957                     if (x != null)
  1958                         return x;
  1960                 if ((sym.flags() & INTERFACE) != 0) {
  1961                     for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
  1962                         Type x = asSuper(l.head, sym);
  1963                         if (x != null)
  1964                             return x;
  1967                 return null;
  1970             @Override
  1971             public Type visitArrayType(ArrayType t, Symbol sym) {
  1972                 return isSubtype(t, sym.type) ? sym.type : null;
  1975             @Override
  1976             public Type visitTypeVar(TypeVar t, Symbol sym) {
  1977                 if (t.tsym == sym)
  1978                     return t;
  1979                 else
  1980                     return asSuper(t.bound, sym);
  1983             @Override
  1984             public Type visitErrorType(ErrorType t, Symbol sym) {
  1985                 return t;
  1987         };
  1989     /**
  1990      * Return the base type of t or any of its outer types that starts
  1991      * with the given symbol.  If none exists, return null.
  1993      * @param t a type
  1994      * @param sym a symbol
  1995      */
  1996     public Type asOuterSuper(Type t, Symbol sym) {
  1997         switch (t.getTag()) {
  1998         case CLASS:
  1999             do {
  2000                 Type s = asSuper(t, sym);
  2001                 if (s != null) return s;
  2002                 t = t.getEnclosingType();
  2003             } while (t.hasTag(CLASS));
  2004             return null;
  2005         case ARRAY:
  2006             return isSubtype(t, sym.type) ? sym.type : null;
  2007         case TYPEVAR:
  2008             return asSuper(t, sym);
  2009         case ERROR:
  2010             return t;
  2011         default:
  2012             return null;
  2016     /**
  2017      * Return the base type of t or any of its enclosing types that
  2018      * starts with the given symbol.  If none exists, return null.
  2020      * @param t a type
  2021      * @param sym a symbol
  2022      */
  2023     public Type asEnclosingSuper(Type t, Symbol sym) {
  2024         switch (t.getTag()) {
  2025         case CLASS:
  2026             do {
  2027                 Type s = asSuper(t, sym);
  2028                 if (s != null) return s;
  2029                 Type outer = t.getEnclosingType();
  2030                 t = (outer.hasTag(CLASS)) ? outer :
  2031                     (t.tsym.owner.enclClass() != null) ? t.tsym.owner.enclClass().type :
  2032                     Type.noType;
  2033             } while (t.hasTag(CLASS));
  2034             return null;
  2035         case ARRAY:
  2036             return isSubtype(t, sym.type) ? sym.type : null;
  2037         case TYPEVAR:
  2038             return asSuper(t, sym);
  2039         case ERROR:
  2040             return t;
  2041         default:
  2042             return null;
  2045     // </editor-fold>
  2047     // <editor-fold defaultstate="collapsed" desc="memberType">
  2048     /**
  2049      * The type of given symbol, seen as a member of t.
  2051      * @param t a type
  2052      * @param sym a symbol
  2053      */
  2054     public Type memberType(Type t, Symbol sym) {
  2055         return (sym.flags() & STATIC) != 0
  2056             ? sym.type
  2057             : memberType.visit(t, sym);
  2059     // where
  2060         private SimpleVisitor<Type,Symbol> memberType = new SimpleVisitor<Type,Symbol>() {
  2062             public Type visitType(Type t, Symbol sym) {
  2063                 return sym.type;
  2066             @Override
  2067             public Type visitWildcardType(WildcardType t, Symbol sym) {
  2068                 return memberType(upperBound(t), sym);
  2071             @Override
  2072             public Type visitClassType(ClassType t, Symbol sym) {
  2073                 Symbol owner = sym.owner;
  2074                 long flags = sym.flags();
  2075                 if (((flags & STATIC) == 0) && owner.type.isParameterized()) {
  2076                     Type base = asOuterSuper(t, owner);
  2077                     //if t is an intersection type T = CT & I1 & I2 ... & In
  2078                     //its supertypes CT, I1, ... In might contain wildcards
  2079                     //so we need to go through capture conversion
  2080                     base = t.isCompound() ? capture(base) : base;
  2081                     if (base != null) {
  2082                         List<Type> ownerParams = owner.type.allparams();
  2083                         List<Type> baseParams = base.allparams();
  2084                         if (ownerParams.nonEmpty()) {
  2085                             if (baseParams.isEmpty()) {
  2086                                 // then base is a raw type
  2087                                 return erasure(sym.type);
  2088                             } else {
  2089                                 return subst(sym.type, ownerParams, baseParams);
  2094                 return sym.type;
  2097             @Override
  2098             public Type visitTypeVar(TypeVar t, Symbol sym) {
  2099                 return memberType(t.bound, sym);
  2102             @Override
  2103             public Type visitErrorType(ErrorType t, Symbol sym) {
  2104                 return t;
  2106         };
  2107     // </editor-fold>
  2109     // <editor-fold defaultstate="collapsed" desc="isAssignable">
  2110     public boolean isAssignable(Type t, Type s) {
  2111         return isAssignable(t, s, noWarnings);
  2114     /**
  2115      * Is t assignable to s?<br>
  2116      * Equivalent to subtype except for constant values and raw
  2117      * types.<br>
  2118      * (not defined for Method and ForAll types)
  2119      */
  2120     public boolean isAssignable(Type t, Type s, Warner warn) {
  2121         if (t.hasTag(ERROR))
  2122             return true;
  2123         if (t.getTag().isSubRangeOf(INT) && t.constValue() != null) {
  2124             int value = ((Number)t.constValue()).intValue();
  2125             switch (s.getTag()) {
  2126             case BYTE:
  2127                 if (Byte.MIN_VALUE <= value && value <= Byte.MAX_VALUE)
  2128                     return true;
  2129                 break;
  2130             case CHAR:
  2131                 if (Character.MIN_VALUE <= value && value <= Character.MAX_VALUE)
  2132                     return true;
  2133                 break;
  2134             case SHORT:
  2135                 if (Short.MIN_VALUE <= value && value <= Short.MAX_VALUE)
  2136                     return true;
  2137                 break;
  2138             case INT:
  2139                 return true;
  2140             case CLASS:
  2141                 switch (unboxedType(s).getTag()) {
  2142                 case BYTE:
  2143                 case CHAR:
  2144                 case SHORT:
  2145                     return isAssignable(t, unboxedType(s), warn);
  2147                 break;
  2150         return isConvertible(t, s, warn);
  2152     // </editor-fold>
  2154     // <editor-fold defaultstate="collapsed" desc="erasure">
  2155     /**
  2156      * The erasure of t {@code |t|} -- the type that results when all
  2157      * type parameters in t are deleted.
  2158      */
  2159     public Type erasure(Type t) {
  2160         return eraseNotNeeded(t)? t : erasure(t, false);
  2162     //where
  2163     private boolean eraseNotNeeded(Type t) {
  2164         // We don't want to erase primitive types and String type as that
  2165         // operation is idempotent. Also, erasing these could result in loss
  2166         // of information such as constant values attached to such types.
  2167         return (t.isPrimitive()) || (syms.stringType.tsym == t.tsym);
  2170     private Type erasure(Type t, boolean recurse) {
  2171         if (t.isPrimitive())
  2172             return t; /* fast special case */
  2173         else
  2174             return erasure.visit(t, recurse);
  2176     // where
  2177         private SimpleVisitor<Type, Boolean> erasure = new SimpleVisitor<Type, Boolean>() {
  2178             public Type visitType(Type t, Boolean recurse) {
  2179                 if (t.isPrimitive())
  2180                     return t; /*fast special case*/
  2181                 else
  2182                     return t.map(recurse ? erasureRecFun : erasureFun);
  2185             @Override
  2186             public Type visitWildcardType(WildcardType t, Boolean recurse) {
  2187                 return erasure(upperBound(t), recurse);
  2190             @Override
  2191             public Type visitClassType(ClassType t, Boolean recurse) {
  2192                 Type erased = t.tsym.erasure(Types.this);
  2193                 if (recurse) {
  2194                     erased = new ErasedClassType(erased.getEnclosingType(),erased.tsym);
  2196                 return erased;
  2199             @Override
  2200             public Type visitTypeVar(TypeVar t, Boolean recurse) {
  2201                 return erasure(t.bound, recurse);
  2204             @Override
  2205             public Type visitErrorType(ErrorType t, Boolean recurse) {
  2206                 return t;
  2209             @Override
  2210             public Type visitAnnotatedType(AnnotatedType t, Boolean recurse) {
  2211                 Type erased = erasure(t.underlyingType, recurse);
  2212                 if (erased.isAnnotated()) {
  2213                     // This can only happen when the underlying type is a
  2214                     // type variable and the upper bound of it is annotated.
  2215                     // The annotation on the type variable overrides the one
  2216                     // on the bound.
  2217                     erased = ((AnnotatedType)erased).underlyingType;
  2219                 return new AnnotatedType(t.typeAnnotations, erased);
  2221         };
  2223     private Mapping erasureFun = new Mapping ("erasure") {
  2224             public Type apply(Type t) { return erasure(t); }
  2225         };
  2227     private Mapping erasureRecFun = new Mapping ("erasureRecursive") {
  2228         public Type apply(Type t) { return erasureRecursive(t); }
  2229     };
  2231     public List<Type> erasure(List<Type> ts) {
  2232         return Type.map(ts, erasureFun);
  2235     public Type erasureRecursive(Type t) {
  2236         return erasure(t, true);
  2239     public List<Type> erasureRecursive(List<Type> ts) {
  2240         return Type.map(ts, erasureRecFun);
  2242     // </editor-fold>
  2244     // <editor-fold defaultstate="collapsed" desc="makeCompoundType">
  2245     /**
  2246      * Make a compound type from non-empty list of types
  2248      * @param bounds            the types from which the compound type is formed
  2249      * @param supertype         is objectType if all bounds are interfaces,
  2250      *                          null otherwise.
  2251      */
  2252     public Type makeCompoundType(List<Type> bounds) {
  2253         return makeCompoundType(bounds, bounds.head.tsym.isInterface());
  2255     public Type makeCompoundType(List<Type> bounds, boolean allInterfaces) {
  2256         Assert.check(bounds.nonEmpty());
  2257         Type firstExplicitBound = bounds.head;
  2258         if (allInterfaces) {
  2259             bounds = bounds.prepend(syms.objectType);
  2261         ClassSymbol bc =
  2262             new ClassSymbol(ABSTRACT|PUBLIC|SYNTHETIC|COMPOUND|ACYCLIC,
  2263                             Type.moreInfo
  2264                                 ? names.fromString(bounds.toString())
  2265                                 : names.empty,
  2266                             null,
  2267                             syms.noSymbol);
  2268         bc.type = new IntersectionClassType(bounds, bc, allInterfaces);
  2269         bc.erasure_field = (bounds.head.hasTag(TYPEVAR)) ?
  2270                 syms.objectType : // error condition, recover
  2271                 erasure(firstExplicitBound);
  2272         bc.members_field = new Scope(bc);
  2273         return bc.type;
  2276     /**
  2277      * A convenience wrapper for {@link #makeCompoundType(List)}; the
  2278      * arguments are converted to a list and passed to the other
  2279      * method.  Note that this might cause a symbol completion.
  2280      * Hence, this version of makeCompoundType may not be called
  2281      * during a classfile read.
  2282      */
  2283     public Type makeCompoundType(Type bound1, Type bound2) {
  2284         return makeCompoundType(List.of(bound1, bound2));
  2286     // </editor-fold>
  2288     // <editor-fold defaultstate="collapsed" desc="supertype">
  2289     public Type supertype(Type t) {
  2290         return supertype.visit(t);
  2292     // where
  2293         private UnaryVisitor<Type> supertype = new UnaryVisitor<Type>() {
  2295             public Type visitType(Type t, Void ignored) {
  2296                 // A note on wildcards: there is no good way to
  2297                 // determine a supertype for a super bounded wildcard.
  2298                 return null;
  2301             @Override
  2302             public Type visitClassType(ClassType t, Void ignored) {
  2303                 if (t.supertype_field == null) {
  2304                     Type supertype = ((ClassSymbol)t.tsym).getSuperclass();
  2305                     // An interface has no superclass; its supertype is Object.
  2306                     if (t.isInterface())
  2307                         supertype = ((ClassType)t.tsym.type).supertype_field;
  2308                     if (t.supertype_field == null) {
  2309                         List<Type> actuals = classBound(t).allparams();
  2310                         List<Type> formals = t.tsym.type.allparams();
  2311                         if (t.hasErasedSupertypes()) {
  2312                             t.supertype_field = erasureRecursive(supertype);
  2313                         } else if (formals.nonEmpty()) {
  2314                             t.supertype_field = subst(supertype, formals, actuals);
  2316                         else {
  2317                             t.supertype_field = supertype;
  2321                 return t.supertype_field;
  2324             /**
  2325              * The supertype is always a class type. If the type
  2326              * variable's bounds start with a class type, this is also
  2327              * the supertype.  Otherwise, the supertype is
  2328              * java.lang.Object.
  2329              */
  2330             @Override
  2331             public Type visitTypeVar(TypeVar t, Void ignored) {
  2332                 if (t.bound.hasTag(TYPEVAR) ||
  2333                     (!t.bound.isCompound() && !t.bound.isInterface())) {
  2334                     return t.bound;
  2335                 } else {
  2336                     return supertype(t.bound);
  2340             @Override
  2341             public Type visitArrayType(ArrayType t, Void ignored) {
  2342                 if (t.elemtype.isPrimitive() || isSameType(t.elemtype, syms.objectType))
  2343                     return arraySuperType();
  2344                 else
  2345                     return new ArrayType(supertype(t.elemtype), t.tsym);
  2348             @Override
  2349             public Type visitErrorType(ErrorType t, Void ignored) {
  2350                 return Type.noType;
  2352         };
  2353     // </editor-fold>
  2355     // <editor-fold defaultstate="collapsed" desc="interfaces">
  2356     /**
  2357      * Return the interfaces implemented by this class.
  2358      */
  2359     public List<Type> interfaces(Type t) {
  2360         return interfaces.visit(t);
  2362     // where
  2363         private UnaryVisitor<List<Type>> interfaces = new UnaryVisitor<List<Type>>() {
  2365             public List<Type> visitType(Type t, Void ignored) {
  2366                 return List.nil();
  2369             @Override
  2370             public List<Type> visitClassType(ClassType t, Void ignored) {
  2371                 if (t.interfaces_field == null) {
  2372                     List<Type> interfaces = ((ClassSymbol)t.tsym).getInterfaces();
  2373                     if (t.interfaces_field == null) {
  2374                         // If t.interfaces_field is null, then t must
  2375                         // be a parameterized type (not to be confused
  2376                         // with a generic type declaration).
  2377                         // Terminology:
  2378                         //    Parameterized type: List<String>
  2379                         //    Generic type declaration: class List<E> { ... }
  2380                         // So t corresponds to List<String> and
  2381                         // t.tsym.type corresponds to List<E>.
  2382                         // The reason t must be parameterized type is
  2383                         // that completion will happen as a side
  2384                         // effect of calling
  2385                         // ClassSymbol.getInterfaces.  Since
  2386                         // t.interfaces_field is null after
  2387                         // completion, we can assume that t is not the
  2388                         // type of a class/interface declaration.
  2389                         Assert.check(t != t.tsym.type, t);
  2390                         List<Type> actuals = t.allparams();
  2391                         List<Type> formals = t.tsym.type.allparams();
  2392                         if (t.hasErasedSupertypes()) {
  2393                             t.interfaces_field = erasureRecursive(interfaces);
  2394                         } else if (formals.nonEmpty()) {
  2395                             t.interfaces_field =
  2396                                 upperBounds(subst(interfaces, formals, actuals));
  2398                         else {
  2399                             t.interfaces_field = interfaces;
  2403                 return t.interfaces_field;
  2406             @Override
  2407             public List<Type> visitTypeVar(TypeVar t, Void ignored) {
  2408                 if (t.bound.isCompound())
  2409                     return interfaces(t.bound);
  2411                 if (t.bound.isInterface())
  2412                     return List.of(t.bound);
  2414                 return List.nil();
  2416         };
  2418     public boolean isDirectSuperInterface(TypeSymbol isym, TypeSymbol origin) {
  2419         for (Type i2 : interfaces(origin.type)) {
  2420             if (isym == i2.tsym) return true;
  2422         return false;
  2424     // </editor-fold>
  2426     // <editor-fold defaultstate="collapsed" desc="isDerivedRaw">
  2427     Map<Type,Boolean> isDerivedRawCache = new HashMap<Type,Boolean>();
  2429     public boolean isDerivedRaw(Type t) {
  2430         Boolean result = isDerivedRawCache.get(t);
  2431         if (result == null) {
  2432             result = isDerivedRawInternal(t);
  2433             isDerivedRawCache.put(t, result);
  2435         return result;
  2438     public boolean isDerivedRawInternal(Type t) {
  2439         if (t.isErroneous())
  2440             return false;
  2441         return
  2442             t.isRaw() ||
  2443             supertype(t) != null && isDerivedRaw(supertype(t)) ||
  2444             isDerivedRaw(interfaces(t));
  2447     public boolean isDerivedRaw(List<Type> ts) {
  2448         List<Type> l = ts;
  2449         while (l.nonEmpty() && !isDerivedRaw(l.head)) l = l.tail;
  2450         return l.nonEmpty();
  2452     // </editor-fold>
  2454     // <editor-fold defaultstate="collapsed" desc="setBounds">
  2455     /**
  2456      * Set the bounds field of the given type variable to reflect a
  2457      * (possibly multiple) list of bounds.
  2458      * @param t                 a type variable
  2459      * @param bounds            the bounds, must be nonempty
  2460      * @param supertype         is objectType if all bounds are interfaces,
  2461      *                          null otherwise.
  2462      */
  2463     public void setBounds(TypeVar t, List<Type> bounds) {
  2464         setBounds(t, bounds, bounds.head.tsym.isInterface());
  2467     /**
  2468      * Same as {@link #setBounds(Type.TypeVar,List,Type)}, except that
  2469      * third parameter is computed directly, as follows: if all
  2470      * all bounds are interface types, the computed supertype is Object,
  2471      * otherwise the supertype is simply left null (in this case, the supertype
  2472      * is assumed to be the head of the bound list passed as second argument).
  2473      * Note that this check might cause a symbol completion. Hence, this version of
  2474      * setBounds may not be called during a classfile read.
  2475      */
  2476     public void setBounds(TypeVar t, List<Type> bounds, boolean allInterfaces) {
  2477         t.bound = bounds.tail.isEmpty() ?
  2478                 bounds.head :
  2479                 makeCompoundType(bounds, allInterfaces);
  2480         t.rank_field = -1;
  2482     // </editor-fold>
  2484     // <editor-fold defaultstate="collapsed" desc="getBounds">
  2485     /**
  2486      * Return list of bounds of the given type variable.
  2487      */
  2488     public List<Type> getBounds(TypeVar t) {
  2489         if (t.bound.hasTag(NONE))
  2490             return List.nil();
  2491         else if (t.bound.isErroneous() || !t.bound.isCompound())
  2492             return List.of(t.bound);
  2493         else if ((erasure(t).tsym.flags() & INTERFACE) == 0)
  2494             return interfaces(t).prepend(supertype(t));
  2495         else
  2496             // No superclass was given in bounds.
  2497             // In this case, supertype is Object, erasure is first interface.
  2498             return interfaces(t);
  2500     // </editor-fold>
  2502     // <editor-fold defaultstate="collapsed" desc="classBound">
  2503     /**
  2504      * If the given type is a (possibly selected) type variable,
  2505      * return the bounding class of this type, otherwise return the
  2506      * type itself.
  2507      */
  2508     public Type classBound(Type t) {
  2509         return classBound.visit(t);
  2511     // where
  2512         private UnaryVisitor<Type> classBound = new UnaryVisitor<Type>() {
  2514             public Type visitType(Type t, Void ignored) {
  2515                 return t;
  2518             @Override
  2519             public Type visitClassType(ClassType t, Void ignored) {
  2520                 Type outer1 = classBound(t.getEnclosingType());
  2521                 if (outer1 != t.getEnclosingType())
  2522                     return new ClassType(outer1, t.getTypeArguments(), t.tsym);
  2523                 else
  2524                     return t;
  2527             @Override
  2528             public Type visitTypeVar(TypeVar t, Void ignored) {
  2529                 return classBound(supertype(t));
  2532             @Override
  2533             public Type visitErrorType(ErrorType t, Void ignored) {
  2534                 return t;
  2536         };
  2537     // </editor-fold>
  2539     // <editor-fold defaultstate="collapsed" desc="sub signature / override equivalence">
  2540     /**
  2541      * Returns true iff the first signature is a <em>sub
  2542      * signature</em> of the other.  This is <b>not</b> an equivalence
  2543      * relation.
  2545      * @jls section 8.4.2.
  2546      * @see #overrideEquivalent(Type t, Type s)
  2547      * @param t first signature (possibly raw).
  2548      * @param s second signature (could be subjected to erasure).
  2549      * @return true if t is a sub signature of s.
  2550      */
  2551     public boolean isSubSignature(Type t, Type s) {
  2552         return isSubSignature(t, s, true);
  2555     public boolean isSubSignature(Type t, Type s, boolean strict) {
  2556         return hasSameArgs(t, s, strict) || hasSameArgs(t, erasure(s), strict);
  2559     /**
  2560      * Returns true iff these signatures are related by <em>override
  2561      * equivalence</em>.  This is the natural extension of
  2562      * isSubSignature to an equivalence relation.
  2564      * @jls section 8.4.2.
  2565      * @see #isSubSignature(Type t, Type s)
  2566      * @param t a signature (possible raw, could be subjected to
  2567      * erasure).
  2568      * @param s a signature (possible raw, could be subjected to
  2569      * erasure).
  2570      * @return true if either argument is a sub signature of the other.
  2571      */
  2572     public boolean overrideEquivalent(Type t, Type s) {
  2573         return hasSameArgs(t, s) ||
  2574             hasSameArgs(t, erasure(s)) || hasSameArgs(erasure(t), s);
  2577     public boolean overridesObjectMethod(TypeSymbol origin, Symbol msym) {
  2578         for (Scope.Entry e = syms.objectType.tsym.members().lookup(msym.name) ; e.scope != null ; e = e.next()) {
  2579             if (msym.overrides(e.sym, origin, Types.this, true)) {
  2580                 return true;
  2583         return false;
  2586     // <editor-fold defaultstate="collapsed" desc="Determining method implementation in given site">
  2587     class ImplementationCache {
  2589         private WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>> _map =
  2590                 new WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>>();
  2592         class Entry {
  2593             final MethodSymbol cachedImpl;
  2594             final Filter<Symbol> implFilter;
  2595             final boolean checkResult;
  2596             final int prevMark;
  2598             public Entry(MethodSymbol cachedImpl,
  2599                     Filter<Symbol> scopeFilter,
  2600                     boolean checkResult,
  2601                     int prevMark) {
  2602                 this.cachedImpl = cachedImpl;
  2603                 this.implFilter = scopeFilter;
  2604                 this.checkResult = checkResult;
  2605                 this.prevMark = prevMark;
  2608             boolean matches(Filter<Symbol> scopeFilter, boolean checkResult, int mark) {
  2609                 return this.implFilter == scopeFilter &&
  2610                         this.checkResult == checkResult &&
  2611                         this.prevMark == mark;
  2615         MethodSymbol get(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
  2616             SoftReference<Map<TypeSymbol, Entry>> ref_cache = _map.get(ms);
  2617             Map<TypeSymbol, Entry> cache = ref_cache != null ? ref_cache.get() : null;
  2618             if (cache == null) {
  2619                 cache = new HashMap<TypeSymbol, Entry>();
  2620                 _map.put(ms, new SoftReference<Map<TypeSymbol, Entry>>(cache));
  2622             Entry e = cache.get(origin);
  2623             CompoundScope members = membersClosure(origin.type, true);
  2624             if (e == null ||
  2625                     !e.matches(implFilter, checkResult, members.getMark())) {
  2626                 MethodSymbol impl = implementationInternal(ms, origin, checkResult, implFilter);
  2627                 cache.put(origin, new Entry(impl, implFilter, checkResult, members.getMark()));
  2628                 return impl;
  2630             else {
  2631                 return e.cachedImpl;
  2635         private MethodSymbol implementationInternal(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
  2636             for (Type t = origin.type; t.hasTag(CLASS) || t.hasTag(TYPEVAR); t = supertype(t)) {
  2637                 while (t.hasTag(TYPEVAR))
  2638                     t = t.getUpperBound();
  2639                 TypeSymbol c = t.tsym;
  2640                 for (Scope.Entry e = c.members().lookup(ms.name, implFilter);
  2641                      e.scope != null;
  2642                      e = e.next(implFilter)) {
  2643                     if (e.sym != null &&
  2644                              e.sym.overrides(ms, origin, Types.this, checkResult))
  2645                         return (MethodSymbol)e.sym;
  2648             return null;
  2652     private ImplementationCache implCache = new ImplementationCache();
  2654     public MethodSymbol implementation(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
  2655         return implCache.get(ms, origin, checkResult, implFilter);
  2657     // </editor-fold>
  2659     // <editor-fold defaultstate="collapsed" desc="compute transitive closure of all members in given site">
  2660     class MembersClosureCache extends SimpleVisitor<CompoundScope, Boolean> {
  2662         private WeakHashMap<TypeSymbol, Entry> _map =
  2663                 new WeakHashMap<TypeSymbol, Entry>();
  2665         class Entry {
  2666             final boolean skipInterfaces;
  2667             final CompoundScope compoundScope;
  2669             public Entry(boolean skipInterfaces, CompoundScope compoundScope) {
  2670                 this.skipInterfaces = skipInterfaces;
  2671                 this.compoundScope = compoundScope;
  2674             boolean matches(boolean skipInterfaces) {
  2675                 return this.skipInterfaces == skipInterfaces;
  2679         List<TypeSymbol> seenTypes = List.nil();
  2681         /** members closure visitor methods **/
  2683         public CompoundScope visitType(Type t, Boolean skipInterface) {
  2684             return null;
  2687         @Override
  2688         public CompoundScope visitClassType(ClassType t, Boolean skipInterface) {
  2689             if (seenTypes.contains(t.tsym)) {
  2690                 //this is possible when an interface is implemented in multiple
  2691                 //superclasses, or when a classs hierarchy is circular - in such
  2692                 //cases we don't need to recurse (empty scope is returned)
  2693                 return new CompoundScope(t.tsym);
  2695             try {
  2696                 seenTypes = seenTypes.prepend(t.tsym);
  2697                 ClassSymbol csym = (ClassSymbol)t.tsym;
  2698                 Entry e = _map.get(csym);
  2699                 if (e == null || !e.matches(skipInterface)) {
  2700                     CompoundScope membersClosure = new CompoundScope(csym);
  2701                     if (!skipInterface) {
  2702                         for (Type i : interfaces(t)) {
  2703                             membersClosure.addSubScope(visit(i, skipInterface));
  2706                     membersClosure.addSubScope(visit(supertype(t), skipInterface));
  2707                     membersClosure.addSubScope(csym.members());
  2708                     e = new Entry(skipInterface, membersClosure);
  2709                     _map.put(csym, e);
  2711                 return e.compoundScope;
  2713             finally {
  2714                 seenTypes = seenTypes.tail;
  2718         @Override
  2719         public CompoundScope visitTypeVar(TypeVar t, Boolean skipInterface) {
  2720             return visit(t.getUpperBound(), skipInterface);
  2724     private MembersClosureCache membersCache = new MembersClosureCache();
  2726     public CompoundScope membersClosure(Type site, boolean skipInterface) {
  2727         return membersCache.visit(site, skipInterface);
  2729     // </editor-fold>
  2732     //where
  2733     public List<MethodSymbol> interfaceCandidates(Type site, MethodSymbol ms) {
  2734         Filter<Symbol> filter = new MethodFilter(ms, site);
  2735         List<MethodSymbol> candidates = List.nil();
  2736             for (Symbol s : membersClosure(site, false).getElements(filter)) {
  2737                 if (!site.tsym.isInterface() && !s.owner.isInterface()) {
  2738                     return List.of((MethodSymbol)s);
  2739                 } else if (!candidates.contains(s)) {
  2740                     candidates = candidates.prepend((MethodSymbol)s);
  2743             return prune(candidates);
  2746     public List<MethodSymbol> prune(List<MethodSymbol> methods) {
  2747         ListBuffer<MethodSymbol> methodsMin = ListBuffer.lb();
  2748         for (MethodSymbol m1 : methods) {
  2749             boolean isMin_m1 = true;
  2750             for (MethodSymbol m2 : methods) {
  2751                 if (m1 == m2) continue;
  2752                 if (m2.owner != m1.owner &&
  2753                         asSuper(m2.owner.type, m1.owner) != null) {
  2754                     isMin_m1 = false;
  2755                     break;
  2758             if (isMin_m1)
  2759                 methodsMin.append(m1);
  2761         return methodsMin.toList();
  2763     // where
  2764             private class MethodFilter implements Filter<Symbol> {
  2766                 Symbol msym;
  2767                 Type site;
  2769                 MethodFilter(Symbol msym, Type site) {
  2770                     this.msym = msym;
  2771                     this.site = site;
  2774                 public boolean accepts(Symbol s) {
  2775                     return s.kind == Kinds.MTH &&
  2776                             s.name == msym.name &&
  2777                             (s.flags() & SYNTHETIC) == 0 &&
  2778                             s.isInheritedIn(site.tsym, Types.this) &&
  2779                             overrideEquivalent(memberType(site, s), memberType(site, msym));
  2781             };
  2782     // </editor-fold>
  2784     /**
  2785      * Does t have the same arguments as s?  It is assumed that both
  2786      * types are (possibly polymorphic) method types.  Monomorphic
  2787      * method types "have the same arguments", if their argument lists
  2788      * are equal.  Polymorphic method types "have the same arguments",
  2789      * if they have the same arguments after renaming all type
  2790      * variables of one to corresponding type variables in the other,
  2791      * where correspondence is by position in the type parameter list.
  2792      */
  2793     public boolean hasSameArgs(Type t, Type s) {
  2794         return hasSameArgs(t, s, true);
  2797     public boolean hasSameArgs(Type t, Type s, boolean strict) {
  2798         return hasSameArgs(t, s, strict ? hasSameArgs_strict : hasSameArgs_nonstrict);
  2801     private boolean hasSameArgs(Type t, Type s, TypeRelation hasSameArgs) {
  2802         return hasSameArgs.visit(t, s);
  2804     // where
  2805         private class HasSameArgs extends TypeRelation {
  2807             boolean strict;
  2809             public HasSameArgs(boolean strict) {
  2810                 this.strict = strict;
  2813             public Boolean visitType(Type t, Type s) {
  2814                 throw new AssertionError();
  2817             @Override
  2818             public Boolean visitMethodType(MethodType t, Type s) {
  2819                 return s.hasTag(METHOD)
  2820                     && containsTypeEquivalent(t.argtypes, s.getParameterTypes());
  2823             @Override
  2824             public Boolean visitForAll(ForAll t, Type s) {
  2825                 if (!s.hasTag(FORALL))
  2826                     return strict ? false : visitMethodType(t.asMethodType(), s);
  2828                 ForAll forAll = (ForAll)s;
  2829                 return hasSameBounds(t, forAll)
  2830                     && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
  2833             @Override
  2834             public Boolean visitErrorType(ErrorType t, Type s) {
  2835                 return false;
  2837         };
  2839         TypeRelation hasSameArgs_strict = new HasSameArgs(true);
  2840         TypeRelation hasSameArgs_nonstrict = new HasSameArgs(false);
  2842     // </editor-fold>
  2844     // <editor-fold defaultstate="collapsed" desc="subst">
  2845     public List<Type> subst(List<Type> ts,
  2846                             List<Type> from,
  2847                             List<Type> to) {
  2848         return new Subst(from, to).subst(ts);
  2851     /**
  2852      * Substitute all occurrences of a type in `from' with the
  2853      * corresponding type in `to' in 't'. Match lists `from' and `to'
  2854      * from the right: If lists have different length, discard leading
  2855      * elements of the longer list.
  2856      */
  2857     public Type subst(Type t, List<Type> from, List<Type> to) {
  2858         return new Subst(from, to).subst(t);
  2861     private class Subst extends UnaryVisitor<Type> {
  2862         List<Type> from;
  2863         List<Type> to;
  2865         public Subst(List<Type> from, List<Type> to) {
  2866             int fromLength = from.length();
  2867             int toLength = to.length();
  2868             while (fromLength > toLength) {
  2869                 fromLength--;
  2870                 from = from.tail;
  2872             while (fromLength < toLength) {
  2873                 toLength--;
  2874                 to = to.tail;
  2876             this.from = from;
  2877             this.to = to;
  2880         Type subst(Type t) {
  2881             if (from.tail == null)
  2882                 return t;
  2883             else
  2884                 return visit(t);
  2887         List<Type> subst(List<Type> ts) {
  2888             if (from.tail == null)
  2889                 return ts;
  2890             boolean wild = false;
  2891             if (ts.nonEmpty() && from.nonEmpty()) {
  2892                 Type head1 = subst(ts.head);
  2893                 List<Type> tail1 = subst(ts.tail);
  2894                 if (head1 != ts.head || tail1 != ts.tail)
  2895                     return tail1.prepend(head1);
  2897             return ts;
  2900         public Type visitType(Type t, Void ignored) {
  2901             return t;
  2904         @Override
  2905         public Type visitMethodType(MethodType t, Void ignored) {
  2906             List<Type> argtypes = subst(t.argtypes);
  2907             Type restype = subst(t.restype);
  2908             List<Type> thrown = subst(t.thrown);
  2909             if (argtypes == t.argtypes &&
  2910                 restype == t.restype &&
  2911                 thrown == t.thrown)
  2912                 return t;
  2913             else
  2914                 return new MethodType(argtypes, restype, thrown, t.tsym);
  2917         @Override
  2918         public Type visitTypeVar(TypeVar t, Void ignored) {
  2919             for (List<Type> from = this.from, to = this.to;
  2920                  from.nonEmpty();
  2921                  from = from.tail, to = to.tail) {
  2922                 if (t == from.head) {
  2923                     return to.head.withTypeVar(t);
  2926             return t;
  2929         @Override
  2930         public Type visitClassType(ClassType t, Void ignored) {
  2931             if (!t.isCompound()) {
  2932                 List<Type> typarams = t.getTypeArguments();
  2933                 List<Type> typarams1 = subst(typarams);
  2934                 Type outer = t.getEnclosingType();
  2935                 Type outer1 = subst(outer);
  2936                 if (typarams1 == typarams && outer1 == outer)
  2937                     return t;
  2938                 else
  2939                     return new ClassType(outer1, typarams1, t.tsym);
  2940             } else {
  2941                 Type st = subst(supertype(t));
  2942                 List<Type> is = upperBounds(subst(interfaces(t)));
  2943                 if (st == supertype(t) && is == interfaces(t))
  2944                     return t;
  2945                 else
  2946                     return makeCompoundType(is.prepend(st));
  2950         @Override
  2951         public Type visitWildcardType(WildcardType t, Void ignored) {
  2952             Type bound = t.type;
  2953             if (t.kind != BoundKind.UNBOUND)
  2954                 bound = subst(bound);
  2955             if (bound == t.type) {
  2956                 return t;
  2957             } else {
  2958                 if (t.isExtendsBound() && bound.isExtendsBound())
  2959                     bound = upperBound(bound);
  2960                 return new WildcardType(bound, t.kind, syms.boundClass, t.bound);
  2964         @Override
  2965         public Type visitArrayType(ArrayType t, Void ignored) {
  2966             Type elemtype = subst(t.elemtype);
  2967             if (elemtype == t.elemtype)
  2968                 return t;
  2969             else
  2970                 return new ArrayType(elemtype, t.tsym);
  2973         @Override
  2974         public Type visitForAll(ForAll t, Void ignored) {
  2975             if (Type.containsAny(to, t.tvars)) {
  2976                 //perform alpha-renaming of free-variables in 't'
  2977                 //if 'to' types contain variables that are free in 't'
  2978                 List<Type> freevars = newInstances(t.tvars);
  2979                 t = new ForAll(freevars,
  2980                         Types.this.subst(t.qtype, t.tvars, freevars));
  2982             List<Type> tvars1 = substBounds(t.tvars, from, to);
  2983             Type qtype1 = subst(t.qtype);
  2984             if (tvars1 == t.tvars && qtype1 == t.qtype) {
  2985                 return t;
  2986             } else if (tvars1 == t.tvars) {
  2987                 return new ForAll(tvars1, qtype1);
  2988             } else {
  2989                 return new ForAll(tvars1, Types.this.subst(qtype1, t.tvars, tvars1));
  2993         @Override
  2994         public Type visitErrorType(ErrorType t, Void ignored) {
  2995             return t;
  2999     public List<Type> substBounds(List<Type> tvars,
  3000                                   List<Type> from,
  3001                                   List<Type> to) {
  3002         if (tvars.isEmpty())
  3003             return tvars;
  3004         ListBuffer<Type> newBoundsBuf = lb();
  3005         boolean changed = false;
  3006         // calculate new bounds
  3007         for (Type t : tvars) {
  3008             TypeVar tv = (TypeVar) t;
  3009             Type bound = subst(tv.bound, from, to);
  3010             if (bound != tv.bound)
  3011                 changed = true;
  3012             newBoundsBuf.append(bound);
  3014         if (!changed)
  3015             return tvars;
  3016         ListBuffer<Type> newTvars = lb();
  3017         // create new type variables without bounds
  3018         for (Type t : tvars) {
  3019             newTvars.append(new TypeVar(t.tsym, null, syms.botType));
  3021         // the new bounds should use the new type variables in place
  3022         // of the old
  3023         List<Type> newBounds = newBoundsBuf.toList();
  3024         from = tvars;
  3025         to = newTvars.toList();
  3026         for (; !newBounds.isEmpty(); newBounds = newBounds.tail) {
  3027             newBounds.head = subst(newBounds.head, from, to);
  3029         newBounds = newBoundsBuf.toList();
  3030         // set the bounds of new type variables to the new bounds
  3031         for (Type t : newTvars.toList()) {
  3032             TypeVar tv = (TypeVar) t;
  3033             tv.bound = newBounds.head;
  3034             newBounds = newBounds.tail;
  3036         return newTvars.toList();
  3039     public TypeVar substBound(TypeVar t, List<Type> from, List<Type> to) {
  3040         Type bound1 = subst(t.bound, from, to);
  3041         if (bound1 == t.bound)
  3042             return t;
  3043         else {
  3044             // create new type variable without bounds
  3045             TypeVar tv = new TypeVar(t.tsym, null, syms.botType);
  3046             // the new bound should use the new type variable in place
  3047             // of the old
  3048             tv.bound = subst(bound1, List.<Type>of(t), List.<Type>of(tv));
  3049             return tv;
  3052     // </editor-fold>
  3054     // <editor-fold defaultstate="collapsed" desc="hasSameBounds">
  3055     /**
  3056      * Does t have the same bounds for quantified variables as s?
  3057      */
  3058     boolean hasSameBounds(ForAll t, ForAll s) {
  3059         List<Type> l1 = t.tvars;
  3060         List<Type> l2 = s.tvars;
  3061         while (l1.nonEmpty() && l2.nonEmpty() &&
  3062                isSameType(l1.head.getUpperBound(),
  3063                           subst(l2.head.getUpperBound(),
  3064                                 s.tvars,
  3065                                 t.tvars))) {
  3066             l1 = l1.tail;
  3067             l2 = l2.tail;
  3069         return l1.isEmpty() && l2.isEmpty();
  3071     // </editor-fold>
  3073     // <editor-fold defaultstate="collapsed" desc="newInstances">
  3074     /** Create new vector of type variables from list of variables
  3075      *  changing all recursive bounds from old to new list.
  3076      */
  3077     public List<Type> newInstances(List<Type> tvars) {
  3078         List<Type> tvars1 = Type.map(tvars, newInstanceFun);
  3079         for (List<Type> l = tvars1; l.nonEmpty(); l = l.tail) {
  3080             TypeVar tv = (TypeVar) l.head;
  3081             tv.bound = subst(tv.bound, tvars, tvars1);
  3083         return tvars1;
  3085     private static final Mapping newInstanceFun = new Mapping("newInstanceFun") {
  3086             public Type apply(Type t) { return new TypeVar(t.tsym, t.getUpperBound(), t.getLowerBound()); }
  3087         };
  3088     // </editor-fold>
  3090     public Type createMethodTypeWithParameters(Type original, List<Type> newParams) {
  3091         return original.accept(methodWithParameters, newParams);
  3093     // where
  3094         private final MapVisitor<List<Type>> methodWithParameters = new MapVisitor<List<Type>>() {
  3095             public Type visitType(Type t, List<Type> newParams) {
  3096                 throw new IllegalArgumentException("Not a method type: " + t);
  3098             public Type visitMethodType(MethodType t, List<Type> newParams) {
  3099                 return new MethodType(newParams, t.restype, t.thrown, t.tsym);
  3101             public Type visitForAll(ForAll t, List<Type> newParams) {
  3102                 return new ForAll(t.tvars, t.qtype.accept(this, newParams));
  3104         };
  3106     public Type createMethodTypeWithThrown(Type original, List<Type> newThrown) {
  3107         return original.accept(methodWithThrown, newThrown);
  3109     // where
  3110         private final MapVisitor<List<Type>> methodWithThrown = new MapVisitor<List<Type>>() {
  3111             public Type visitType(Type t, List<Type> newThrown) {
  3112                 throw new IllegalArgumentException("Not a method type: " + t);
  3114             public Type visitMethodType(MethodType t, List<Type> newThrown) {
  3115                 return new MethodType(t.argtypes, t.restype, newThrown, t.tsym);
  3117             public Type visitForAll(ForAll t, List<Type> newThrown) {
  3118                 return new ForAll(t.tvars, t.qtype.accept(this, newThrown));
  3120         };
  3122     public Type createMethodTypeWithReturn(Type original, Type newReturn) {
  3123         return original.accept(methodWithReturn, newReturn);
  3125     // where
  3126         private final MapVisitor<Type> methodWithReturn = new MapVisitor<Type>() {
  3127             public Type visitType(Type t, Type newReturn) {
  3128                 throw new IllegalArgumentException("Not a method type: " + t);
  3130             public Type visitMethodType(MethodType t, Type newReturn) {
  3131                 return new MethodType(t.argtypes, newReturn, t.thrown, t.tsym);
  3133             public Type visitForAll(ForAll t, Type newReturn) {
  3134                 return new ForAll(t.tvars, t.qtype.accept(this, newReturn));
  3136         };
  3138     // <editor-fold defaultstate="collapsed" desc="createErrorType">
  3139     public Type createErrorType(Type originalType) {
  3140         return new ErrorType(originalType, syms.errSymbol);
  3143     public Type createErrorType(ClassSymbol c, Type originalType) {
  3144         return new ErrorType(c, originalType);
  3147     public Type createErrorType(Name name, TypeSymbol container, Type originalType) {
  3148         return new ErrorType(name, container, originalType);
  3150     // </editor-fold>
  3152     // <editor-fold defaultstate="collapsed" desc="rank">
  3153     /**
  3154      * The rank of a class is the length of the longest path between
  3155      * the class and java.lang.Object in the class inheritance
  3156      * graph. Undefined for all but reference types.
  3157      */
  3158     public int rank(Type t) {
  3159         t = t.unannotatedType();
  3160         switch(t.getTag()) {
  3161         case CLASS: {
  3162             ClassType cls = (ClassType)t;
  3163             if (cls.rank_field < 0) {
  3164                 Name fullname = cls.tsym.getQualifiedName();
  3165                 if (fullname == names.java_lang_Object)
  3166                     cls.rank_field = 0;
  3167                 else {
  3168                     int r = rank(supertype(cls));
  3169                     for (List<Type> l = interfaces(cls);
  3170                          l.nonEmpty();
  3171                          l = l.tail) {
  3172                         if (rank(l.head) > r)
  3173                             r = rank(l.head);
  3175                     cls.rank_field = r + 1;
  3178             return cls.rank_field;
  3180         case TYPEVAR: {
  3181             TypeVar tvar = (TypeVar)t;
  3182             if (tvar.rank_field < 0) {
  3183                 int r = rank(supertype(tvar));
  3184                 for (List<Type> l = interfaces(tvar);
  3185                      l.nonEmpty();
  3186                      l = l.tail) {
  3187                     if (rank(l.head) > r) r = rank(l.head);
  3189                 tvar.rank_field = r + 1;
  3191             return tvar.rank_field;
  3193         case ERROR:
  3194             return 0;
  3195         default:
  3196             throw new AssertionError();
  3199     // </editor-fold>
  3201     /**
  3202      * Helper method for generating a string representation of a given type
  3203      * accordingly to a given locale
  3204      */
  3205     public String toString(Type t, Locale locale) {
  3206         return Printer.createStandardPrinter(messages).visit(t, locale);
  3209     /**
  3210      * Helper method for generating a string representation of a given type
  3211      * accordingly to a given locale
  3212      */
  3213     public String toString(Symbol t, Locale locale) {
  3214         return Printer.createStandardPrinter(messages).visit(t, locale);
  3217     // <editor-fold defaultstate="collapsed" desc="toString">
  3218     /**
  3219      * This toString is slightly more descriptive than the one on Type.
  3221      * @deprecated Types.toString(Type t, Locale l) provides better support
  3222      * for localization
  3223      */
  3224     @Deprecated
  3225     public String toString(Type t) {
  3226         if (t.hasTag(FORALL)) {
  3227             ForAll forAll = (ForAll)t;
  3228             return typaramsString(forAll.tvars) + forAll.qtype;
  3230         return "" + t;
  3232     // where
  3233         private String typaramsString(List<Type> tvars) {
  3234             StringBuilder s = new StringBuilder();
  3235             s.append('<');
  3236             boolean first = true;
  3237             for (Type t : tvars) {
  3238                 if (!first) s.append(", ");
  3239                 first = false;
  3240                 appendTyparamString(((TypeVar)t.unannotatedType()), s);
  3242             s.append('>');
  3243             return s.toString();
  3245         private void appendTyparamString(TypeVar t, StringBuilder buf) {
  3246             buf.append(t);
  3247             if (t.bound == null ||
  3248                 t.bound.tsym.getQualifiedName() == names.java_lang_Object)
  3249                 return;
  3250             buf.append(" extends "); // Java syntax; no need for i18n
  3251             Type bound = t.bound;
  3252             if (!bound.isCompound()) {
  3253                 buf.append(bound);
  3254             } else if ((erasure(t).tsym.flags() & INTERFACE) == 0) {
  3255                 buf.append(supertype(t));
  3256                 for (Type intf : interfaces(t)) {
  3257                     buf.append('&');
  3258                     buf.append(intf);
  3260             } else {
  3261                 // No superclass was given in bounds.
  3262                 // In this case, supertype is Object, erasure is first interface.
  3263                 boolean first = true;
  3264                 for (Type intf : interfaces(t)) {
  3265                     if (!first) buf.append('&');
  3266                     first = false;
  3267                     buf.append(intf);
  3271     // </editor-fold>
  3273     // <editor-fold defaultstate="collapsed" desc="Determining least upper bounds of types">
  3274     /**
  3275      * A cache for closures.
  3277      * <p>A closure is a list of all the supertypes and interfaces of
  3278      * a class or interface type, ordered by ClassSymbol.precedes
  3279      * (that is, subclasses come first, arbitrary but fixed
  3280      * otherwise).
  3281      */
  3282     private Map<Type,List<Type>> closureCache = new HashMap<Type,List<Type>>();
  3284     /**
  3285      * Returns the closure of a class or interface type.
  3286      */
  3287     public List<Type> closure(Type t) {
  3288         List<Type> cl = closureCache.get(t);
  3289         if (cl == null) {
  3290             Type st = supertype(t);
  3291             if (!t.isCompound()) {
  3292                 if (st.hasTag(CLASS)) {
  3293                     cl = insert(closure(st), t);
  3294                 } else if (st.hasTag(TYPEVAR)) {
  3295                     cl = closure(st).prepend(t);
  3296                 } else {
  3297                     cl = List.of(t);
  3299             } else {
  3300                 cl = closure(supertype(t));
  3302             for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail)
  3303                 cl = union(cl, closure(l.head));
  3304             closureCache.put(t, cl);
  3306         return cl;
  3309     /**
  3310      * Insert a type in a closure
  3311      */
  3312     public List<Type> insert(List<Type> cl, Type t) {
  3313         if (cl.isEmpty() || t.tsym.precedes(cl.head.tsym, this)) {
  3314             return cl.prepend(t);
  3315         } else if (cl.head.tsym.precedes(t.tsym, this)) {
  3316             return insert(cl.tail, t).prepend(cl.head);
  3317         } else {
  3318             return cl;
  3322     /**
  3323      * Form the union of two closures
  3324      */
  3325     public List<Type> union(List<Type> cl1, List<Type> cl2) {
  3326         if (cl1.isEmpty()) {
  3327             return cl2;
  3328         } else if (cl2.isEmpty()) {
  3329             return cl1;
  3330         } else if (cl1.head.tsym.precedes(cl2.head.tsym, this)) {
  3331             return union(cl1.tail, cl2).prepend(cl1.head);
  3332         } else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) {
  3333             return union(cl1, cl2.tail).prepend(cl2.head);
  3334         } else {
  3335             return union(cl1.tail, cl2.tail).prepend(cl1.head);
  3339     /**
  3340      * Intersect two closures
  3341      */
  3342     public List<Type> intersect(List<Type> cl1, List<Type> cl2) {
  3343         if (cl1 == cl2)
  3344             return cl1;
  3345         if (cl1.isEmpty() || cl2.isEmpty())
  3346             return List.nil();
  3347         if (cl1.head.tsym.precedes(cl2.head.tsym, this))
  3348             return intersect(cl1.tail, cl2);
  3349         if (cl2.head.tsym.precedes(cl1.head.tsym, this))
  3350             return intersect(cl1, cl2.tail);
  3351         if (isSameType(cl1.head, cl2.head))
  3352             return intersect(cl1.tail, cl2.tail).prepend(cl1.head);
  3353         if (cl1.head.tsym == cl2.head.tsym &&
  3354             cl1.head.hasTag(CLASS) && cl2.head.hasTag(CLASS)) {
  3355             if (cl1.head.isParameterized() && cl2.head.isParameterized()) {
  3356                 Type merge = merge(cl1.head,cl2.head);
  3357                 return intersect(cl1.tail, cl2.tail).prepend(merge);
  3359             if (cl1.head.isRaw() || cl2.head.isRaw())
  3360                 return intersect(cl1.tail, cl2.tail).prepend(erasure(cl1.head));
  3362         return intersect(cl1.tail, cl2.tail);
  3364     // where
  3365         class TypePair {
  3366             final Type t1;
  3367             final Type t2;
  3368             TypePair(Type t1, Type t2) {
  3369                 this.t1 = t1;
  3370                 this.t2 = t2;
  3372             @Override
  3373             public int hashCode() {
  3374                 return 127 * Types.this.hashCode(t1) + Types.this.hashCode(t2);
  3376             @Override
  3377             public boolean equals(Object obj) {
  3378                 if (!(obj instanceof TypePair))
  3379                     return false;
  3380                 TypePair typePair = (TypePair)obj;
  3381                 return isSameType(t1, typePair.t1)
  3382                     && isSameType(t2, typePair.t2);
  3385         Set<TypePair> mergeCache = new HashSet<TypePair>();
  3386         private Type merge(Type c1, Type c2) {
  3387             ClassType class1 = (ClassType) c1;
  3388             List<Type> act1 = class1.getTypeArguments();
  3389             ClassType class2 = (ClassType) c2;
  3390             List<Type> act2 = class2.getTypeArguments();
  3391             ListBuffer<Type> merged = new ListBuffer<Type>();
  3392             List<Type> typarams = class1.tsym.type.getTypeArguments();
  3394             while (act1.nonEmpty() && act2.nonEmpty() && typarams.nonEmpty()) {
  3395                 if (containsType(act1.head, act2.head)) {
  3396                     merged.append(act1.head);
  3397                 } else if (containsType(act2.head, act1.head)) {
  3398                     merged.append(act2.head);
  3399                 } else {
  3400                     TypePair pair = new TypePair(c1, c2);
  3401                     Type m;
  3402                     if (mergeCache.add(pair)) {
  3403                         m = new WildcardType(lub(upperBound(act1.head),
  3404                                                  upperBound(act2.head)),
  3405                                              BoundKind.EXTENDS,
  3406                                              syms.boundClass);
  3407                         mergeCache.remove(pair);
  3408                     } else {
  3409                         m = new WildcardType(syms.objectType,
  3410                                              BoundKind.UNBOUND,
  3411                                              syms.boundClass);
  3413                     merged.append(m.withTypeVar(typarams.head));
  3415                 act1 = act1.tail;
  3416                 act2 = act2.tail;
  3417                 typarams = typarams.tail;
  3419             Assert.check(act1.isEmpty() && act2.isEmpty() && typarams.isEmpty());
  3420             return new ClassType(class1.getEnclosingType(), merged.toList(), class1.tsym);
  3423     /**
  3424      * Return the minimum type of a closure, a compound type if no
  3425      * unique minimum exists.
  3426      */
  3427     private Type compoundMin(List<Type> cl) {
  3428         if (cl.isEmpty()) return syms.objectType;
  3429         List<Type> compound = closureMin(cl);
  3430         if (compound.isEmpty())
  3431             return null;
  3432         else if (compound.tail.isEmpty())
  3433             return compound.head;
  3434         else
  3435             return makeCompoundType(compound);
  3438     /**
  3439      * Return the minimum types of a closure, suitable for computing
  3440      * compoundMin or glb.
  3441      */
  3442     private List<Type> closureMin(List<Type> cl) {
  3443         ListBuffer<Type> classes = lb();
  3444         ListBuffer<Type> interfaces = lb();
  3445         while (!cl.isEmpty()) {
  3446             Type current = cl.head;
  3447             if (current.isInterface())
  3448                 interfaces.append(current);
  3449             else
  3450                 classes.append(current);
  3451             ListBuffer<Type> candidates = lb();
  3452             for (Type t : cl.tail) {
  3453                 if (!isSubtypeNoCapture(current, t))
  3454                     candidates.append(t);
  3456             cl = candidates.toList();
  3458         return classes.appendList(interfaces).toList();
  3461     /**
  3462      * Return the least upper bound of pair of types.  if the lub does
  3463      * not exist return null.
  3464      */
  3465     public Type lub(Type t1, Type t2) {
  3466         return lub(List.of(t1, t2));
  3469     /**
  3470      * Return the least upper bound (lub) of set of types.  If the lub
  3471      * does not exist return the type of null (bottom).
  3472      */
  3473     public Type lub(List<Type> ts) {
  3474         final int ARRAY_BOUND = 1;
  3475         final int CLASS_BOUND = 2;
  3476         int boundkind = 0;
  3477         for (Type t : ts) {
  3478             switch (t.getTag()) {
  3479             case CLASS:
  3480                 boundkind |= CLASS_BOUND;
  3481                 break;
  3482             case ARRAY:
  3483                 boundkind |= ARRAY_BOUND;
  3484                 break;
  3485             case  TYPEVAR:
  3486                 do {
  3487                     t = t.getUpperBound();
  3488                 } while (t.hasTag(TYPEVAR));
  3489                 if (t.hasTag(ARRAY)) {
  3490                     boundkind |= ARRAY_BOUND;
  3491                 } else {
  3492                     boundkind |= CLASS_BOUND;
  3494                 break;
  3495             default:
  3496                 if (t.isPrimitive())
  3497                     return syms.errType;
  3500         switch (boundkind) {
  3501         case 0:
  3502             return syms.botType;
  3504         case ARRAY_BOUND:
  3505             // calculate lub(A[], B[])
  3506             List<Type> elements = Type.map(ts, elemTypeFun);
  3507             for (Type t : elements) {
  3508                 if (t.isPrimitive()) {
  3509                     // if a primitive type is found, then return
  3510                     // arraySuperType unless all the types are the
  3511                     // same
  3512                     Type first = ts.head;
  3513                     for (Type s : ts.tail) {
  3514                         if (!isSameType(first, s)) {
  3515                              // lub(int[], B[]) is Cloneable & Serializable
  3516                             return arraySuperType();
  3519                     // all the array types are the same, return one
  3520                     // lub(int[], int[]) is int[]
  3521                     return first;
  3524             // lub(A[], B[]) is lub(A, B)[]
  3525             return new ArrayType(lub(elements), syms.arrayClass);
  3527         case CLASS_BOUND:
  3528             // calculate lub(A, B)
  3529             while (!ts.head.hasTag(CLASS) && !ts.head.hasTag(TYPEVAR)) {
  3530                 ts = ts.tail;
  3532             Assert.check(!ts.isEmpty());
  3533             //step 1 - compute erased candidate set (EC)
  3534             List<Type> cl = erasedSupertypes(ts.head);
  3535             for (Type t : ts.tail) {
  3536                 if (t.hasTag(CLASS) || t.hasTag(TYPEVAR))
  3537                     cl = intersect(cl, erasedSupertypes(t));
  3539             //step 2 - compute minimal erased candidate set (MEC)
  3540             List<Type> mec = closureMin(cl);
  3541             //step 3 - for each element G in MEC, compute lci(Inv(G))
  3542             List<Type> candidates = List.nil();
  3543             for (Type erasedSupertype : mec) {
  3544                 List<Type> lci = List.of(asSuper(ts.head, erasedSupertype.tsym));
  3545                 for (Type t : ts) {
  3546                     lci = intersect(lci, List.of(asSuper(t, erasedSupertype.tsym)));
  3548                 candidates = candidates.appendList(lci);
  3550             //step 4 - let MEC be { G1, G2 ... Gn }, then we have that
  3551             //lub = lci(Inv(G1)) & lci(Inv(G2)) & ... & lci(Inv(Gn))
  3552             return compoundMin(candidates);
  3554         default:
  3555             // calculate lub(A, B[])
  3556             List<Type> classes = List.of(arraySuperType());
  3557             for (Type t : ts) {
  3558                 if (!t.hasTag(ARRAY)) // Filter out any arrays
  3559                     classes = classes.prepend(t);
  3561             // lub(A, B[]) is lub(A, arraySuperType)
  3562             return lub(classes);
  3565     // where
  3566         List<Type> erasedSupertypes(Type t) {
  3567             ListBuffer<Type> buf = lb();
  3568             for (Type sup : closure(t)) {
  3569                 if (sup.hasTag(TYPEVAR)) {
  3570                     buf.append(sup);
  3571                 } else {
  3572                     buf.append(erasure(sup));
  3575             return buf.toList();
  3578         private Type arraySuperType = null;
  3579         private Type arraySuperType() {
  3580             // initialized lazily to avoid problems during compiler startup
  3581             if (arraySuperType == null) {
  3582                 synchronized (this) {
  3583                     if (arraySuperType == null) {
  3584                         // JLS 10.8: all arrays implement Cloneable and Serializable.
  3585                         arraySuperType = makeCompoundType(List.of(syms.serializableType,
  3586                                                                   syms.cloneableType), true);
  3590             return arraySuperType;
  3592     // </editor-fold>
  3594     // <editor-fold defaultstate="collapsed" desc="Greatest lower bound">
  3595     public Type glb(List<Type> ts) {
  3596         Type t1 = ts.head;
  3597         for (Type t2 : ts.tail) {
  3598             if (t1.isErroneous())
  3599                 return t1;
  3600             t1 = glb(t1, t2);
  3602         return t1;
  3604     //where
  3605     public Type glb(Type t, Type s) {
  3606         if (s == null)
  3607             return t;
  3608         else if (t.isPrimitive() || s.isPrimitive())
  3609             return syms.errType;
  3610         else if (isSubtypeNoCapture(t, s))
  3611             return t;
  3612         else if (isSubtypeNoCapture(s, t))
  3613             return s;
  3615         List<Type> closure = union(closure(t), closure(s));
  3616         List<Type> bounds = closureMin(closure);
  3618         if (bounds.isEmpty()) {             // length == 0
  3619             return syms.objectType;
  3620         } else if (bounds.tail.isEmpty()) { // length == 1
  3621             return bounds.head;
  3622         } else {                            // length > 1
  3623             int classCount = 0;
  3624             for (Type bound : bounds)
  3625                 if (!bound.isInterface())
  3626                     classCount++;
  3627             if (classCount > 1)
  3628                 return createErrorType(t);
  3630         return makeCompoundType(bounds);
  3632     // </editor-fold>
  3634     // <editor-fold defaultstate="collapsed" desc="hashCode">
  3635     /**
  3636      * Compute a hash code on a type.
  3637      */
  3638     public int hashCode(Type t) {
  3639         return hashCode.visit(t);
  3641     // where
  3642         private static final UnaryVisitor<Integer> hashCode = new UnaryVisitor<Integer>() {
  3644             public Integer visitType(Type t, Void ignored) {
  3645                 return t.getTag().ordinal();
  3648             @Override
  3649             public Integer visitClassType(ClassType t, Void ignored) {
  3650                 int result = visit(t.getEnclosingType());
  3651                 result *= 127;
  3652                 result += t.tsym.flatName().hashCode();
  3653                 for (Type s : t.getTypeArguments()) {
  3654                     result *= 127;
  3655                     result += visit(s);
  3657                 return result;
  3660             @Override
  3661             public Integer visitMethodType(MethodType t, Void ignored) {
  3662                 int h = METHOD.ordinal();
  3663                 for (List<Type> thisargs = t.argtypes;
  3664                      thisargs.tail != null;
  3665                      thisargs = thisargs.tail)
  3666                     h = (h << 5) + visit(thisargs.head);
  3667                 return (h << 5) + visit(t.restype);
  3670             @Override
  3671             public Integer visitWildcardType(WildcardType t, Void ignored) {
  3672                 int result = t.kind.hashCode();
  3673                 if (t.type != null) {
  3674                     result *= 127;
  3675                     result += visit(t.type);
  3677                 return result;
  3680             @Override
  3681             public Integer visitArrayType(ArrayType t, Void ignored) {
  3682                 return visit(t.elemtype) + 12;
  3685             @Override
  3686             public Integer visitTypeVar(TypeVar t, Void ignored) {
  3687                 return System.identityHashCode(t.tsym);
  3690             @Override
  3691             public Integer visitUndetVar(UndetVar t, Void ignored) {
  3692                 return System.identityHashCode(t);
  3695             @Override
  3696             public Integer visitErrorType(ErrorType t, Void ignored) {
  3697                 return 0;
  3699         };
  3700     // </editor-fold>
  3702     // <editor-fold defaultstate="collapsed" desc="Return-Type-Substitutable">
  3703     /**
  3704      * Does t have a result that is a subtype of the result type of s,
  3705      * suitable for covariant returns?  It is assumed that both types
  3706      * are (possibly polymorphic) method types.  Monomorphic method
  3707      * types are handled in the obvious way.  Polymorphic method types
  3708      * require renaming all type variables of one to corresponding
  3709      * type variables in the other, where correspondence is by
  3710      * position in the type parameter list. */
  3711     public boolean resultSubtype(Type t, Type s, Warner warner) {
  3712         List<Type> tvars = t.getTypeArguments();
  3713         List<Type> svars = s.getTypeArguments();
  3714         Type tres = t.getReturnType();
  3715         Type sres = subst(s.getReturnType(), svars, tvars);
  3716         return covariantReturnType(tres, sres, warner);
  3719     /**
  3720      * Return-Type-Substitutable.
  3721      * @jls section 8.4.5
  3722      */
  3723     public boolean returnTypeSubstitutable(Type r1, Type r2) {
  3724         if (hasSameArgs(r1, r2))
  3725             return resultSubtype(r1, r2, noWarnings);
  3726         else
  3727             return covariantReturnType(r1.getReturnType(),
  3728                                        erasure(r2.getReturnType()),
  3729                                        noWarnings);
  3732     public boolean returnTypeSubstitutable(Type r1,
  3733                                            Type r2, Type r2res,
  3734                                            Warner warner) {
  3735         if (isSameType(r1.getReturnType(), r2res))
  3736             return true;
  3737         if (r1.getReturnType().isPrimitive() || r2res.isPrimitive())
  3738             return false;
  3740         if (hasSameArgs(r1, r2))
  3741             return covariantReturnType(r1.getReturnType(), r2res, warner);
  3742         if (!allowCovariantReturns)
  3743             return false;
  3744         if (isSubtypeUnchecked(r1.getReturnType(), r2res, warner))
  3745             return true;
  3746         if (!isSubtype(r1.getReturnType(), erasure(r2res)))
  3747             return false;
  3748         warner.warn(LintCategory.UNCHECKED);
  3749         return true;
  3752     /**
  3753      * Is t an appropriate return type in an overrider for a
  3754      * method that returns s?
  3755      */
  3756     public boolean covariantReturnType(Type t, Type s, Warner warner) {
  3757         return
  3758             isSameType(t, s) ||
  3759             allowCovariantReturns &&
  3760             !t.isPrimitive() &&
  3761             !s.isPrimitive() &&
  3762             isAssignable(t, s, warner);
  3764     // </editor-fold>
  3766     // <editor-fold defaultstate="collapsed" desc="Box/unbox support">
  3767     /**
  3768      * Return the class that boxes the given primitive.
  3769      */
  3770     public ClassSymbol boxedClass(Type t) {
  3771         return reader.enterClass(syms.boxedName[t.getTag().ordinal()]);
  3774     /**
  3775      * Return the boxed type if 't' is primitive, otherwise return 't' itself.
  3776      */
  3777     public Type boxedTypeOrType(Type t) {
  3778         return t.isPrimitive() ?
  3779             boxedClass(t).type :
  3780             t;
  3783     /**
  3784      * Return the primitive type corresponding to a boxed type.
  3785      */
  3786     public Type unboxedType(Type t) {
  3787         if (allowBoxing) {
  3788             for (int i=0; i<syms.boxedName.length; i++) {
  3789                 Name box = syms.boxedName[i];
  3790                 if (box != null &&
  3791                     asSuper(t, reader.enterClass(box)) != null)
  3792                     return syms.typeOfTag[i];
  3795         return Type.noType;
  3798     /**
  3799      * Return the unboxed type if 't' is a boxed class, otherwise return 't' itself.
  3800      */
  3801     public Type unboxedTypeOrType(Type t) {
  3802         Type unboxedType = unboxedType(t);
  3803         return unboxedType.hasTag(NONE) ? t : unboxedType;
  3805     // </editor-fold>
  3807     // <editor-fold defaultstate="collapsed" desc="Capture conversion">
  3808     /*
  3809      * JLS 5.1.10 Capture Conversion:
  3811      * Let G name a generic type declaration with n formal type
  3812      * parameters A1 ... An with corresponding bounds U1 ... Un. There
  3813      * exists a capture conversion from G<T1 ... Tn> to G<S1 ... Sn>,
  3814      * where, for 1 <= i <= n:
  3816      * + If Ti is a wildcard type argument (4.5.1) of the form ? then
  3817      *   Si is a fresh type variable whose upper bound is
  3818      *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is the null
  3819      *   type.
  3821      * + If Ti is a wildcard type argument of the form ? extends Bi,
  3822      *   then Si is a fresh type variable whose upper bound is
  3823      *   glb(Bi, Ui[A1 := S1, ..., An := Sn]) and whose lower bound is
  3824      *   the null type, where glb(V1,... ,Vm) is V1 & ... & Vm. It is
  3825      *   a compile-time error if for any two classes (not interfaces)
  3826      *   Vi and Vj,Vi is not a subclass of Vj or vice versa.
  3828      * + If Ti is a wildcard type argument of the form ? super Bi,
  3829      *   then Si is a fresh type variable whose upper bound is
  3830      *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is Bi.
  3832      * + Otherwise, Si = Ti.
  3834      * Capture conversion on any type other than a parameterized type
  3835      * (4.5) acts as an identity conversion (5.1.1). Capture
  3836      * conversions never require a special action at run time and
  3837      * therefore never throw an exception at run time.
  3839      * Capture conversion is not applied recursively.
  3840      */
  3841     /**
  3842      * Capture conversion as specified by the JLS.
  3843      */
  3845     public List<Type> capture(List<Type> ts) {
  3846         List<Type> buf = List.nil();
  3847         for (Type t : ts) {
  3848             buf = buf.prepend(capture(t));
  3850         return buf.reverse();
  3852     public Type capture(Type t) {
  3853         if (!t.hasTag(CLASS))
  3854             return t;
  3855         if (t.getEnclosingType() != Type.noType) {
  3856             Type capturedEncl = capture(t.getEnclosingType());
  3857             if (capturedEncl != t.getEnclosingType()) {
  3858                 Type type1 = memberType(capturedEncl, t.tsym);
  3859                 t = subst(type1, t.tsym.type.getTypeArguments(), t.getTypeArguments());
  3862         t = t.unannotatedType();
  3863         ClassType cls = (ClassType)t;
  3864         if (cls.isRaw() || !cls.isParameterized())
  3865             return cls;
  3867         ClassType G = (ClassType)cls.asElement().asType();
  3868         List<Type> A = G.getTypeArguments();
  3869         List<Type> T = cls.getTypeArguments();
  3870         List<Type> S = freshTypeVariables(T);
  3872         List<Type> currentA = A;
  3873         List<Type> currentT = T;
  3874         List<Type> currentS = S;
  3875         boolean captured = false;
  3876         while (!currentA.isEmpty() &&
  3877                !currentT.isEmpty() &&
  3878                !currentS.isEmpty()) {
  3879             if (currentS.head != currentT.head) {
  3880                 captured = true;
  3881                 WildcardType Ti = (WildcardType)currentT.head.unannotatedType();
  3882                 Type Ui = currentA.head.getUpperBound();
  3883                 CapturedType Si = (CapturedType)currentS.head.unannotatedType();
  3884                 if (Ui == null)
  3885                     Ui = syms.objectType;
  3886                 switch (Ti.kind) {
  3887                 case UNBOUND:
  3888                     Si.bound = subst(Ui, A, S);
  3889                     Si.lower = syms.botType;
  3890                     break;
  3891                 case EXTENDS:
  3892                     Si.bound = glb(Ti.getExtendsBound(), subst(Ui, A, S));
  3893                     Si.lower = syms.botType;
  3894                     break;
  3895                 case SUPER:
  3896                     Si.bound = subst(Ui, A, S);
  3897                     Si.lower = Ti.getSuperBound();
  3898                     break;
  3900                 if (Si.bound == Si.lower)
  3901                     currentS.head = Si.bound;
  3903             currentA = currentA.tail;
  3904             currentT = currentT.tail;
  3905             currentS = currentS.tail;
  3907         if (!currentA.isEmpty() || !currentT.isEmpty() || !currentS.isEmpty())
  3908             return erasure(t); // some "rare" type involved
  3910         if (captured)
  3911             return new ClassType(cls.getEnclosingType(), S, cls.tsym);
  3912         else
  3913             return t;
  3915     // where
  3916         public List<Type> freshTypeVariables(List<Type> types) {
  3917             ListBuffer<Type> result = lb();
  3918             for (Type t : types) {
  3919                 if (t.hasTag(WILDCARD)) {
  3920                     t = t.unannotatedType();
  3921                     Type bound = ((WildcardType)t).getExtendsBound();
  3922                     if (bound == null)
  3923                         bound = syms.objectType;
  3924                     result.append(new CapturedType(capturedName,
  3925                                                    syms.noSymbol,
  3926                                                    bound,
  3927                                                    syms.botType,
  3928                                                    (WildcardType)t));
  3929                 } else {
  3930                     result.append(t);
  3933             return result.toList();
  3935     // </editor-fold>
  3937     // <editor-fold defaultstate="collapsed" desc="Internal utility methods">
  3938     private List<Type> upperBounds(List<Type> ss) {
  3939         if (ss.isEmpty()) return ss;
  3940         Type head = upperBound(ss.head);
  3941         List<Type> tail = upperBounds(ss.tail);
  3942         if (head != ss.head || tail != ss.tail)
  3943             return tail.prepend(head);
  3944         else
  3945             return ss;
  3948     private boolean sideCast(Type from, Type to, Warner warn) {
  3949         // We are casting from type $from$ to type $to$, which are
  3950         // non-final unrelated types.  This method
  3951         // tries to reject a cast by transferring type parameters
  3952         // from $to$ to $from$ by common superinterfaces.
  3953         boolean reverse = false;
  3954         Type target = to;
  3955         if ((to.tsym.flags() & INTERFACE) == 0) {
  3956             Assert.check((from.tsym.flags() & INTERFACE) != 0);
  3957             reverse = true;
  3958             to = from;
  3959             from = target;
  3961         List<Type> commonSupers = superClosure(to, erasure(from));
  3962         boolean giveWarning = commonSupers.isEmpty();
  3963         // The arguments to the supers could be unified here to
  3964         // get a more accurate analysis
  3965         while (commonSupers.nonEmpty()) {
  3966             Type t1 = asSuper(from, commonSupers.head.tsym);
  3967             Type t2 = commonSupers.head; // same as asSuper(to, commonSupers.head.tsym);
  3968             if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
  3969                 return false;
  3970             giveWarning = giveWarning || (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2));
  3971             commonSupers = commonSupers.tail;
  3973         if (giveWarning && !isReifiable(reverse ? from : to))
  3974             warn.warn(LintCategory.UNCHECKED);
  3975         if (!allowCovariantReturns)
  3976             // reject if there is a common method signature with
  3977             // incompatible return types.
  3978             chk.checkCompatibleAbstracts(warn.pos(), from, to);
  3979         return true;
  3982     private boolean sideCastFinal(Type from, Type to, Warner warn) {
  3983         // We are casting from type $from$ to type $to$, which are
  3984         // unrelated types one of which is final and the other of
  3985         // which is an interface.  This method
  3986         // tries to reject a cast by transferring type parameters
  3987         // from the final class to the interface.
  3988         boolean reverse = false;
  3989         Type target = to;
  3990         if ((to.tsym.flags() & INTERFACE) == 0) {
  3991             Assert.check((from.tsym.flags() & INTERFACE) != 0);
  3992             reverse = true;
  3993             to = from;
  3994             from = target;
  3996         Assert.check((from.tsym.flags() & FINAL) != 0);
  3997         Type t1 = asSuper(from, to.tsym);
  3998         if (t1 == null) return false;
  3999         Type t2 = to;
  4000         if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
  4001             return false;
  4002         if (!allowCovariantReturns)
  4003             // reject if there is a common method signature with
  4004             // incompatible return types.
  4005             chk.checkCompatibleAbstracts(warn.pos(), from, to);
  4006         if (!isReifiable(target) &&
  4007             (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2)))
  4008             warn.warn(LintCategory.UNCHECKED);
  4009         return true;
  4012     private boolean giveWarning(Type from, Type to) {
  4013         List<Type> bounds = to.isCompound() ?
  4014                 ((IntersectionClassType)to.unannotatedType()).getComponents() : List.of(to);
  4015         for (Type b : bounds) {
  4016             Type subFrom = asSub(from, b.tsym);
  4017             if (b.isParameterized() &&
  4018                     (!(isUnbounded(b) ||
  4019                     isSubtype(from, b) ||
  4020                     ((subFrom != null) && containsType(b.allparams(), subFrom.allparams()))))) {
  4021                 return true;
  4024         return false;
  4027     private List<Type> superClosure(Type t, Type s) {
  4028         List<Type> cl = List.nil();
  4029         for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
  4030             if (isSubtype(s, erasure(l.head))) {
  4031                 cl = insert(cl, l.head);
  4032             } else {
  4033                 cl = union(cl, superClosure(l.head, s));
  4036         return cl;
  4039     private boolean containsTypeEquivalent(Type t, Type s) {
  4040         return
  4041             isSameType(t, s) || // shortcut
  4042             containsType(t, s) && containsType(s, t);
  4045     // <editor-fold defaultstate="collapsed" desc="adapt">
  4046     /**
  4047      * Adapt a type by computing a substitution which maps a source
  4048      * type to a target type.
  4050      * @param source    the source type
  4051      * @param target    the target type
  4052      * @param from      the type variables of the computed substitution
  4053      * @param to        the types of the computed substitution.
  4054      */
  4055     public void adapt(Type source,
  4056                        Type target,
  4057                        ListBuffer<Type> from,
  4058                        ListBuffer<Type> to) throws AdaptFailure {
  4059         new Adapter(from, to).adapt(source, target);
  4062     class Adapter extends SimpleVisitor<Void, Type> {
  4064         ListBuffer<Type> from;
  4065         ListBuffer<Type> to;
  4066         Map<Symbol,Type> mapping;
  4068         Adapter(ListBuffer<Type> from, ListBuffer<Type> to) {
  4069             this.from = from;
  4070             this.to = to;
  4071             mapping = new HashMap<Symbol,Type>();
  4074         public void adapt(Type source, Type target) throws AdaptFailure {
  4075             visit(source, target);
  4076             List<Type> fromList = from.toList();
  4077             List<Type> toList = to.toList();
  4078             while (!fromList.isEmpty()) {
  4079                 Type val = mapping.get(fromList.head.tsym);
  4080                 if (toList.head != val)
  4081                     toList.head = val;
  4082                 fromList = fromList.tail;
  4083                 toList = toList.tail;
  4087         @Override
  4088         public Void visitClassType(ClassType source, Type target) throws AdaptFailure {
  4089             if (target.hasTag(CLASS))
  4090                 adaptRecursive(source.allparams(), target.allparams());
  4091             return null;
  4094         @Override
  4095         public Void visitArrayType(ArrayType source, Type target) throws AdaptFailure {
  4096             if (target.hasTag(ARRAY))
  4097                 adaptRecursive(elemtype(source), elemtype(target));
  4098             return null;
  4101         @Override
  4102         public Void visitWildcardType(WildcardType source, Type target) throws AdaptFailure {
  4103             if (source.isExtendsBound())
  4104                 adaptRecursive(upperBound(source), upperBound(target));
  4105             else if (source.isSuperBound())
  4106                 adaptRecursive(lowerBound(source), lowerBound(target));
  4107             return null;
  4110         @Override
  4111         public Void visitTypeVar(TypeVar source, Type target) throws AdaptFailure {
  4112             // Check to see if there is
  4113             // already a mapping for $source$, in which case
  4114             // the old mapping will be merged with the new
  4115             Type val = mapping.get(source.tsym);
  4116             if (val != null) {
  4117                 if (val.isSuperBound() && target.isSuperBound()) {
  4118                     val = isSubtype(lowerBound(val), lowerBound(target))
  4119                         ? target : val;
  4120                 } else if (val.isExtendsBound() && target.isExtendsBound()) {
  4121                     val = isSubtype(upperBound(val), upperBound(target))
  4122                         ? val : target;
  4123                 } else if (!isSameType(val, target)) {
  4124                     throw new AdaptFailure();
  4126             } else {
  4127                 val = target;
  4128                 from.append(source);
  4129                 to.append(target);
  4131             mapping.put(source.tsym, val);
  4132             return null;
  4135         @Override
  4136         public Void visitType(Type source, Type target) {
  4137             return null;
  4140         private Set<TypePair> cache = new HashSet<TypePair>();
  4142         private void adaptRecursive(Type source, Type target) {
  4143             TypePair pair = new TypePair(source, target);
  4144             if (cache.add(pair)) {
  4145                 try {
  4146                     visit(source, target);
  4147                 } finally {
  4148                     cache.remove(pair);
  4153         private void adaptRecursive(List<Type> source, List<Type> target) {
  4154             if (source.length() == target.length()) {
  4155                 while (source.nonEmpty()) {
  4156                     adaptRecursive(source.head, target.head);
  4157                     source = source.tail;
  4158                     target = target.tail;
  4164     public static class AdaptFailure extends RuntimeException {
  4165         static final long serialVersionUID = -7490231548272701566L;
  4168     private void adaptSelf(Type t,
  4169                            ListBuffer<Type> from,
  4170                            ListBuffer<Type> to) {
  4171         try {
  4172             //if (t.tsym.type != t)
  4173                 adapt(t.tsym.type, t, from, to);
  4174         } catch (AdaptFailure ex) {
  4175             // Adapt should never fail calculating a mapping from
  4176             // t.tsym.type to t as there can be no merge problem.
  4177             throw new AssertionError(ex);
  4180     // </editor-fold>
  4182     /**
  4183      * Rewrite all type variables (universal quantifiers) in the given
  4184      * type to wildcards (existential quantifiers).  This is used to
  4185      * determine if a cast is allowed.  For example, if high is true
  4186      * and {@code T <: Number}, then {@code List<T>} is rewritten to
  4187      * {@code List<?  extends Number>}.  Since {@code List<Integer> <:
  4188      * List<? extends Number>} a {@code List<T>} can be cast to {@code
  4189      * List<Integer>} with a warning.
  4190      * @param t a type
  4191      * @param high if true return an upper bound; otherwise a lower
  4192      * bound
  4193      * @param rewriteTypeVars only rewrite captured wildcards if false;
  4194      * otherwise rewrite all type variables
  4195      * @return the type rewritten with wildcards (existential
  4196      * quantifiers) only
  4197      */
  4198     private Type rewriteQuantifiers(Type t, boolean high, boolean rewriteTypeVars) {
  4199         return new Rewriter(high, rewriteTypeVars).visit(t);
  4202     class Rewriter extends UnaryVisitor<Type> {
  4204         boolean high;
  4205         boolean rewriteTypeVars;
  4207         Rewriter(boolean high, boolean rewriteTypeVars) {
  4208             this.high = high;
  4209             this.rewriteTypeVars = rewriteTypeVars;
  4212         @Override
  4213         public Type visitClassType(ClassType t, Void s) {
  4214             ListBuffer<Type> rewritten = new ListBuffer<Type>();
  4215             boolean changed = false;
  4216             for (Type arg : t.allparams()) {
  4217                 Type bound = visit(arg);
  4218                 if (arg != bound) {
  4219                     changed = true;
  4221                 rewritten.append(bound);
  4223             if (changed)
  4224                 return subst(t.tsym.type,
  4225                         t.tsym.type.allparams(),
  4226                         rewritten.toList());
  4227             else
  4228                 return t;
  4231         public Type visitType(Type t, Void s) {
  4232             return high ? upperBound(t) : lowerBound(t);
  4235         @Override
  4236         public Type visitCapturedType(CapturedType t, Void s) {
  4237             Type w_bound = t.wildcard.type;
  4238             Type bound = w_bound.contains(t) ?
  4239                         erasure(w_bound) :
  4240                         visit(w_bound);
  4241             return rewriteAsWildcardType(visit(bound), t.wildcard.bound, t.wildcard.kind);
  4244         @Override
  4245         public Type visitTypeVar(TypeVar t, Void s) {
  4246             if (rewriteTypeVars) {
  4247                 Type bound = t.bound.contains(t) ?
  4248                         erasure(t.bound) :
  4249                         visit(t.bound);
  4250                 return rewriteAsWildcardType(bound, t, EXTENDS);
  4251             } else {
  4252                 return t;
  4256         @Override
  4257         public Type visitWildcardType(WildcardType t, Void s) {
  4258             Type bound2 = visit(t.type);
  4259             return t.type == bound2 ? t : rewriteAsWildcardType(bound2, t.bound, t.kind);
  4262         private Type rewriteAsWildcardType(Type bound, TypeVar formal, BoundKind bk) {
  4263             switch (bk) {
  4264                case EXTENDS: return high ?
  4265                        makeExtendsWildcard(B(bound), formal) :
  4266                        makeExtendsWildcard(syms.objectType, formal);
  4267                case SUPER: return high ?
  4268                        makeSuperWildcard(syms.botType, formal) :
  4269                        makeSuperWildcard(B(bound), formal);
  4270                case UNBOUND: return makeExtendsWildcard(syms.objectType, formal);
  4271                default:
  4272                    Assert.error("Invalid bound kind " + bk);
  4273                    return null;
  4277         Type B(Type t) {
  4278             while (t.hasTag(WILDCARD)) {
  4279                 WildcardType w = (WildcardType)t.unannotatedType();
  4280                 t = high ?
  4281                     w.getExtendsBound() :
  4282                     w.getSuperBound();
  4283                 if (t == null) {
  4284                     t = high ? syms.objectType : syms.botType;
  4287             return t;
  4292     /**
  4293      * Create a wildcard with the given upper (extends) bound; create
  4294      * an unbounded wildcard if bound is Object.
  4296      * @param bound the upper bound
  4297      * @param formal the formal type parameter that will be
  4298      * substituted by the wildcard
  4299      */
  4300     private WildcardType makeExtendsWildcard(Type bound, TypeVar formal) {
  4301         if (bound == syms.objectType) {
  4302             return new WildcardType(syms.objectType,
  4303                                     BoundKind.UNBOUND,
  4304                                     syms.boundClass,
  4305                                     formal);
  4306         } else {
  4307             return new WildcardType(bound,
  4308                                     BoundKind.EXTENDS,
  4309                                     syms.boundClass,
  4310                                     formal);
  4314     /**
  4315      * Create a wildcard with the given lower (super) bound; create an
  4316      * unbounded wildcard if bound is bottom (type of {@code null}).
  4318      * @param bound the lower bound
  4319      * @param formal the formal type parameter that will be
  4320      * substituted by the wildcard
  4321      */
  4322     private WildcardType makeSuperWildcard(Type bound, TypeVar formal) {
  4323         if (bound.hasTag(BOT)) {
  4324             return new WildcardType(syms.objectType,
  4325                                     BoundKind.UNBOUND,
  4326                                     syms.boundClass,
  4327                                     formal);
  4328         } else {
  4329             return new WildcardType(bound,
  4330                                     BoundKind.SUPER,
  4331                                     syms.boundClass,
  4332                                     formal);
  4336     /**
  4337      * A wrapper for a type that allows use in sets.
  4338      */
  4339     public static class UniqueType {
  4340         public final Type type;
  4341         final Types types;
  4343         public UniqueType(Type type, Types types) {
  4344             this.type = type;
  4345             this.types = types;
  4348         public int hashCode() {
  4349             return types.hashCode(type);
  4352         public boolean equals(Object obj) {
  4353             return (obj instanceof UniqueType) &&
  4354                 types.isSameAnnotatedType(type, ((UniqueType)obj).type);
  4357         public String toString() {
  4358             return type.toString();
  4362     // </editor-fold>
  4364     // <editor-fold defaultstate="collapsed" desc="Visitors">
  4365     /**
  4366      * A default visitor for types.  All visitor methods except
  4367      * visitType are implemented by delegating to visitType.  Concrete
  4368      * subclasses must provide an implementation of visitType and can
  4369      * override other methods as needed.
  4371      * @param <R> the return type of the operation implemented by this
  4372      * visitor; use Void if no return type is needed.
  4373      * @param <S> the type of the second argument (the first being the
  4374      * type itself) of the operation implemented by this visitor; use
  4375      * Void if a second argument is not needed.
  4376      */
  4377     public static abstract class DefaultTypeVisitor<R,S> implements Type.Visitor<R,S> {
  4378         final public R visit(Type t, S s)               { return t.accept(this, s); }
  4379         public R visitClassType(ClassType t, S s)       { return visitType(t, s); }
  4380         public R visitWildcardType(WildcardType t, S s) { return visitType(t, s); }
  4381         public R visitArrayType(ArrayType t, S s)       { return visitType(t, s); }
  4382         public R visitMethodType(MethodType t, S s)     { return visitType(t, s); }
  4383         public R visitPackageType(PackageType t, S s)   { return visitType(t, s); }
  4384         public R visitTypeVar(TypeVar t, S s)           { return visitType(t, s); }
  4385         public R visitCapturedType(CapturedType t, S s) { return visitType(t, s); }
  4386         public R visitForAll(ForAll t, S s)             { return visitType(t, s); }
  4387         public R visitUndetVar(UndetVar t, S s)         { return visitType(t, s); }
  4388         public R visitErrorType(ErrorType t, S s)       { return visitType(t, s); }
  4389         // Pretend annotations don't exist
  4390         public R visitAnnotatedType(AnnotatedType t, S s) { return visit(t.underlyingType, s); }
  4393     /**
  4394      * A default visitor for symbols.  All visitor methods except
  4395      * visitSymbol are implemented by delegating to visitSymbol.  Concrete
  4396      * subclasses must provide an implementation of visitSymbol and can
  4397      * override other methods as needed.
  4399      * @param <R> the return type of the operation implemented by this
  4400      * visitor; use Void if no return type is needed.
  4401      * @param <S> the type of the second argument (the first being the
  4402      * symbol itself) of the operation implemented by this visitor; use
  4403      * Void if a second argument is not needed.
  4404      */
  4405     public static abstract class DefaultSymbolVisitor<R,S> implements Symbol.Visitor<R,S> {
  4406         final public R visit(Symbol s, S arg)                   { return s.accept(this, arg); }
  4407         public R visitClassSymbol(ClassSymbol s, S arg)         { return visitSymbol(s, arg); }
  4408         public R visitMethodSymbol(MethodSymbol s, S arg)       { return visitSymbol(s, arg); }
  4409         public R visitOperatorSymbol(OperatorSymbol s, S arg)   { return visitSymbol(s, arg); }
  4410         public R visitPackageSymbol(PackageSymbol s, S arg)     { return visitSymbol(s, arg); }
  4411         public R visitTypeSymbol(TypeSymbol s, S arg)           { return visitSymbol(s, arg); }
  4412         public R visitVarSymbol(VarSymbol s, S arg)             { return visitSymbol(s, arg); }
  4415     /**
  4416      * A <em>simple</em> visitor for types.  This visitor is simple as
  4417      * captured wildcards, for-all types (generic methods), and
  4418      * undetermined type variables (part of inference) are hidden.
  4419      * Captured wildcards are hidden by treating them as type
  4420      * variables and the rest are hidden by visiting their qtypes.
  4422      * @param <R> the return type of the operation implemented by this
  4423      * visitor; use Void if no return type is needed.
  4424      * @param <S> the type of the second argument (the first being the
  4425      * type itself) of the operation implemented by this visitor; use
  4426      * Void if a second argument is not needed.
  4427      */
  4428     public static abstract class SimpleVisitor<R,S> extends DefaultTypeVisitor<R,S> {
  4429         @Override
  4430         public R visitCapturedType(CapturedType t, S s) {
  4431             return visitTypeVar(t, s);
  4433         @Override
  4434         public R visitForAll(ForAll t, S s) {
  4435             return visit(t.qtype, s);
  4437         @Override
  4438         public R visitUndetVar(UndetVar t, S s) {
  4439             return visit(t.qtype, s);
  4443     /**
  4444      * A plain relation on types.  That is a 2-ary function on the
  4445      * form Type&nbsp;&times;&nbsp;Type&nbsp;&rarr;&nbsp;Boolean.
  4446      * <!-- In plain text: Type x Type -> Boolean -->
  4447      */
  4448     public static abstract class TypeRelation extends SimpleVisitor<Boolean,Type> {}
  4450     /**
  4451      * A convenience visitor for implementing operations that only
  4452      * require one argument (the type itself), that is, unary
  4453      * operations.
  4455      * @param <R> the return type of the operation implemented by this
  4456      * visitor; use Void if no return type is needed.
  4457      */
  4458     public static abstract class UnaryVisitor<R> extends SimpleVisitor<R,Void> {
  4459         final public R visit(Type t) { return t.accept(this, null); }
  4462     /**
  4463      * A visitor for implementing a mapping from types to types.  The
  4464      * default behavior of this class is to implement the identity
  4465      * mapping (mapping a type to itself).  This can be overridden in
  4466      * subclasses.
  4468      * @param <S> the type of the second argument (the first being the
  4469      * type itself) of this mapping; use Void if a second argument is
  4470      * not needed.
  4471      */
  4472     public static class MapVisitor<S> extends DefaultTypeVisitor<Type,S> {
  4473         final public Type visit(Type t) { return t.accept(this, null); }
  4474         public Type visitType(Type t, S s) { return t; }
  4476     // </editor-fold>
  4479     // <editor-fold defaultstate="collapsed" desc="Annotation support">
  4481     public RetentionPolicy getRetention(Attribute.Compound a) {
  4482         return getRetention(a.type.tsym);
  4485     public RetentionPolicy getRetention(Symbol sym) {
  4486         RetentionPolicy vis = RetentionPolicy.CLASS; // the default
  4487         Attribute.Compound c = sym.attribute(syms.retentionType.tsym);
  4488         if (c != null) {
  4489             Attribute value = c.member(names.value);
  4490             if (value != null && value instanceof Attribute.Enum) {
  4491                 Name levelName = ((Attribute.Enum)value).value.name;
  4492                 if (levelName == names.SOURCE) vis = RetentionPolicy.SOURCE;
  4493                 else if (levelName == names.CLASS) vis = RetentionPolicy.CLASS;
  4494                 else if (levelName == names.RUNTIME) vis = RetentionPolicy.RUNTIME;
  4495                 else ;// /* fail soft */ throw new AssertionError(levelName);
  4498         return vis;
  4500     // </editor-fold>
  4502     // <editor-fold defaultstate="collapsed" desc="Signature Generation">
  4504     public static abstract class SignatureGenerator {
  4506         private final Types types;
  4508         protected abstract void append(char ch);
  4509         protected abstract void append(byte[] ba);
  4510         protected abstract void append(Name name);
  4511         protected void classReference(ClassSymbol c) { /* by default: no-op */ }
  4513         protected SignatureGenerator(Types types) {
  4514             this.types = types;
  4517         /**
  4518          * Assemble signature of given type in string buffer.
  4519          */
  4520         public void assembleSig(Type type) {
  4521             type = type.unannotatedType();
  4522             switch (type.getTag()) {
  4523                 case BYTE:
  4524                     append('B');
  4525                     break;
  4526                 case SHORT:
  4527                     append('S');
  4528                     break;
  4529                 case CHAR:
  4530                     append('C');
  4531                     break;
  4532                 case INT:
  4533                     append('I');
  4534                     break;
  4535                 case LONG:
  4536                     append('J');
  4537                     break;
  4538                 case FLOAT:
  4539                     append('F');
  4540                     break;
  4541                 case DOUBLE:
  4542                     append('D');
  4543                     break;
  4544                 case BOOLEAN:
  4545                     append('Z');
  4546                     break;
  4547                 case VOID:
  4548                     append('V');
  4549                     break;
  4550                 case CLASS:
  4551                     append('L');
  4552                     assembleClassSig(type);
  4553                     append(';');
  4554                     break;
  4555                 case ARRAY:
  4556                     ArrayType at = (ArrayType) type;
  4557                     append('[');
  4558                     assembleSig(at.elemtype);
  4559                     break;
  4560                 case METHOD:
  4561                     MethodType mt = (MethodType) type;
  4562                     append('(');
  4563                     assembleSig(mt.argtypes);
  4564                     append(')');
  4565                     assembleSig(mt.restype);
  4566                     if (hasTypeVar(mt.thrown)) {
  4567                         for (List<Type> l = mt.thrown; l.nonEmpty(); l = l.tail) {
  4568                             append('^');
  4569                             assembleSig(l.head);
  4572                     break;
  4573                 case WILDCARD: {
  4574                     Type.WildcardType ta = (Type.WildcardType) type;
  4575                     switch (ta.kind) {
  4576                         case SUPER:
  4577                             append('-');
  4578                             assembleSig(ta.type);
  4579                             break;
  4580                         case EXTENDS:
  4581                             append('+');
  4582                             assembleSig(ta.type);
  4583                             break;
  4584                         case UNBOUND:
  4585                             append('*');
  4586                             break;
  4587                         default:
  4588                             throw new AssertionError(ta.kind);
  4590                     break;
  4592                 case TYPEVAR:
  4593                     append('T');
  4594                     append(type.tsym.name);
  4595                     append(';');
  4596                     break;
  4597                 case FORALL:
  4598                     Type.ForAll ft = (Type.ForAll) type;
  4599                     assembleParamsSig(ft.tvars);
  4600                     assembleSig(ft.qtype);
  4601                     break;
  4602                 default:
  4603                     throw new AssertionError("typeSig " + type.getTag());
  4607         public boolean hasTypeVar(List<Type> l) {
  4608             while (l.nonEmpty()) {
  4609                 if (l.head.hasTag(TypeTag.TYPEVAR)) {
  4610                     return true;
  4612                 l = l.tail;
  4614             return false;
  4617         public void assembleClassSig(Type type) {
  4618             type = type.unannotatedType();
  4619             ClassType ct = (ClassType) type;
  4620             ClassSymbol c = (ClassSymbol) ct.tsym;
  4621             classReference(c);
  4622             Type outer = ct.getEnclosingType();
  4623             if (outer.allparams().nonEmpty()) {
  4624                 boolean rawOuter =
  4625                         c.owner.kind == Kinds.MTH || // either a local class
  4626                         c.name == types.names.empty; // or anonymous
  4627                 assembleClassSig(rawOuter
  4628                         ? types.erasure(outer)
  4629                         : outer);
  4630                 append('.');
  4631                 Assert.check(c.flatname.startsWith(c.owner.enclClass().flatname));
  4632                 append(rawOuter
  4633                         ? c.flatname.subName(c.owner.enclClass().flatname.getByteLength() + 1, c.flatname.getByteLength())
  4634                         : c.name);
  4635             } else {
  4636                 append(externalize(c.flatname));
  4638             if (ct.getTypeArguments().nonEmpty()) {
  4639                 append('<');
  4640                 assembleSig(ct.getTypeArguments());
  4641                 append('>');
  4645         public void assembleParamsSig(List<Type> typarams) {
  4646             append('<');
  4647             for (List<Type> ts = typarams; ts.nonEmpty(); ts = ts.tail) {
  4648                 Type.TypeVar tvar = (Type.TypeVar) ts.head;
  4649                 append(tvar.tsym.name);
  4650                 List<Type> bounds = types.getBounds(tvar);
  4651                 if ((bounds.head.tsym.flags() & INTERFACE) != 0) {
  4652                     append(':');
  4654                 for (List<Type> l = bounds; l.nonEmpty(); l = l.tail) {
  4655                     append(':');
  4656                     assembleSig(l.head);
  4659             append('>');
  4662         private void assembleSig(List<Type> types) {
  4663             for (List<Type> ts = types; ts.nonEmpty(); ts = ts.tail) {
  4664                 assembleSig(ts.head);
  4668     // </editor-fold>

mercurial