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

Fri, 22 Feb 2013 18:19:51 +0000

author
mcimadamore
date
Fri, 22 Feb 2013 18:19:51 +0000
changeset 1605
94e67bed460d
parent 1600
3fef0cae83b3
child 1644
40adaf938847
permissions
-rw-r--r--

8008708: Regression: separate compilation causes crash in wildcards inference logic
Summary: Invalid use of WildcardType.bound in Types.removeWildcards
Reviewed-by: jjg

     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.Comparator;
    30 import java.util.HashSet;
    31 import java.util.HashMap;
    32 import java.util.Locale;
    33 import java.util.Map;
    34 import java.util.Set;
    35 import java.util.WeakHashMap;
    37 import javax.lang.model.type.TypeKind;
    39 import com.sun.tools.javac.code.Attribute.RetentionPolicy;
    40 import com.sun.tools.javac.code.Lint.LintCategory;
    41 import com.sun.tools.javac.code.Type.UndetVar.InferenceBound;
    42 import com.sun.tools.javac.comp.Check;
    43 import com.sun.tools.javac.jvm.ClassReader;
    44 import com.sun.tools.javac.util.*;
    45 import static com.sun.tools.javac.code.BoundKind.*;
    46 import static com.sun.tools.javac.code.Flags.*;
    47 import static com.sun.tools.javac.code.Scope.*;
    48 import static com.sun.tools.javac.code.Symbol.*;
    49 import static com.sun.tools.javac.code.Type.*;
    50 import static com.sun.tools.javac.code.TypeTag.*;
    51 import static com.sun.tools.javac.jvm.ClassFile.externalize;
    52 import static com.sun.tools.javac.util.ListBuffer.lb;
    54 /**
    55  * Utility class containing various operations on types.
    56  *
    57  * <p>Unless other names are more illustrative, the following naming
    58  * conventions should be observed in this file:
    59  *
    60  * <dl>
    61  * <dt>t</dt>
    62  * <dd>If the first argument to an operation is a type, it should be named t.</dd>
    63  * <dt>s</dt>
    64  * <dd>Similarly, if the second argument to an operation is a type, it should be named s.</dd>
    65  * <dt>ts</dt>
    66  * <dd>If an operations takes a list of types, the first should be named ts.</dd>
    67  * <dt>ss</dt>
    68  * <dd>A second list of types should be named ss.</dd>
    69  * </dl>
    70  *
    71  * <p><b>This is NOT part of any supported API.
    72  * If you write code that depends on this, you do so at your own risk.
    73  * This code and its internal interfaces are subject to change or
    74  * deletion without notice.</b>
    75  */
    76 public class Types {
    77     protected static final Context.Key<Types> typesKey =
    78         new Context.Key<Types>();
    80     final Symtab syms;
    81     final JavacMessages messages;
    82     final Names names;
    83     final boolean allowBoxing;
    84     final boolean allowCovariantReturns;
    85     final boolean allowObjectToPrimitiveCast;
    86     final boolean allowDefaultMethods;
    87     final ClassReader reader;
    88     final Check chk;
    89     JCDiagnostic.Factory diags;
    90     List<Warner> warnStack = List.nil();
    91     final Name capturedName;
    92     private final FunctionDescriptorLookupError functionDescriptorLookupError;
    94     public final Warner noWarnings;
    96     // <editor-fold defaultstate="collapsed" desc="Instantiating">
    97     public static Types instance(Context context) {
    98         Types instance = context.get(typesKey);
    99         if (instance == null)
   100             instance = new Types(context);
   101         return instance;
   102     }
   104     protected Types(Context context) {
   105         context.put(typesKey, this);
   106         syms = Symtab.instance(context);
   107         names = Names.instance(context);
   108         Source source = Source.instance(context);
   109         allowBoxing = source.allowBoxing();
   110         allowCovariantReturns = source.allowCovariantReturns();
   111         allowObjectToPrimitiveCast = source.allowObjectToPrimitiveCast();
   112         allowDefaultMethods = source.allowDefaultMethods();
   113         reader = ClassReader.instance(context);
   114         chk = Check.instance(context);
   115         capturedName = names.fromString("<captured wildcard>");
   116         messages = JavacMessages.instance(context);
   117         diags = JCDiagnostic.Factory.instance(context);
   118         functionDescriptorLookupError = new FunctionDescriptorLookupError();
   119         noWarnings = new Warner(null);
   120     }
   121     // </editor-fold>
   123     // <editor-fold defaultstate="collapsed" desc="upperBound">
   124     /**
   125      * The "rvalue conversion".<br>
   126      * The upper bound of most types is the type
   127      * itself.  Wildcards, on the other hand have upper
   128      * and lower bounds.
   129      * @param t a type
   130      * @return the upper bound of the given type
   131      */
   132     public Type upperBound(Type t) {
   133         return upperBound.visit(t);
   134     }
   135     // where
   136         private final MapVisitor<Void> upperBound = new MapVisitor<Void>() {
   138             @Override
   139             public Type visitWildcardType(WildcardType t, Void ignored) {
   140                 if (t.isSuperBound())
   141                     return t.bound == null ? syms.objectType : t.bound.bound;
   142                 else
   143                     return visit(t.type);
   144             }
   146             @Override
   147             public Type visitCapturedType(CapturedType t, Void ignored) {
   148                 return visit(t.bound);
   149             }
   150         };
   151     // </editor-fold>
   153     // <editor-fold defaultstate="collapsed" desc="lowerBound">
   154     /**
   155      * The "lvalue conversion".<br>
   156      * The lower bound of most types is the type
   157      * itself.  Wildcards, on the other hand have upper
   158      * and lower bounds.
   159      * @param t a type
   160      * @return the lower bound of the given type
   161      */
   162     public Type lowerBound(Type t) {
   163         return lowerBound.visit(t);
   164     }
   165     // where
   166         private final MapVisitor<Void> lowerBound = new MapVisitor<Void>() {
   168             @Override
   169             public Type visitWildcardType(WildcardType t, Void ignored) {
   170                 return t.isExtendsBound() ? syms.botType : visit(t.type);
   171             }
   173             @Override
   174             public Type visitCapturedType(CapturedType t, Void ignored) {
   175                 return visit(t.getLowerBound());
   176             }
   177         };
   178     // </editor-fold>
   180     // <editor-fold defaultstate="collapsed" desc="isUnbounded">
   181     /**
   182      * Checks that all the arguments to a class are unbounded
   183      * wildcards or something else that doesn't make any restrictions
   184      * on the arguments. If a class isUnbounded, a raw super- or
   185      * subclass can be cast to it without a warning.
   186      * @param t a type
   187      * @return true iff the given type is unbounded or raw
   188      */
   189     public boolean isUnbounded(Type t) {
   190         return isUnbounded.visit(t);
   191     }
   192     // where
   193         private final UnaryVisitor<Boolean> isUnbounded = new UnaryVisitor<Boolean>() {
   195             public Boolean visitType(Type t, Void ignored) {
   196                 return true;
   197             }
   199             @Override
   200             public Boolean visitClassType(ClassType t, Void ignored) {
   201                 List<Type> parms = t.tsym.type.allparams();
   202                 List<Type> args = t.allparams();
   203                 while (parms.nonEmpty()) {
   204                     WildcardType unb = new WildcardType(syms.objectType,
   205                                                         BoundKind.UNBOUND,
   206                                                         syms.boundClass,
   207                                                         (TypeVar)parms.head);
   208                     if (!containsType(args.head, unb))
   209                         return false;
   210                     parms = parms.tail;
   211                     args = args.tail;
   212                 }
   213                 return true;
   214             }
   215         };
   216     // </editor-fold>
   218     // <editor-fold defaultstate="collapsed" desc="asSub">
   219     /**
   220      * Return the least specific subtype of t that starts with symbol
   221      * sym.  If none exists, return null.  The least specific subtype
   222      * is determined as follows:
   223      *
   224      * <p>If there is exactly one parameterized instance of sym that is a
   225      * subtype of t, that parameterized instance is returned.<br>
   226      * Otherwise, if the plain type or raw type `sym' is a subtype of
   227      * type t, the type `sym' itself is returned.  Otherwise, null is
   228      * returned.
   229      */
   230     public Type asSub(Type t, Symbol sym) {
   231         return asSub.visit(t, sym);
   232     }
   233     // where
   234         private final SimpleVisitor<Type,Symbol> asSub = new SimpleVisitor<Type,Symbol>() {
   236             public Type visitType(Type t, Symbol sym) {
   237                 return null;
   238             }
   240             @Override
   241             public Type visitClassType(ClassType t, Symbol sym) {
   242                 if (t.tsym == sym)
   243                     return t;
   244                 Type base = asSuper(sym.type, t.tsym);
   245                 if (base == null)
   246                     return null;
   247                 ListBuffer<Type> from = new ListBuffer<Type>();
   248                 ListBuffer<Type> to = new ListBuffer<Type>();
   249                 try {
   250                     adapt(base, t, from, to);
   251                 } catch (AdaptFailure ex) {
   252                     return null;
   253                 }
   254                 Type res = subst(sym.type, from.toList(), to.toList());
   255                 if (!isSubtype(res, t))
   256                     return null;
   257                 ListBuffer<Type> openVars = new ListBuffer<Type>();
   258                 for (List<Type> l = sym.type.allparams();
   259                      l.nonEmpty(); l = l.tail)
   260                     if (res.contains(l.head) && !t.contains(l.head))
   261                         openVars.append(l.head);
   262                 if (openVars.nonEmpty()) {
   263                     if (t.isRaw()) {
   264                         // The subtype of a raw type is raw
   265                         res = erasure(res);
   266                     } else {
   267                         // Unbound type arguments default to ?
   268                         List<Type> opens = openVars.toList();
   269                         ListBuffer<Type> qs = new ListBuffer<Type>();
   270                         for (List<Type> iter = opens; iter.nonEmpty(); iter = iter.tail) {
   271                             qs.append(new WildcardType(syms.objectType, BoundKind.UNBOUND, syms.boundClass, (TypeVar) iter.head));
   272                         }
   273                         res = subst(res, opens, qs.toList());
   274                     }
   275                 }
   276                 return res;
   277             }
   279             @Override
   280             public Type visitErrorType(ErrorType t, Symbol sym) {
   281                 return t;
   282             }
   283         };
   284     // </editor-fold>
   286     // <editor-fold defaultstate="collapsed" desc="isConvertible">
   287     /**
   288      * Is t a subtype of or convertible via boxing/unboxing
   289      * conversion to s?
   290      */
   291     public boolean isConvertible(Type t, Type s, Warner warn) {
   292         if (t.tag == ERROR)
   293             return true;
   294         boolean tPrimitive = t.isPrimitive();
   295         boolean sPrimitive = s.isPrimitive();
   296         if (tPrimitive == sPrimitive) {
   297             return isSubtypeUnchecked(t, s, warn);
   298         }
   299         if (!allowBoxing) return false;
   300         return tPrimitive
   301             ? isSubtype(boxedClass(t).type, s)
   302             : isSubtype(unboxedType(t), s);
   303     }
   305     /**
   306      * Is t a subtype of or convertiable via boxing/unboxing
   307      * convertions to s?
   308      */
   309     public boolean isConvertible(Type t, Type s) {
   310         return isConvertible(t, s, noWarnings);
   311     }
   312     // </editor-fold>
   314     // <editor-fold defaultstate="collapsed" desc="findSam">
   316     /**
   317      * Exception used to report a function descriptor lookup failure. The exception
   318      * wraps a diagnostic that can be used to generate more details error
   319      * messages.
   320      */
   321     public static class FunctionDescriptorLookupError extends RuntimeException {
   322         private static final long serialVersionUID = 0;
   324         JCDiagnostic diagnostic;
   326         FunctionDescriptorLookupError() {
   327             this.diagnostic = null;
   328         }
   330         FunctionDescriptorLookupError setMessage(JCDiagnostic diag) {
   331             this.diagnostic = diag;
   332             return this;
   333         }
   335         public JCDiagnostic getDiagnostic() {
   336             return diagnostic;
   337         }
   338     }
   340     /**
   341      * A cache that keeps track of function descriptors associated with given
   342      * functional interfaces.
   343      */
   344     class DescriptorCache {
   346         private WeakHashMap<TypeSymbol, Entry> _map = new WeakHashMap<TypeSymbol, Entry>();
   348         class FunctionDescriptor {
   349             Symbol descSym;
   351             FunctionDescriptor(Symbol descSym) {
   352                 this.descSym = descSym;
   353             }
   355             public Symbol getSymbol() {
   356                 return descSym;
   357             }
   359             public Type getType(Type site) {
   360                 site = removeWildcards(site);
   361                 if (!chk.checkValidGenericType(site)) {
   362                     //if the inferred functional interface type is not well-formed,
   363                     //or if it's not a subtype of the original target, issue an error
   364                     throw failure(diags.fragment("no.suitable.functional.intf.inst", site));
   365                 }
   366                 return memberType(site, descSym);
   367             }
   368         }
   370         class Entry {
   371             final FunctionDescriptor cachedDescRes;
   372             final int prevMark;
   374             public Entry(FunctionDescriptor cachedDescRes,
   375                     int prevMark) {
   376                 this.cachedDescRes = cachedDescRes;
   377                 this.prevMark = prevMark;
   378             }
   380             boolean matches(int mark) {
   381                 return  this.prevMark == mark;
   382             }
   383         }
   385         FunctionDescriptor get(TypeSymbol origin) throws FunctionDescriptorLookupError {
   386             Entry e = _map.get(origin);
   387             CompoundScope members = membersClosure(origin.type, false);
   388             if (e == null ||
   389                     !e.matches(members.getMark())) {
   390                 FunctionDescriptor descRes = findDescriptorInternal(origin, members);
   391                 _map.put(origin, new Entry(descRes, members.getMark()));
   392                 return descRes;
   393             }
   394             else {
   395                 return e.cachedDescRes;
   396             }
   397         }
   399         /**
   400          * Compute the function descriptor associated with a given functional interface
   401          */
   402         public FunctionDescriptor findDescriptorInternal(TypeSymbol origin, CompoundScope membersCache) throws FunctionDescriptorLookupError {
   403             if (!origin.isInterface() || (origin.flags() & ANNOTATION) != 0) {
   404                 //t must be an interface
   405                 throw failure("not.a.functional.intf", origin);
   406             }
   408             final ListBuffer<Symbol> abstracts = ListBuffer.lb();
   409             for (Symbol sym : membersCache.getElements(new DescriptorFilter(origin))) {
   410                 Type mtype = memberType(origin.type, sym);
   411                 if (abstracts.isEmpty() ||
   412                         (sym.name == abstracts.first().name &&
   413                         overrideEquivalent(mtype, memberType(origin.type, abstracts.first())))) {
   414                     abstracts.append(sym);
   415                 } else {
   416                     //the target method(s) should be the only abstract members of t
   417                     throw failure("not.a.functional.intf.1",  origin,
   418                             diags.fragment("incompatible.abstracts", Kinds.kindName(origin), origin));
   419                 }
   420             }
   421             if (abstracts.isEmpty()) {
   422                 //t must define a suitable non-generic method
   423                 throw failure("not.a.functional.intf.1", origin,
   424                             diags.fragment("no.abstracts", Kinds.kindName(origin), origin));
   425             } else if (abstracts.size() == 1) {
   426                 return new FunctionDescriptor(abstracts.first());
   427             } else { // size > 1
   428                 FunctionDescriptor descRes = mergeDescriptors(origin, abstracts.toList());
   429                 if (descRes == null) {
   430                     //we can get here if the functional interface is ill-formed
   431                     ListBuffer<JCDiagnostic> descriptors = ListBuffer.lb();
   432                     for (Symbol desc : abstracts) {
   433                         String key = desc.type.getThrownTypes().nonEmpty() ?
   434                                 "descriptor.throws" : "descriptor";
   435                         descriptors.append(diags.fragment(key, desc.name,
   436                                 desc.type.getParameterTypes(),
   437                                 desc.type.getReturnType(),
   438                                 desc.type.getThrownTypes()));
   439                     }
   440                     JCDiagnostic.MultilineDiagnostic incompatibleDescriptors =
   441                             new JCDiagnostic.MultilineDiagnostic(diags.fragment("incompatible.descs.in.functional.intf",
   442                             Kinds.kindName(origin), origin), descriptors.toList());
   443                     throw failure(incompatibleDescriptors);
   444                 }
   445                 return descRes;
   446             }
   447         }
   449         /**
   450          * Compute a synthetic type for the target descriptor given a list
   451          * of override-equivalent methods in the functional interface type.
   452          * The resulting method type is a method type that is override-equivalent
   453          * and return-type substitutable with each method in the original list.
   454          */
   455         private FunctionDescriptor mergeDescriptors(TypeSymbol origin, List<Symbol> methodSyms) {
   456             //pick argument types - simply take the signature that is a
   457             //subsignature of all other signatures in the list (as per JLS 8.4.2)
   458             List<Symbol> mostSpecific = List.nil();
   459             outer: for (Symbol msym1 : methodSyms) {
   460                 Type mt1 = memberType(origin.type, msym1);
   461                 for (Symbol msym2 : methodSyms) {
   462                     Type mt2 = memberType(origin.type, msym2);
   463                     if (!isSubSignature(mt1, mt2)) {
   464                         continue outer;
   465                     }
   466                 }
   467                 mostSpecific = mostSpecific.prepend(msym1);
   468             }
   469             if (mostSpecific.isEmpty()) {
   470                 return null;
   471             }
   474             //pick return types - this is done in two phases: (i) first, the most
   475             //specific return type is chosen using strict subtyping; if this fails,
   476             //a second attempt is made using return type substitutability (see JLS 8.4.5)
   477             boolean phase2 = false;
   478             Symbol bestSoFar = null;
   479             while (bestSoFar == null) {
   480                 outer: for (Symbol msym1 : mostSpecific) {
   481                     Type mt1 = memberType(origin.type, msym1);
   482                     for (Symbol msym2 : methodSyms) {
   483                         Type mt2 = memberType(origin.type, msym2);
   484                         if (phase2 ?
   485                                 !returnTypeSubstitutable(mt1, mt2) :
   486                                 !isSubtypeInternal(mt1.getReturnType(), mt2.getReturnType())) {
   487                             continue outer;
   488                         }
   489                     }
   490                     bestSoFar = msym1;
   491                 }
   492                 if (phase2) {
   493                     break;
   494                 } else {
   495                     phase2 = true;
   496                 }
   497             }
   498             if (bestSoFar == null) return null;
   500             //merge thrown types - form the intersection of all the thrown types in
   501             //all the signatures in the list
   502             List<Type> thrown = null;
   503             for (Symbol msym1 : methodSyms) {
   504                 Type mt1 = memberType(origin.type, msym1);
   505                 thrown = (thrown == null) ?
   506                     mt1.getThrownTypes() :
   507                     chk.intersect(mt1.getThrownTypes(), thrown);
   508             }
   510             final List<Type> thrown1 = thrown;
   511             return new FunctionDescriptor(bestSoFar) {
   512                 @Override
   513                 public Type getType(Type origin) {
   514                     Type mt = memberType(origin, getSymbol());
   515                     return createMethodTypeWithThrown(mt, thrown1);
   516                 }
   517             };
   518         }
   520         boolean isSubtypeInternal(Type s, Type t) {
   521             return (s.isPrimitive() && t.isPrimitive()) ?
   522                     isSameType(t, s) :
   523                     isSubtype(s, t);
   524         }
   526         FunctionDescriptorLookupError failure(String msg, Object... args) {
   527             return failure(diags.fragment(msg, args));
   528         }
   530         FunctionDescriptorLookupError failure(JCDiagnostic diag) {
   531             return functionDescriptorLookupError.setMessage(diag);
   532         }
   533     }
   535     private DescriptorCache descCache = new DescriptorCache();
   537     /**
   538      * Find the method descriptor associated to this class symbol - if the
   539      * symbol 'origin' is not a functional interface, an exception is thrown.
   540      */
   541     public Symbol findDescriptorSymbol(TypeSymbol origin) throws FunctionDescriptorLookupError {
   542         return descCache.get(origin).getSymbol();
   543     }
   545     /**
   546      * Find the type of the method descriptor associated to this class symbol -
   547      * if the symbol 'origin' is not a functional interface, an exception is thrown.
   548      */
   549     public Type findDescriptorType(Type origin) throws FunctionDescriptorLookupError {
   550         return descCache.get(origin.tsym).getType(origin);
   551     }
   553     /**
   554      * Is given type a functional interface?
   555      */
   556     public boolean isFunctionalInterface(TypeSymbol tsym) {
   557         try {
   558             findDescriptorSymbol(tsym);
   559             return true;
   560         } catch (FunctionDescriptorLookupError ex) {
   561             return false;
   562         }
   563     }
   565     public boolean isFunctionalInterface(Type site) {
   566         try {
   567             findDescriptorType(site);
   568             return true;
   569         } catch (FunctionDescriptorLookupError ex) {
   570             return false;
   571         }
   572     }
   574     public Type removeWildcards(Type site) {
   575         Type capturedSite = capture(site);
   576         if (capturedSite != site) {
   577             Type formalInterface = site.tsym.type;
   578             ListBuffer<Type> typeargs = ListBuffer.lb();
   579             List<Type> actualTypeargs = site.getTypeArguments();
   580             List<Type> capturedTypeargs = capturedSite.getTypeArguments();
   581             //simply replace the wildcards with its bound
   582             for (Type t : formalInterface.getTypeArguments()) {
   583                 if (actualTypeargs.head.hasTag(WILDCARD)) {
   584                     WildcardType wt = (WildcardType)actualTypeargs.head;
   585                     Type bound;
   586                     switch (wt.kind) {
   587                         case EXTENDS:
   588                         case UNBOUND:
   589                             CapturedType capVar = (CapturedType)capturedTypeargs.head;
   590                             //use declared bound if it doesn't depend on formal type-args
   591                             bound = capVar.bound.containsAny(capturedSite.getTypeArguments()) ?
   592                                     syms.objectType : capVar.bound;
   593                             break;
   594                         default:
   595                             bound = wt.type;
   596                     }
   597                     typeargs.append(bound);
   598                 } else {
   599                     typeargs.append(actualTypeargs.head);
   600                 }
   601                 actualTypeargs = actualTypeargs.tail;
   602                 capturedTypeargs = capturedTypeargs.tail;
   603             }
   604             return subst(formalInterface, formalInterface.getTypeArguments(), typeargs.toList());
   605         } else {
   606             return site;
   607         }
   608     }
   609     // </editor-fold>
   611    /**
   612     * Scope filter used to skip methods that should be ignored (such as methods
   613     * overridden by j.l.Object) during function interface conversion/marker interface checks
   614     */
   615     class DescriptorFilter implements Filter<Symbol> {
   617        TypeSymbol origin;
   619        DescriptorFilter(TypeSymbol origin) {
   620            this.origin = origin;
   621        }
   623        @Override
   624        public boolean accepts(Symbol sym) {
   625            return sym.kind == Kinds.MTH &&
   626                    (sym.flags() & (ABSTRACT | DEFAULT)) == ABSTRACT &&
   627                    !overridesObjectMethod(origin, sym) &&
   628                    (interfaceCandidates(origin.type, (MethodSymbol)sym).head.flags() & DEFAULT) == 0;
   629        }
   630     };
   632     // <editor-fold defaultstate="collapsed" desc="isMarker">
   634     /**
   635      * A cache that keeps track of marker interfaces
   636      */
   637     class MarkerCache {
   639         private WeakHashMap<TypeSymbol, Entry> _map = new WeakHashMap<TypeSymbol, Entry>();
   641         class Entry {
   642             final boolean isMarkerIntf;
   643             final int prevMark;
   645             public Entry(boolean isMarkerIntf,
   646                     int prevMark) {
   647                 this.isMarkerIntf = isMarkerIntf;
   648                 this.prevMark = prevMark;
   649             }
   651             boolean matches(int mark) {
   652                 return  this.prevMark == mark;
   653             }
   654         }
   656         boolean get(TypeSymbol origin) throws FunctionDescriptorLookupError {
   657             Entry e = _map.get(origin);
   658             CompoundScope members = membersClosure(origin.type, false);
   659             if (e == null ||
   660                     !e.matches(members.getMark())) {
   661                 boolean isMarkerIntf = isMarkerInterfaceInternal(origin, members);
   662                 _map.put(origin, new Entry(isMarkerIntf, members.getMark()));
   663                 return isMarkerIntf;
   664             }
   665             else {
   666                 return e.isMarkerIntf;
   667             }
   668         }
   670         /**
   671          * Is given symbol a marker interface
   672          */
   673         public boolean isMarkerInterfaceInternal(TypeSymbol origin, CompoundScope membersCache) throws FunctionDescriptorLookupError {
   674             return !origin.isInterface() ?
   675                     false :
   676                     !membersCache.getElements(new DescriptorFilter(origin)).iterator().hasNext();
   677         }
   678     }
   680     private MarkerCache markerCache = new MarkerCache();
   682     /**
   683      * Is given type a marker interface?
   684      */
   685     public boolean isMarkerInterface(Type site) {
   686         return markerCache.get(site.tsym);
   687     }
   688     // </editor-fold>
   690     // <editor-fold defaultstate="collapsed" desc="isSubtype">
   691     /**
   692      * Is t an unchecked subtype of s?
   693      */
   694     public boolean isSubtypeUnchecked(Type t, Type s) {
   695         return isSubtypeUnchecked(t, s, noWarnings);
   696     }
   697     /**
   698      * Is t an unchecked subtype of s?
   699      */
   700     public boolean isSubtypeUnchecked(Type t, Type s, Warner warn) {
   701         boolean result = isSubtypeUncheckedInternal(t, s, warn);
   702         if (result) {
   703             checkUnsafeVarargsConversion(t, s, warn);
   704         }
   705         return result;
   706     }
   707     //where
   708         private boolean isSubtypeUncheckedInternal(Type t, Type s, Warner warn) {
   709             if (t.hasTag(ARRAY) && s.hasTag(ARRAY)) {
   710                 t = t.unannotatedType();
   711                 s = s.unannotatedType();
   712                 if (((ArrayType)t).elemtype.isPrimitive()) {
   713                     return isSameType(elemtype(t), elemtype(s));
   714                 } else {
   715                     return isSubtypeUnchecked(elemtype(t), elemtype(s), warn);
   716                 }
   717             } else if (isSubtype(t, s)) {
   718                 return true;
   719             }
   720             else if (t.tag == TYPEVAR) {
   721                 return isSubtypeUnchecked(t.getUpperBound(), s, warn);
   722             }
   723             else if (!s.isRaw()) {
   724                 Type t2 = asSuper(t, s.tsym);
   725                 if (t2 != null && t2.isRaw()) {
   726                     if (isReifiable(s))
   727                         warn.silentWarn(LintCategory.UNCHECKED);
   728                     else
   729                         warn.warn(LintCategory.UNCHECKED);
   730                     return true;
   731                 }
   732             }
   733             return false;
   734         }
   736         private void checkUnsafeVarargsConversion(Type t, Type s, Warner warn) {
   737             if (t.tag != ARRAY || isReifiable(t))
   738                 return;
   739             t = t.unannotatedType();
   740             s = s.unannotatedType();
   741             ArrayType from = (ArrayType)t;
   742             boolean shouldWarn = false;
   743             switch (s.tag) {
   744                 case ARRAY:
   745                     ArrayType to = (ArrayType)s;
   746                     shouldWarn = from.isVarargs() &&
   747                             !to.isVarargs() &&
   748                             !isReifiable(from);
   749                     break;
   750                 case CLASS:
   751                     shouldWarn = from.isVarargs();
   752                     break;
   753             }
   754             if (shouldWarn) {
   755                 warn.warn(LintCategory.VARARGS);
   756             }
   757         }
   759     /**
   760      * Is t a subtype of s?<br>
   761      * (not defined for Method and ForAll types)
   762      */
   763     final public boolean isSubtype(Type t, Type s) {
   764         return isSubtype(t, s, true);
   765     }
   766     final public boolean isSubtypeNoCapture(Type t, Type s) {
   767         return isSubtype(t, s, false);
   768     }
   769     public boolean isSubtype(Type t, Type s, boolean capture) {
   770         if (t == s)
   771             return true;
   773         t = t.unannotatedType();
   774         s = s.unannotatedType();
   776         if (t == s)
   777             return true;
   779         if (s.isPartial())
   780             return isSuperType(s, t);
   782         if (s.isCompound()) {
   783             for (Type s2 : interfaces(s).prepend(supertype(s))) {
   784                 if (!isSubtype(t, s2, capture))
   785                     return false;
   786             }
   787             return true;
   788         }
   790         Type lower = lowerBound(s);
   791         if (s != lower)
   792             return isSubtype(capture ? capture(t) : t, lower, false);
   794         return isSubtype.visit(capture ? capture(t) : t, s);
   795     }
   796     // where
   797         private TypeRelation isSubtype = new TypeRelation()
   798         {
   799             public Boolean visitType(Type t, Type s) {
   800                 switch (t.tag) {
   801                  case BYTE:
   802                      return (!s.hasTag(CHAR) && t.getTag().isSubRangeOf(s.getTag()));
   803                  case CHAR:
   804                      return (!s.hasTag(SHORT) && t.getTag().isSubRangeOf(s.getTag()));
   805                  case SHORT: case INT: case LONG:
   806                  case FLOAT: case DOUBLE:
   807                      return t.getTag().isSubRangeOf(s.getTag());
   808                  case BOOLEAN: case VOID:
   809                      return t.hasTag(s.getTag());
   810                  case TYPEVAR:
   811                      return isSubtypeNoCapture(t.getUpperBound(), s);
   812                  case BOT:
   813                      return
   814                          s.hasTag(BOT) || s.hasTag(CLASS) ||
   815                          s.hasTag(ARRAY) || s.hasTag(TYPEVAR);
   816                  case WILDCARD: //we shouldn't be here - avoids crash (see 7034495)
   817                  case NONE:
   818                      return false;
   819                  default:
   820                      throw new AssertionError("isSubtype " + t.tag);
   821                  }
   822             }
   824             private Set<TypePair> cache = new HashSet<TypePair>();
   826             private boolean containsTypeRecursive(Type t, Type s) {
   827                 TypePair pair = new TypePair(t, s);
   828                 if (cache.add(pair)) {
   829                     try {
   830                         return containsType(t.getTypeArguments(),
   831                                             s.getTypeArguments());
   832                     } finally {
   833                         cache.remove(pair);
   834                     }
   835                 } else {
   836                     return containsType(t.getTypeArguments(),
   837                                         rewriteSupers(s).getTypeArguments());
   838                 }
   839             }
   841             private Type rewriteSupers(Type t) {
   842                 if (!t.isParameterized())
   843                     return t;
   844                 ListBuffer<Type> from = lb();
   845                 ListBuffer<Type> to = lb();
   846                 adaptSelf(t, from, to);
   847                 if (from.isEmpty())
   848                     return t;
   849                 ListBuffer<Type> rewrite = lb();
   850                 boolean changed = false;
   851                 for (Type orig : to.toList()) {
   852                     Type s = rewriteSupers(orig);
   853                     if (s.isSuperBound() && !s.isExtendsBound()) {
   854                         s = new WildcardType(syms.objectType,
   855                                              BoundKind.UNBOUND,
   856                                              syms.boundClass);
   857                         changed = true;
   858                     } else if (s != orig) {
   859                         s = new WildcardType(upperBound(s),
   860                                              BoundKind.EXTENDS,
   861                                              syms.boundClass);
   862                         changed = true;
   863                     }
   864                     rewrite.append(s);
   865                 }
   866                 if (changed)
   867                     return subst(t.tsym.type, from.toList(), rewrite.toList());
   868                 else
   869                     return t;
   870             }
   872             @Override
   873             public Boolean visitClassType(ClassType t, Type s) {
   874                 Type sup = asSuper(t, s.tsym);
   875                 return sup != null
   876                     && sup.tsym == s.tsym
   877                     // You're not allowed to write
   878                     //     Vector<Object> vec = new Vector<String>();
   879                     // But with wildcards you can write
   880                     //     Vector<? extends Object> vec = new Vector<String>();
   881                     // which means that subtype checking must be done
   882                     // here instead of same-type checking (via containsType).
   883                     && (!s.isParameterized() || containsTypeRecursive(s, sup))
   884                     && isSubtypeNoCapture(sup.getEnclosingType(),
   885                                           s.getEnclosingType());
   886             }
   888             @Override
   889             public Boolean visitArrayType(ArrayType t, Type s) {
   890                 if (s.tag == ARRAY) {
   891                     if (t.elemtype.isPrimitive())
   892                         return isSameType(t.elemtype, elemtype(s));
   893                     else
   894                         return isSubtypeNoCapture(t.elemtype, elemtype(s));
   895                 }
   897                 if (s.tag == CLASS) {
   898                     Name sname = s.tsym.getQualifiedName();
   899                     return sname == names.java_lang_Object
   900                         || sname == names.java_lang_Cloneable
   901                         || sname == names.java_io_Serializable;
   902                 }
   904                 return false;
   905             }
   907             @Override
   908             public Boolean visitUndetVar(UndetVar t, Type s) {
   909                 //todo: test against origin needed? or replace with substitution?
   910                 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN) {
   911                     return true;
   912                 } else if (s.tag == BOT) {
   913                     //if 's' is 'null' there's no instantiated type U for which
   914                     //U <: s (but 'null' itself, which is not a valid type)
   915                     return false;
   916                 }
   918                 t.addBound(InferenceBound.UPPER, s, Types.this);
   919                 return true;
   920             }
   922             @Override
   923             public Boolean visitErrorType(ErrorType t, Type s) {
   924                 return true;
   925             }
   926         };
   928     /**
   929      * Is t a subtype of every type in given list `ts'?<br>
   930      * (not defined for Method and ForAll types)<br>
   931      * Allows unchecked conversions.
   932      */
   933     public boolean isSubtypeUnchecked(Type t, List<Type> ts, Warner warn) {
   934         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
   935             if (!isSubtypeUnchecked(t, l.head, warn))
   936                 return false;
   937         return true;
   938     }
   940     /**
   941      * Are corresponding elements of ts subtypes of ss?  If lists are
   942      * of different length, return false.
   943      */
   944     public boolean isSubtypes(List<Type> ts, List<Type> ss) {
   945         while (ts.tail != null && ss.tail != null
   946                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   947                isSubtype(ts.head, ss.head)) {
   948             ts = ts.tail;
   949             ss = ss.tail;
   950         }
   951         return ts.tail == null && ss.tail == null;
   952         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   953     }
   955     /**
   956      * Are corresponding elements of ts subtypes of ss, allowing
   957      * unchecked conversions?  If lists are of different length,
   958      * return false.
   959      **/
   960     public boolean isSubtypesUnchecked(List<Type> ts, List<Type> ss, Warner warn) {
   961         while (ts.tail != null && ss.tail != null
   962                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   963                isSubtypeUnchecked(ts.head, ss.head, warn)) {
   964             ts = ts.tail;
   965             ss = ss.tail;
   966         }
   967         return ts.tail == null && ss.tail == null;
   968         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   969     }
   970     // </editor-fold>
   972     // <editor-fold defaultstate="collapsed" desc="isSuperType">
   973     /**
   974      * Is t a supertype of s?
   975      */
   976     public boolean isSuperType(Type t, Type s) {
   977         switch (t.tag) {
   978         case ERROR:
   979             return true;
   980         case UNDETVAR: {
   981             UndetVar undet = (UndetVar)t;
   982             if (t == s ||
   983                 undet.qtype == s ||
   984                 s.tag == ERROR ||
   985                 s.tag == BOT) return true;
   986             undet.addBound(InferenceBound.LOWER, s, this);
   987             return true;
   988         }
   989         default:
   990             return isSubtype(s, t);
   991         }
   992     }
   993     // </editor-fold>
   995     // <editor-fold defaultstate="collapsed" desc="isSameType">
   996     /**
   997      * Are corresponding elements of the lists the same type?  If
   998      * lists are of different length, return false.
   999      */
  1000     public boolean isSameTypes(List<Type> ts, List<Type> ss) {
  1001         return isSameTypes(ts, ss, false);
  1003     public boolean isSameTypes(List<Type> ts, List<Type> ss, boolean strict) {
  1004         while (ts.tail != null && ss.tail != null
  1005                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
  1006                isSameType(ts.head, ss.head, strict)) {
  1007             ts = ts.tail;
  1008             ss = ss.tail;
  1010         return ts.tail == null && ss.tail == null;
  1011         /*inlined: ts.isEmpty() && ss.isEmpty();*/
  1014     /**
  1015      * Is t the same type as s?
  1016      */
  1017     public boolean isSameType(Type t, Type s) {
  1018         return isSameType(t, s, false);
  1020     public boolean isSameType(Type t, Type s, boolean strict) {
  1021         return strict ?
  1022                 isSameTypeStrict.visit(t, s) :
  1023                 isSameTypeLoose.visit(t, s);
  1025     // where
  1026         abstract class SameTypeVisitor extends TypeRelation {
  1028             public Boolean visitType(Type t, Type s) {
  1029                 if (t == s)
  1030                     return true;
  1032                 if (s.isPartial())
  1033                     return visit(s, t);
  1035                 switch (t.tag) {
  1036                 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
  1037                 case DOUBLE: case BOOLEAN: case VOID: case BOT: case NONE:
  1038                     return t.tag == s.tag;
  1039                 case TYPEVAR: {
  1040                     if (s.tag == TYPEVAR) {
  1041                         //type-substitution does not preserve type-var types
  1042                         //check that type var symbols and bounds are indeed the same
  1043                         return sameTypeVars((TypeVar)t, (TypeVar)s);
  1045                     else {
  1046                         //special case for s == ? super X, where upper(s) = u
  1047                         //check that u == t, where u has been set by Type.withTypeVar
  1048                         return s.isSuperBound() &&
  1049                                 !s.isExtendsBound() &&
  1050                                 visit(t, upperBound(s));
  1053                 default:
  1054                     throw new AssertionError("isSameType " + t.tag);
  1058             abstract boolean sameTypeVars(TypeVar tv1, TypeVar tv2);
  1060             @Override
  1061             public Boolean visitWildcardType(WildcardType t, Type s) {
  1062                 if (s.isPartial())
  1063                     return visit(s, t);
  1064                 else
  1065                     return false;
  1068             @Override
  1069             public Boolean visitClassType(ClassType t, Type s) {
  1070                 if (t == s)
  1071                     return true;
  1073                 if (s.isPartial())
  1074                     return visit(s, t);
  1076                 if (s.isSuperBound() && !s.isExtendsBound())
  1077                     return visit(t, upperBound(s)) && visit(t, lowerBound(s));
  1079                 if (t.isCompound() && s.isCompound()) {
  1080                     if (!visit(supertype(t), supertype(s)))
  1081                         return false;
  1083                     HashSet<UniqueType> set = new HashSet<UniqueType>();
  1084                     for (Type x : interfaces(t))
  1085                         set.add(new UniqueType(x, Types.this));
  1086                     for (Type x : interfaces(s)) {
  1087                         if (!set.remove(new UniqueType(x, Types.this)))
  1088                             return false;
  1090                     return (set.isEmpty());
  1092                 return t.tsym == s.tsym
  1093                     && visit(t.getEnclosingType(), s.getEnclosingType())
  1094                     && containsTypes(t.getTypeArguments(), s.getTypeArguments());
  1097             abstract protected boolean containsTypes(List<Type> ts1, List<Type> ts2);
  1099             @Override
  1100             public Boolean visitArrayType(ArrayType t, Type s) {
  1101                 if (t == s)
  1102                     return true;
  1104                 if (s.isPartial())
  1105                     return visit(s, t);
  1107                 return s.hasTag(ARRAY)
  1108                     && containsTypeEquivalent(t.elemtype, elemtype(s));
  1111             @Override
  1112             public Boolean visitMethodType(MethodType t, Type s) {
  1113                 // isSameType for methods does not take thrown
  1114                 // exceptions into account!
  1115                 return hasSameArgs(t, s) && visit(t.getReturnType(), s.getReturnType());
  1118             @Override
  1119             public Boolean visitPackageType(PackageType t, Type s) {
  1120                 return t == s;
  1123             @Override
  1124             public Boolean visitForAll(ForAll t, Type s) {
  1125                 if (s.tag != FORALL)
  1126                     return false;
  1128                 ForAll forAll = (ForAll)s;
  1129                 return hasSameBounds(t, forAll)
  1130                     && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
  1133             @Override
  1134             public Boolean visitUndetVar(UndetVar t, Type s) {
  1135                 if (s.tag == WILDCARD)
  1136                     // FIXME, this might be leftovers from before capture conversion
  1137                     return false;
  1139                 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN)
  1140                     return true;
  1142                 t.addBound(InferenceBound.EQ, s, Types.this);
  1144                 return true;
  1147             @Override
  1148             public Boolean visitErrorType(ErrorType t, Type s) {
  1149                 return true;
  1153         /**
  1154          * Standard type-equality relation - type variables are considered
  1155          * equals if they share the same type symbol.
  1156          */
  1157         TypeRelation isSameTypeLoose = new SameTypeVisitor() {
  1158             @Override
  1159             boolean sameTypeVars(TypeVar tv1, TypeVar tv2) {
  1160                 return tv1.tsym == tv2.tsym && visit(tv1.getUpperBound(), tv2.getUpperBound());
  1162             @Override
  1163             protected boolean containsTypes(List<Type> ts1, List<Type> ts2) {
  1164                 return containsTypeEquivalent(ts1, ts2);
  1166         };
  1168         /**
  1169          * Strict type-equality relation - type variables are considered
  1170          * equals if they share the same object identity.
  1171          */
  1172         TypeRelation isSameTypeStrict = new SameTypeVisitor() {
  1173             @Override
  1174             boolean sameTypeVars(TypeVar tv1, TypeVar tv2) {
  1175                 return tv1 == tv2;
  1177             @Override
  1178             protected boolean containsTypes(List<Type> ts1, List<Type> ts2) {
  1179                 return isSameTypes(ts1, ts2, true);
  1181         };
  1182     // </editor-fold>
  1184     // <editor-fold defaultstate="collapsed" desc="Contains Type">
  1185     public boolean containedBy(Type t, Type s) {
  1186         switch (t.tag) {
  1187         case UNDETVAR:
  1188             if (s.tag == WILDCARD) {
  1189                 UndetVar undetvar = (UndetVar)t;
  1190                 WildcardType wt = (WildcardType)s;
  1191                 switch(wt.kind) {
  1192                     case UNBOUND: //similar to ? extends Object
  1193                     case EXTENDS: {
  1194                         Type bound = upperBound(s);
  1195                         undetvar.addBound(InferenceBound.UPPER, bound, this);
  1196                         break;
  1198                     case SUPER: {
  1199                         Type bound = lowerBound(s);
  1200                         undetvar.addBound(InferenceBound.LOWER, bound, this);
  1201                         break;
  1204                 return true;
  1205             } else {
  1206                 return isSameType(t, s);
  1208         case ERROR:
  1209             return true;
  1210         default:
  1211             return containsType(s, t);
  1215     boolean containsType(List<Type> ts, List<Type> ss) {
  1216         while (ts.nonEmpty() && ss.nonEmpty()
  1217                && containsType(ts.head, ss.head)) {
  1218             ts = ts.tail;
  1219             ss = ss.tail;
  1221         return ts.isEmpty() && ss.isEmpty();
  1224     /**
  1225      * Check if t contains s.
  1227      * <p>T contains S if:
  1229      * <p>{@code L(T) <: L(S) && U(S) <: U(T)}
  1231      * <p>This relation is only used by ClassType.isSubtype(), that
  1232      * is,
  1234      * <p>{@code C<S> <: C<T> if T contains S.}
  1236      * <p>Because of F-bounds, this relation can lead to infinite
  1237      * recursion.  Thus we must somehow break that recursion.  Notice
  1238      * that containsType() is only called from ClassType.isSubtype().
  1239      * Since the arguments have already been checked against their
  1240      * bounds, we know:
  1242      * <p>{@code U(S) <: U(T) if T is "super" bound (U(T) *is* the bound)}
  1244      * <p>{@code L(T) <: L(S) if T is "extends" bound (L(T) is bottom)}
  1246      * @param t a type
  1247      * @param s a type
  1248      */
  1249     public boolean containsType(Type t, Type s) {
  1250         return containsType.visit(t, s);
  1252     // where
  1253         private TypeRelation containsType = new TypeRelation() {
  1255             private Type U(Type t) {
  1256                 while (t.tag == WILDCARD) {
  1257                     WildcardType w = (WildcardType)t;
  1258                     if (w.isSuperBound())
  1259                         return w.bound == null ? syms.objectType : w.bound.bound;
  1260                     else
  1261                         t = w.type;
  1263                 return t;
  1266             private Type L(Type t) {
  1267                 while (t.tag == WILDCARD) {
  1268                     WildcardType w = (WildcardType)t;
  1269                     if (w.isExtendsBound())
  1270                         return syms.botType;
  1271                     else
  1272                         t = w.type;
  1274                 return t;
  1277             public Boolean visitType(Type t, Type s) {
  1278                 if (s.isPartial())
  1279                     return containedBy(s, t);
  1280                 else
  1281                     return isSameType(t, s);
  1284 //            void debugContainsType(WildcardType t, Type s) {
  1285 //                System.err.println();
  1286 //                System.err.format(" does %s contain %s?%n", t, s);
  1287 //                System.err.format(" %s U(%s) <: U(%s) %s = %s%n",
  1288 //                                  upperBound(s), s, t, U(t),
  1289 //                                  t.isSuperBound()
  1290 //                                  || isSubtypeNoCapture(upperBound(s), U(t)));
  1291 //                System.err.format(" %s L(%s) <: L(%s) %s = %s%n",
  1292 //                                  L(t), t, s, lowerBound(s),
  1293 //                                  t.isExtendsBound()
  1294 //                                  || isSubtypeNoCapture(L(t), lowerBound(s)));
  1295 //                System.err.println();
  1296 //            }
  1298             @Override
  1299             public Boolean visitWildcardType(WildcardType t, Type s) {
  1300                 if (s.isPartial())
  1301                     return containedBy(s, t);
  1302                 else {
  1303 //                    debugContainsType(t, s);
  1304                     return isSameWildcard(t, s)
  1305                         || isCaptureOf(s, t)
  1306                         || ((t.isExtendsBound() || isSubtypeNoCapture(L(t), lowerBound(s))) &&
  1307                             (t.isSuperBound() || isSubtypeNoCapture(upperBound(s), U(t))));
  1311             @Override
  1312             public Boolean visitUndetVar(UndetVar t, Type s) {
  1313                 if (s.tag != WILDCARD)
  1314                     return isSameType(t, s);
  1315                 else
  1316                     return false;
  1319             @Override
  1320             public Boolean visitErrorType(ErrorType t, Type s) {
  1321                 return true;
  1323         };
  1325     public boolean isCaptureOf(Type s, WildcardType t) {
  1326         if (s.tag != TYPEVAR || !((TypeVar)s).isCaptured())
  1327             return false;
  1328         return isSameWildcard(t, ((CapturedType)s).wildcard);
  1331     public boolean isSameWildcard(WildcardType t, Type s) {
  1332         if (s.tag != WILDCARD)
  1333             return false;
  1334         WildcardType w = (WildcardType)s;
  1335         return w.kind == t.kind && w.type == t.type;
  1338     public boolean containsTypeEquivalent(List<Type> ts, List<Type> ss) {
  1339         while (ts.nonEmpty() && ss.nonEmpty()
  1340                && containsTypeEquivalent(ts.head, ss.head)) {
  1341             ts = ts.tail;
  1342             ss = ss.tail;
  1344         return ts.isEmpty() && ss.isEmpty();
  1346     // </editor-fold>
  1348     // <editor-fold defaultstate="collapsed" desc="isCastable">
  1349     public boolean isCastable(Type t, Type s) {
  1350         return isCastable(t, s, noWarnings);
  1353     /**
  1354      * Is t is castable to s?<br>
  1355      * s is assumed to be an erased type.<br>
  1356      * (not defined for Method and ForAll types).
  1357      */
  1358     public boolean isCastable(Type t, Type s, Warner warn) {
  1359         if (t == s)
  1360             return true;
  1362         if (t.isPrimitive() != s.isPrimitive())
  1363             return allowBoxing && (
  1364                     isConvertible(t, s, warn)
  1365                     || (allowObjectToPrimitiveCast &&
  1366                         s.isPrimitive() &&
  1367                         isSubtype(boxedClass(s).type, t)));
  1368         if (warn != warnStack.head) {
  1369             try {
  1370                 warnStack = warnStack.prepend(warn);
  1371                 checkUnsafeVarargsConversion(t, s, warn);
  1372                 return isCastable.visit(t,s);
  1373             } finally {
  1374                 warnStack = warnStack.tail;
  1376         } else {
  1377             return isCastable.visit(t,s);
  1380     // where
  1381         private TypeRelation isCastable = new TypeRelation() {
  1383             public Boolean visitType(Type t, Type s) {
  1384                 if (s.tag == ERROR)
  1385                     return true;
  1387                 switch (t.tag) {
  1388                 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
  1389                 case DOUBLE:
  1390                     return s.isNumeric();
  1391                 case BOOLEAN:
  1392                     return s.tag == BOOLEAN;
  1393                 case VOID:
  1394                     return false;
  1395                 case BOT:
  1396                     return isSubtype(t, s);
  1397                 default:
  1398                     throw new AssertionError();
  1402             @Override
  1403             public Boolean visitWildcardType(WildcardType t, Type s) {
  1404                 return isCastable(upperBound(t), s, warnStack.head);
  1407             @Override
  1408             public Boolean visitClassType(ClassType t, Type s) {
  1409                 if (s.tag == ERROR || s.tag == BOT)
  1410                     return true;
  1412                 if (s.tag == TYPEVAR) {
  1413                     if (isCastable(t, s.getUpperBound(), noWarnings)) {
  1414                         warnStack.head.warn(LintCategory.UNCHECKED);
  1415                         return true;
  1416                     } else {
  1417                         return false;
  1421                 if (t.isCompound()) {
  1422                     Warner oldWarner = warnStack.head;
  1423                     warnStack.head = noWarnings;
  1424                     if (!visit(supertype(t), s))
  1425                         return false;
  1426                     for (Type intf : interfaces(t)) {
  1427                         if (!visit(intf, s))
  1428                             return false;
  1430                     if (warnStack.head.hasLint(LintCategory.UNCHECKED))
  1431                         oldWarner.warn(LintCategory.UNCHECKED);
  1432                     return true;
  1435                 if (s.isCompound()) {
  1436                     // call recursively to reuse the above code
  1437                     return visitClassType((ClassType)s, t);
  1440                 if (s.tag == CLASS || s.tag == ARRAY) {
  1441                     boolean upcast;
  1442                     if ((upcast = isSubtype(erasure(t), erasure(s)))
  1443                         || isSubtype(erasure(s), erasure(t))) {
  1444                         if (!upcast && s.tag == ARRAY) {
  1445                             if (!isReifiable(s))
  1446                                 warnStack.head.warn(LintCategory.UNCHECKED);
  1447                             return true;
  1448                         } else if (s.isRaw()) {
  1449                             return true;
  1450                         } else if (t.isRaw()) {
  1451                             if (!isUnbounded(s))
  1452                                 warnStack.head.warn(LintCategory.UNCHECKED);
  1453                             return true;
  1455                         // Assume |a| <: |b|
  1456                         final Type a = upcast ? t : s;
  1457                         final Type b = upcast ? s : t;
  1458                         final boolean HIGH = true;
  1459                         final boolean LOW = false;
  1460                         final boolean DONT_REWRITE_TYPEVARS = false;
  1461                         Type aHigh = rewriteQuantifiers(a, HIGH, DONT_REWRITE_TYPEVARS);
  1462                         Type aLow  = rewriteQuantifiers(a, LOW,  DONT_REWRITE_TYPEVARS);
  1463                         Type bHigh = rewriteQuantifiers(b, HIGH, DONT_REWRITE_TYPEVARS);
  1464                         Type bLow  = rewriteQuantifiers(b, LOW,  DONT_REWRITE_TYPEVARS);
  1465                         Type lowSub = asSub(bLow, aLow.tsym);
  1466                         Type highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
  1467                         if (highSub == null) {
  1468                             final boolean REWRITE_TYPEVARS = true;
  1469                             aHigh = rewriteQuantifiers(a, HIGH, REWRITE_TYPEVARS);
  1470                             aLow  = rewriteQuantifiers(a, LOW,  REWRITE_TYPEVARS);
  1471                             bHigh = rewriteQuantifiers(b, HIGH, REWRITE_TYPEVARS);
  1472                             bLow  = rewriteQuantifiers(b, LOW,  REWRITE_TYPEVARS);
  1473                             lowSub = asSub(bLow, aLow.tsym);
  1474                             highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
  1476                         if (highSub != null) {
  1477                             if (!(a.tsym == highSub.tsym && a.tsym == lowSub.tsym)) {
  1478                                 Assert.error(a.tsym + " != " + highSub.tsym + " != " + lowSub.tsym);
  1480                             if (!disjointTypes(aHigh.allparams(), highSub.allparams())
  1481                                 && !disjointTypes(aHigh.allparams(), lowSub.allparams())
  1482                                 && !disjointTypes(aLow.allparams(), highSub.allparams())
  1483                                 && !disjointTypes(aLow.allparams(), lowSub.allparams())) {
  1484                                 if (upcast ? giveWarning(a, b) :
  1485                                     giveWarning(b, a))
  1486                                     warnStack.head.warn(LintCategory.UNCHECKED);
  1487                                 return true;
  1490                         if (isReifiable(s))
  1491                             return isSubtypeUnchecked(a, b);
  1492                         else
  1493                             return isSubtypeUnchecked(a, b, warnStack.head);
  1496                     // Sidecast
  1497                     if (s.tag == CLASS) {
  1498                         if ((s.tsym.flags() & INTERFACE) != 0) {
  1499                             return ((t.tsym.flags() & FINAL) == 0)
  1500                                 ? sideCast(t, s, warnStack.head)
  1501                                 : sideCastFinal(t, s, warnStack.head);
  1502                         } else if ((t.tsym.flags() & INTERFACE) != 0) {
  1503                             return ((s.tsym.flags() & FINAL) == 0)
  1504                                 ? sideCast(t, s, warnStack.head)
  1505                                 : sideCastFinal(t, s, warnStack.head);
  1506                         } else {
  1507                             // unrelated class types
  1508                             return false;
  1512                 return false;
  1515             @Override
  1516             public Boolean visitArrayType(ArrayType t, Type s) {
  1517                 switch (s.tag) {
  1518                 case ERROR:
  1519                 case BOT:
  1520                     return true;
  1521                 case TYPEVAR:
  1522                     if (isCastable(s, t, noWarnings)) {
  1523                         warnStack.head.warn(LintCategory.UNCHECKED);
  1524                         return true;
  1525                     } else {
  1526                         return false;
  1528                 case CLASS:
  1529                     return isSubtype(t, s);
  1530                 case ARRAY:
  1531                     if (elemtype(t).isPrimitive() || elemtype(s).isPrimitive()) {
  1532                         return elemtype(t).tag == elemtype(s).tag;
  1533                     } else {
  1534                         return visit(elemtype(t), elemtype(s));
  1536                 default:
  1537                     return false;
  1541             @Override
  1542             public Boolean visitTypeVar(TypeVar t, Type s) {
  1543                 switch (s.tag) {
  1544                 case ERROR:
  1545                 case BOT:
  1546                     return true;
  1547                 case TYPEVAR:
  1548                     if (isSubtype(t, s)) {
  1549                         return true;
  1550                     } else if (isCastable(t.bound, s, noWarnings)) {
  1551                         warnStack.head.warn(LintCategory.UNCHECKED);
  1552                         return true;
  1553                     } else {
  1554                         return false;
  1556                 default:
  1557                     return isCastable(t.bound, s, warnStack.head);
  1561             @Override
  1562             public Boolean visitErrorType(ErrorType t, Type s) {
  1563                 return true;
  1565         };
  1566     // </editor-fold>
  1568     // <editor-fold defaultstate="collapsed" desc="disjointTypes">
  1569     public boolean disjointTypes(List<Type> ts, List<Type> ss) {
  1570         while (ts.tail != null && ss.tail != null) {
  1571             if (disjointType(ts.head, ss.head)) return true;
  1572             ts = ts.tail;
  1573             ss = ss.tail;
  1575         return false;
  1578     /**
  1579      * Two types or wildcards are considered disjoint if it can be
  1580      * proven that no type can be contained in both. It is
  1581      * conservative in that it is allowed to say that two types are
  1582      * not disjoint, even though they actually are.
  1584      * The type {@code C<X>} is castable to {@code C<Y>} exactly if
  1585      * {@code X} and {@code Y} are not disjoint.
  1586      */
  1587     public boolean disjointType(Type t, Type s) {
  1588         return disjointType.visit(t, s);
  1590     // where
  1591         private TypeRelation disjointType = new TypeRelation() {
  1593             private Set<TypePair> cache = new HashSet<TypePair>();
  1595             public Boolean visitType(Type t, Type s) {
  1596                 if (s.tag == WILDCARD)
  1597                     return visit(s, t);
  1598                 else
  1599                     return notSoftSubtypeRecursive(t, s) || notSoftSubtypeRecursive(s, t);
  1602             private boolean isCastableRecursive(Type t, Type s) {
  1603                 TypePair pair = new TypePair(t, s);
  1604                 if (cache.add(pair)) {
  1605                     try {
  1606                         return Types.this.isCastable(t, s);
  1607                     } finally {
  1608                         cache.remove(pair);
  1610                 } else {
  1611                     return true;
  1615             private boolean notSoftSubtypeRecursive(Type t, Type s) {
  1616                 TypePair pair = new TypePair(t, s);
  1617                 if (cache.add(pair)) {
  1618                     try {
  1619                         return Types.this.notSoftSubtype(t, s);
  1620                     } finally {
  1621                         cache.remove(pair);
  1623                 } else {
  1624                     return false;
  1628             @Override
  1629             public Boolean visitWildcardType(WildcardType t, Type s) {
  1630                 if (t.isUnbound())
  1631                     return false;
  1633                 if (s.tag != WILDCARD) {
  1634                     if (t.isExtendsBound())
  1635                         return notSoftSubtypeRecursive(s, t.type);
  1636                     else // isSuperBound()
  1637                         return notSoftSubtypeRecursive(t.type, s);
  1640                 if (s.isUnbound())
  1641                     return false;
  1643                 if (t.isExtendsBound()) {
  1644                     if (s.isExtendsBound())
  1645                         return !isCastableRecursive(t.type, upperBound(s));
  1646                     else if (s.isSuperBound())
  1647                         return notSoftSubtypeRecursive(lowerBound(s), t.type);
  1648                 } else if (t.isSuperBound()) {
  1649                     if (s.isExtendsBound())
  1650                         return notSoftSubtypeRecursive(t.type, upperBound(s));
  1652                 return false;
  1654         };
  1655     // </editor-fold>
  1657     // <editor-fold defaultstate="collapsed" desc="lowerBoundArgtypes">
  1658     /**
  1659      * Returns the lower bounds of the formals of a method.
  1660      */
  1661     public List<Type> lowerBoundArgtypes(Type t) {
  1662         return lowerBounds(t.getParameterTypes());
  1664     public List<Type> lowerBounds(List<Type> ts) {
  1665         return map(ts, lowerBoundMapping);
  1667     private final Mapping lowerBoundMapping = new Mapping("lowerBound") {
  1668             public Type apply(Type t) {
  1669                 return lowerBound(t);
  1671         };
  1672     // </editor-fold>
  1674     // <editor-fold defaultstate="collapsed" desc="notSoftSubtype">
  1675     /**
  1676      * This relation answers the question: is impossible that
  1677      * something of type `t' can be a subtype of `s'? This is
  1678      * different from the question "is `t' not a subtype of `s'?"
  1679      * when type variables are involved: Integer is not a subtype of T
  1680      * where {@code <T extends Number>} but it is not true that Integer cannot
  1681      * possibly be a subtype of T.
  1682      */
  1683     public boolean notSoftSubtype(Type t, Type s) {
  1684         if (t == s) return false;
  1685         if (t.tag == TYPEVAR) {
  1686             TypeVar tv = (TypeVar) t;
  1687             return !isCastable(tv.bound,
  1688                                relaxBound(s),
  1689                                noWarnings);
  1691         if (s.tag != WILDCARD)
  1692             s = upperBound(s);
  1694         return !isSubtype(t, relaxBound(s));
  1697     private Type relaxBound(Type t) {
  1698         if (t.tag == TYPEVAR) {
  1699             while (t.tag == TYPEVAR)
  1700                 t = t.getUpperBound();
  1701             t = rewriteQuantifiers(t, true, true);
  1703         return t;
  1705     // </editor-fold>
  1707     // <editor-fold defaultstate="collapsed" desc="isReifiable">
  1708     public boolean isReifiable(Type t) {
  1709         return isReifiable.visit(t);
  1711     // where
  1712         private UnaryVisitor<Boolean> isReifiable = new UnaryVisitor<Boolean>() {
  1714             public Boolean visitType(Type t, Void ignored) {
  1715                 return true;
  1718             @Override
  1719             public Boolean visitClassType(ClassType t, Void ignored) {
  1720                 if (t.isCompound())
  1721                     return false;
  1722                 else {
  1723                     if (!t.isParameterized())
  1724                         return true;
  1726                     for (Type param : t.allparams()) {
  1727                         if (!param.isUnbound())
  1728                             return false;
  1730                     return true;
  1734             @Override
  1735             public Boolean visitArrayType(ArrayType t, Void ignored) {
  1736                 return visit(t.elemtype);
  1739             @Override
  1740             public Boolean visitTypeVar(TypeVar t, Void ignored) {
  1741                 return false;
  1743         };
  1744     // </editor-fold>
  1746     // <editor-fold defaultstate="collapsed" desc="Array Utils">
  1747     public boolean isArray(Type t) {
  1748         while (t.tag == WILDCARD)
  1749             t = upperBound(t);
  1750         return t.tag == ARRAY;
  1753     /**
  1754      * The element type of an array.
  1755      */
  1756     public Type elemtype(Type t) {
  1757         switch (t.tag) {
  1758         case WILDCARD:
  1759             return elemtype(upperBound(t));
  1760         case ARRAY:
  1761             t = t.unannotatedType();
  1762             return ((ArrayType)t).elemtype;
  1763         case FORALL:
  1764             return elemtype(((ForAll)t).qtype);
  1765         case ERROR:
  1766             return t;
  1767         default:
  1768             return null;
  1772     public Type elemtypeOrType(Type t) {
  1773         Type elemtype = elemtype(t);
  1774         return elemtype != null ?
  1775             elemtype :
  1776             t;
  1779     /**
  1780      * Mapping to take element type of an arraytype
  1781      */
  1782     private Mapping elemTypeFun = new Mapping ("elemTypeFun") {
  1783         public Type apply(Type t) { return elemtype(t); }
  1784     };
  1786     /**
  1787      * The number of dimensions of an array type.
  1788      */
  1789     public int dimensions(Type t) {
  1790         int result = 0;
  1791         while (t.tag == ARRAY) {
  1792             result++;
  1793             t = elemtype(t);
  1795         return result;
  1798     /**
  1799      * Returns an ArrayType with the component type t
  1801      * @param t The component type of the ArrayType
  1802      * @return the ArrayType for the given component
  1803      */
  1804     public ArrayType makeArrayType(Type t) {
  1805         if (t.tag == VOID ||
  1806             t.tag == PACKAGE) {
  1807             Assert.error("Type t must not be a VOID or PACKAGE type, " + t.toString());
  1809         return new ArrayType(t, syms.arrayClass);
  1811     // </editor-fold>
  1813     // <editor-fold defaultstate="collapsed" desc="asSuper">
  1814     /**
  1815      * Return the (most specific) base type of t that starts with the
  1816      * given symbol.  If none exists, return null.
  1818      * @param t a type
  1819      * @param sym a symbol
  1820      */
  1821     public Type asSuper(Type t, Symbol sym) {
  1822         return asSuper.visit(t, sym);
  1824     // where
  1825         private SimpleVisitor<Type,Symbol> asSuper = new SimpleVisitor<Type,Symbol>() {
  1827             public Type visitType(Type t, Symbol sym) {
  1828                 return null;
  1831             @Override
  1832             public Type visitClassType(ClassType t, Symbol sym) {
  1833                 if (t.tsym == sym)
  1834                     return t;
  1836                 Type st = supertype(t);
  1837                 if (st.tag == CLASS || st.tag == TYPEVAR || st.tag == ERROR) {
  1838                     Type x = asSuper(st, sym);
  1839                     if (x != null)
  1840                         return x;
  1842                 if ((sym.flags() & INTERFACE) != 0) {
  1843                     for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
  1844                         Type x = asSuper(l.head, sym);
  1845                         if (x != null)
  1846                             return x;
  1849                 return null;
  1852             @Override
  1853             public Type visitArrayType(ArrayType t, Symbol sym) {
  1854                 return isSubtype(t, sym.type) ? sym.type : null;
  1857             @Override
  1858             public Type visitTypeVar(TypeVar t, Symbol sym) {
  1859                 if (t.tsym == sym)
  1860                     return t;
  1861                 else
  1862                     return asSuper(t.bound, sym);
  1865             @Override
  1866             public Type visitErrorType(ErrorType t, Symbol sym) {
  1867                 return t;
  1869         };
  1871     /**
  1872      * Return the base type of t or any of its outer types that starts
  1873      * with the given symbol.  If none exists, return null.
  1875      * @param t a type
  1876      * @param sym a symbol
  1877      */
  1878     public Type asOuterSuper(Type t, Symbol sym) {
  1879         switch (t.tag) {
  1880         case CLASS:
  1881             do {
  1882                 Type s = asSuper(t, sym);
  1883                 if (s != null) return s;
  1884                 t = t.getEnclosingType();
  1885             } while (t.tag == CLASS);
  1886             return null;
  1887         case ARRAY:
  1888             return isSubtype(t, sym.type) ? sym.type : null;
  1889         case TYPEVAR:
  1890             return asSuper(t, sym);
  1891         case ERROR:
  1892             return t;
  1893         default:
  1894             return null;
  1898     /**
  1899      * Return the base type of t or any of its enclosing types that
  1900      * starts with the given symbol.  If none exists, return null.
  1902      * @param t a type
  1903      * @param sym a symbol
  1904      */
  1905     public Type asEnclosingSuper(Type t, Symbol sym) {
  1906         switch (t.tag) {
  1907         case CLASS:
  1908             do {
  1909                 Type s = asSuper(t, sym);
  1910                 if (s != null) return s;
  1911                 Type outer = t.getEnclosingType();
  1912                 t = (outer.tag == CLASS) ? outer :
  1913                     (t.tsym.owner.enclClass() != null) ? t.tsym.owner.enclClass().type :
  1914                     Type.noType;
  1915             } while (t.tag == CLASS);
  1916             return null;
  1917         case ARRAY:
  1918             return isSubtype(t, sym.type) ? sym.type : null;
  1919         case TYPEVAR:
  1920             return asSuper(t, sym);
  1921         case ERROR:
  1922             return t;
  1923         default:
  1924             return null;
  1927     // </editor-fold>
  1929     // <editor-fold defaultstate="collapsed" desc="memberType">
  1930     /**
  1931      * The type of given symbol, seen as a member of t.
  1933      * @param t a type
  1934      * @param sym a symbol
  1935      */
  1936     public Type memberType(Type t, Symbol sym) {
  1937         return (sym.flags() & STATIC) != 0
  1938             ? sym.type
  1939             : memberType.visit(t, sym);
  1941     // where
  1942         private SimpleVisitor<Type,Symbol> memberType = new SimpleVisitor<Type,Symbol>() {
  1944             public Type visitType(Type t, Symbol sym) {
  1945                 return sym.type;
  1948             @Override
  1949             public Type visitWildcardType(WildcardType t, Symbol sym) {
  1950                 return memberType(upperBound(t), sym);
  1953             @Override
  1954             public Type visitClassType(ClassType t, Symbol sym) {
  1955                 Symbol owner = sym.owner;
  1956                 long flags = sym.flags();
  1957                 if (((flags & STATIC) == 0) && owner.type.isParameterized()) {
  1958                     Type base = asOuterSuper(t, owner);
  1959                     //if t is an intersection type T = CT & I1 & I2 ... & In
  1960                     //its supertypes CT, I1, ... In might contain wildcards
  1961                     //so we need to go through capture conversion
  1962                     base = t.isCompound() ? capture(base) : base;
  1963                     if (base != null) {
  1964                         List<Type> ownerParams = owner.type.allparams();
  1965                         List<Type> baseParams = base.allparams();
  1966                         if (ownerParams.nonEmpty()) {
  1967                             if (baseParams.isEmpty()) {
  1968                                 // then base is a raw type
  1969                                 return erasure(sym.type);
  1970                             } else {
  1971                                 return subst(sym.type, ownerParams, baseParams);
  1976                 return sym.type;
  1979             @Override
  1980             public Type visitTypeVar(TypeVar t, Symbol sym) {
  1981                 return memberType(t.bound, sym);
  1984             @Override
  1985             public Type visitErrorType(ErrorType t, Symbol sym) {
  1986                 return t;
  1988         };
  1989     // </editor-fold>
  1991     // <editor-fold defaultstate="collapsed" desc="isAssignable">
  1992     public boolean isAssignable(Type t, Type s) {
  1993         return isAssignable(t, s, noWarnings);
  1996     /**
  1997      * Is t assignable to s?<br>
  1998      * Equivalent to subtype except for constant values and raw
  1999      * types.<br>
  2000      * (not defined for Method and ForAll types)
  2001      */
  2002     public boolean isAssignable(Type t, Type s, Warner warn) {
  2003         if (t.tag == ERROR)
  2004             return true;
  2005         if (t.tag.isSubRangeOf(INT) && t.constValue() != null) {
  2006             int value = ((Number)t.constValue()).intValue();
  2007             switch (s.tag) {
  2008             case BYTE:
  2009                 if (Byte.MIN_VALUE <= value && value <= Byte.MAX_VALUE)
  2010                     return true;
  2011                 break;
  2012             case CHAR:
  2013                 if (Character.MIN_VALUE <= value && value <= Character.MAX_VALUE)
  2014                     return true;
  2015                 break;
  2016             case SHORT:
  2017                 if (Short.MIN_VALUE <= value && value <= Short.MAX_VALUE)
  2018                     return true;
  2019                 break;
  2020             case INT:
  2021                 return true;
  2022             case CLASS:
  2023                 switch (unboxedType(s).tag) {
  2024                 case BYTE:
  2025                 case CHAR:
  2026                 case SHORT:
  2027                     return isAssignable(t, unboxedType(s), warn);
  2029                 break;
  2032         return isConvertible(t, s, warn);
  2034     // </editor-fold>
  2036     // <editor-fold defaultstate="collapsed" desc="erasure">
  2037     /**
  2038      * The erasure of t {@code |t|} -- the type that results when all
  2039      * type parameters in t are deleted.
  2040      */
  2041     public Type erasure(Type t) {
  2042         return eraseNotNeeded(t)? t : erasure(t, false);
  2044     //where
  2045     private boolean eraseNotNeeded(Type t) {
  2046         // We don't want to erase primitive types and String type as that
  2047         // operation is idempotent. Also, erasing these could result in loss
  2048         // of information such as constant values attached to such types.
  2049         return (t.isPrimitive()) || (syms.stringType.tsym == t.tsym);
  2052     private Type erasure(Type t, boolean recurse) {
  2053         if (t.isPrimitive())
  2054             return t; /* fast special case */
  2055         else
  2056             return erasure.visit(t, recurse);
  2058     // where
  2059         private SimpleVisitor<Type, Boolean> erasure = new SimpleVisitor<Type, Boolean>() {
  2060             public Type visitType(Type t, Boolean recurse) {
  2061                 if (t.isPrimitive())
  2062                     return t; /*fast special case*/
  2063                 else
  2064                     return t.map(recurse ? erasureRecFun : erasureFun);
  2067             @Override
  2068             public Type visitWildcardType(WildcardType t, Boolean recurse) {
  2069                 return erasure(upperBound(t), recurse);
  2072             @Override
  2073             public Type visitClassType(ClassType t, Boolean recurse) {
  2074                 Type erased = t.tsym.erasure(Types.this);
  2075                 if (recurse) {
  2076                     erased = new ErasedClassType(erased.getEnclosingType(),erased.tsym);
  2078                 return erased;
  2081             @Override
  2082             public Type visitTypeVar(TypeVar t, Boolean recurse) {
  2083                 return erasure(t.bound, recurse);
  2086             @Override
  2087             public Type visitErrorType(ErrorType t, Boolean recurse) {
  2088                 return t;
  2091             @Override
  2092             public Type visitAnnotatedType(AnnotatedType t, Boolean recurse) {
  2093                 Type erased = erasure(t.underlyingType, recurse);
  2094                 if (erased.getKind() == TypeKind.ANNOTATED) {
  2095                     // This can only happen when the underlying type is a
  2096                     // type variable and the upper bound of it is annotated.
  2097                     // The annotation on the type variable overrides the one
  2098                     // on the bound.
  2099                     erased = ((AnnotatedType)erased).underlyingType;
  2101                 return new AnnotatedType(t.typeAnnotations, erased);
  2103         };
  2105     private Mapping erasureFun = new Mapping ("erasure") {
  2106             public Type apply(Type t) { return erasure(t); }
  2107         };
  2109     private Mapping erasureRecFun = new Mapping ("erasureRecursive") {
  2110         public Type apply(Type t) { return erasureRecursive(t); }
  2111     };
  2113     public List<Type> erasure(List<Type> ts) {
  2114         return Type.map(ts, erasureFun);
  2117     public Type erasureRecursive(Type t) {
  2118         return erasure(t, true);
  2121     public List<Type> erasureRecursive(List<Type> ts) {
  2122         return Type.map(ts, erasureRecFun);
  2124     // </editor-fold>
  2126     // <editor-fold defaultstate="collapsed" desc="makeCompoundType">
  2127     /**
  2128      * Make a compound type from non-empty list of types
  2130      * @param bounds            the types from which the compound type is formed
  2131      * @param supertype         is objectType if all bounds are interfaces,
  2132      *                          null otherwise.
  2133      */
  2134     public Type makeCompoundType(List<Type> bounds) {
  2135         return makeCompoundType(bounds, bounds.head.tsym.isInterface());
  2137     public Type makeCompoundType(List<Type> bounds, boolean allInterfaces) {
  2138         Assert.check(bounds.nonEmpty());
  2139         Type firstExplicitBound = bounds.head;
  2140         if (allInterfaces) {
  2141             bounds = bounds.prepend(syms.objectType);
  2143         ClassSymbol bc =
  2144             new ClassSymbol(ABSTRACT|PUBLIC|SYNTHETIC|COMPOUND|ACYCLIC,
  2145                             Type.moreInfo
  2146                                 ? names.fromString(bounds.toString())
  2147                                 : names.empty,
  2148                             null,
  2149                             syms.noSymbol);
  2150         bc.type = new IntersectionClassType(bounds, bc, allInterfaces);
  2151         bc.erasure_field = (bounds.head.tag == TYPEVAR) ?
  2152                 syms.objectType : // error condition, recover
  2153                 erasure(firstExplicitBound);
  2154         bc.members_field = new Scope(bc);
  2155         return bc.type;
  2158     /**
  2159      * A convenience wrapper for {@link #makeCompoundType(List)}; the
  2160      * arguments are converted to a list and passed to the other
  2161      * method.  Note that this might cause a symbol completion.
  2162      * Hence, this version of makeCompoundType may not be called
  2163      * during a classfile read.
  2164      */
  2165     public Type makeCompoundType(Type bound1, Type bound2) {
  2166         return makeCompoundType(List.of(bound1, bound2));
  2168     // </editor-fold>
  2170     // <editor-fold defaultstate="collapsed" desc="supertype">
  2171     public Type supertype(Type t) {
  2172         return supertype.visit(t);
  2174     // where
  2175         private UnaryVisitor<Type> supertype = new UnaryVisitor<Type>() {
  2177             public Type visitType(Type t, Void ignored) {
  2178                 // A note on wildcards: there is no good way to
  2179                 // determine a supertype for a super bounded wildcard.
  2180                 return null;
  2183             @Override
  2184             public Type visitClassType(ClassType t, Void ignored) {
  2185                 if (t.supertype_field == null) {
  2186                     Type supertype = ((ClassSymbol)t.tsym).getSuperclass();
  2187                     // An interface has no superclass; its supertype is Object.
  2188                     if (t.isInterface())
  2189                         supertype = ((ClassType)t.tsym.type).supertype_field;
  2190                     if (t.supertype_field == null) {
  2191                         List<Type> actuals = classBound(t).allparams();
  2192                         List<Type> formals = t.tsym.type.allparams();
  2193                         if (t.hasErasedSupertypes()) {
  2194                             t.supertype_field = erasureRecursive(supertype);
  2195                         } else if (formals.nonEmpty()) {
  2196                             t.supertype_field = subst(supertype, formals, actuals);
  2198                         else {
  2199                             t.supertype_field = supertype;
  2203                 return t.supertype_field;
  2206             /**
  2207              * The supertype is always a class type. If the type
  2208              * variable's bounds start with a class type, this is also
  2209              * the supertype.  Otherwise, the supertype is
  2210              * java.lang.Object.
  2211              */
  2212             @Override
  2213             public Type visitTypeVar(TypeVar t, Void ignored) {
  2214                 if (t.bound.tag == TYPEVAR ||
  2215                     (!t.bound.isCompound() && !t.bound.isInterface())) {
  2216                     return t.bound;
  2217                 } else {
  2218                     return supertype(t.bound);
  2222             @Override
  2223             public Type visitArrayType(ArrayType t, Void ignored) {
  2224                 if (t.elemtype.isPrimitive() || isSameType(t.elemtype, syms.objectType))
  2225                     return arraySuperType();
  2226                 else
  2227                     return new ArrayType(supertype(t.elemtype), t.tsym);
  2230             @Override
  2231             public Type visitErrorType(ErrorType t, Void ignored) {
  2232                 return t;
  2234         };
  2235     // </editor-fold>
  2237     // <editor-fold defaultstate="collapsed" desc="interfaces">
  2238     /**
  2239      * Return the interfaces implemented by this class.
  2240      */
  2241     public List<Type> interfaces(Type t) {
  2242         return interfaces.visit(t);
  2244     // where
  2245         private UnaryVisitor<List<Type>> interfaces = new UnaryVisitor<List<Type>>() {
  2247             public List<Type> visitType(Type t, Void ignored) {
  2248                 return List.nil();
  2251             @Override
  2252             public List<Type> visitClassType(ClassType t, Void ignored) {
  2253                 if (t.interfaces_field == null) {
  2254                     List<Type> interfaces = ((ClassSymbol)t.tsym).getInterfaces();
  2255                     if (t.interfaces_field == null) {
  2256                         // If t.interfaces_field is null, then t must
  2257                         // be a parameterized type (not to be confused
  2258                         // with a generic type declaration).
  2259                         // Terminology:
  2260                         //    Parameterized type: List<String>
  2261                         //    Generic type declaration: class List<E> { ... }
  2262                         // So t corresponds to List<String> and
  2263                         // t.tsym.type corresponds to List<E>.
  2264                         // The reason t must be parameterized type is
  2265                         // that completion will happen as a side
  2266                         // effect of calling
  2267                         // ClassSymbol.getInterfaces.  Since
  2268                         // t.interfaces_field is null after
  2269                         // completion, we can assume that t is not the
  2270                         // type of a class/interface declaration.
  2271                         Assert.check(t != t.tsym.type, t);
  2272                         List<Type> actuals = t.allparams();
  2273                         List<Type> formals = t.tsym.type.allparams();
  2274                         if (t.hasErasedSupertypes()) {
  2275                             t.interfaces_field = erasureRecursive(interfaces);
  2276                         } else if (formals.nonEmpty()) {
  2277                             t.interfaces_field =
  2278                                 upperBounds(subst(interfaces, formals, actuals));
  2280                         else {
  2281                             t.interfaces_field = interfaces;
  2285                 return t.interfaces_field;
  2288             @Override
  2289             public List<Type> visitTypeVar(TypeVar t, Void ignored) {
  2290                 if (t.bound.isCompound())
  2291                     return interfaces(t.bound);
  2293                 if (t.bound.isInterface())
  2294                     return List.of(t.bound);
  2296                 return List.nil();
  2298         };
  2300     public boolean isDirectSuperInterface(TypeSymbol isym, TypeSymbol origin) {
  2301         for (Type i2 : interfaces(origin.type)) {
  2302             if (isym == i2.tsym) return true;
  2304         return false;
  2306     // </editor-fold>
  2308     // <editor-fold defaultstate="collapsed" desc="isDerivedRaw">
  2309     Map<Type,Boolean> isDerivedRawCache = new HashMap<Type,Boolean>();
  2311     public boolean isDerivedRaw(Type t) {
  2312         Boolean result = isDerivedRawCache.get(t);
  2313         if (result == null) {
  2314             result = isDerivedRawInternal(t);
  2315             isDerivedRawCache.put(t, result);
  2317         return result;
  2320     public boolean isDerivedRawInternal(Type t) {
  2321         if (t.isErroneous())
  2322             return false;
  2323         return
  2324             t.isRaw() ||
  2325             supertype(t) != null && isDerivedRaw(supertype(t)) ||
  2326             isDerivedRaw(interfaces(t));
  2329     public boolean isDerivedRaw(List<Type> ts) {
  2330         List<Type> l = ts;
  2331         while (l.nonEmpty() && !isDerivedRaw(l.head)) l = l.tail;
  2332         return l.nonEmpty();
  2334     // </editor-fold>
  2336     // <editor-fold defaultstate="collapsed" desc="setBounds">
  2337     /**
  2338      * Set the bounds field of the given type variable to reflect a
  2339      * (possibly multiple) list of bounds.
  2340      * @param t                 a type variable
  2341      * @param bounds            the bounds, must be nonempty
  2342      * @param supertype         is objectType if all bounds are interfaces,
  2343      *                          null otherwise.
  2344      */
  2345     public void setBounds(TypeVar t, List<Type> bounds) {
  2346         setBounds(t, bounds, bounds.head.tsym.isInterface());
  2349     /**
  2350      * Same as {@link #setBounds(Type.TypeVar,List,Type)}, except that
  2351      * third parameter is computed directly, as follows: if all
  2352      * all bounds are interface types, the computed supertype is Object,
  2353      * otherwise the supertype is simply left null (in this case, the supertype
  2354      * is assumed to be the head of the bound list passed as second argument).
  2355      * Note that this check might cause a symbol completion. Hence, this version of
  2356      * setBounds may not be called during a classfile read.
  2357      */
  2358     public void setBounds(TypeVar t, List<Type> bounds, boolean allInterfaces) {
  2359         t.bound = bounds.tail.isEmpty() ?
  2360                 bounds.head :
  2361                 makeCompoundType(bounds, allInterfaces);
  2362         t.rank_field = -1;
  2364     // </editor-fold>
  2366     // <editor-fold defaultstate="collapsed" desc="getBounds">
  2367     /**
  2368      * Return list of bounds of the given type variable.
  2369      */
  2370     public List<Type> getBounds(TypeVar t) {
  2371         if (t.bound.hasTag(NONE))
  2372             return List.nil();
  2373         else if (t.bound.isErroneous() || !t.bound.isCompound())
  2374             return List.of(t.bound);
  2375         else if ((erasure(t).tsym.flags() & INTERFACE) == 0)
  2376             return interfaces(t).prepend(supertype(t));
  2377         else
  2378             // No superclass was given in bounds.
  2379             // In this case, supertype is Object, erasure is first interface.
  2380             return interfaces(t);
  2382     // </editor-fold>
  2384     // <editor-fold defaultstate="collapsed" desc="classBound">
  2385     /**
  2386      * If the given type is a (possibly selected) type variable,
  2387      * return the bounding class of this type, otherwise return the
  2388      * type itself.
  2389      */
  2390     public Type classBound(Type t) {
  2391         return classBound.visit(t);
  2393     // where
  2394         private UnaryVisitor<Type> classBound = new UnaryVisitor<Type>() {
  2396             public Type visitType(Type t, Void ignored) {
  2397                 return t;
  2400             @Override
  2401             public Type visitClassType(ClassType t, Void ignored) {
  2402                 Type outer1 = classBound(t.getEnclosingType());
  2403                 if (outer1 != t.getEnclosingType())
  2404                     return new ClassType(outer1, t.getTypeArguments(), t.tsym);
  2405                 else
  2406                     return t;
  2409             @Override
  2410             public Type visitTypeVar(TypeVar t, Void ignored) {
  2411                 return classBound(supertype(t));
  2414             @Override
  2415             public Type visitErrorType(ErrorType t, Void ignored) {
  2416                 return t;
  2418         };
  2419     // </editor-fold>
  2421     // <editor-fold defaultstate="collapsed" desc="sub signature / override equivalence">
  2422     /**
  2423      * Returns true iff the first signature is a <em>sub
  2424      * signature</em> of the other.  This is <b>not</b> an equivalence
  2425      * relation.
  2427      * @jls section 8.4.2.
  2428      * @see #overrideEquivalent(Type t, Type s)
  2429      * @param t first signature (possibly raw).
  2430      * @param s second signature (could be subjected to erasure).
  2431      * @return true if t is a sub signature of s.
  2432      */
  2433     public boolean isSubSignature(Type t, Type s) {
  2434         return isSubSignature(t, s, true);
  2437     public boolean isSubSignature(Type t, Type s, boolean strict) {
  2438         return hasSameArgs(t, s, strict) || hasSameArgs(t, erasure(s), strict);
  2441     /**
  2442      * Returns true iff these signatures are related by <em>override
  2443      * equivalence</em>.  This is the natural extension of
  2444      * isSubSignature to an equivalence relation.
  2446      * @jls section 8.4.2.
  2447      * @see #isSubSignature(Type t, Type s)
  2448      * @param t a signature (possible raw, could be subjected to
  2449      * erasure).
  2450      * @param s a signature (possible raw, could be subjected to
  2451      * erasure).
  2452      * @return true if either argument is a sub signature of the other.
  2453      */
  2454     public boolean overrideEquivalent(Type t, Type s) {
  2455         return hasSameArgs(t, s) ||
  2456             hasSameArgs(t, erasure(s)) || hasSameArgs(erasure(t), s);
  2459     public boolean overridesObjectMethod(TypeSymbol origin, Symbol msym) {
  2460         for (Scope.Entry e = syms.objectType.tsym.members().lookup(msym.name) ; e.scope != null ; e = e.next()) {
  2461             if (msym.overrides(e.sym, origin, Types.this, true)) {
  2462                 return true;
  2465         return false;
  2468     // <editor-fold defaultstate="collapsed" desc="Determining method implementation in given site">
  2469     class ImplementationCache {
  2471         private WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>> _map =
  2472                 new WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>>();
  2474         class Entry {
  2475             final MethodSymbol cachedImpl;
  2476             final Filter<Symbol> implFilter;
  2477             final boolean checkResult;
  2478             final int prevMark;
  2480             public Entry(MethodSymbol cachedImpl,
  2481                     Filter<Symbol> scopeFilter,
  2482                     boolean checkResult,
  2483                     int prevMark) {
  2484                 this.cachedImpl = cachedImpl;
  2485                 this.implFilter = scopeFilter;
  2486                 this.checkResult = checkResult;
  2487                 this.prevMark = prevMark;
  2490             boolean matches(Filter<Symbol> scopeFilter, boolean checkResult, int mark) {
  2491                 return this.implFilter == scopeFilter &&
  2492                         this.checkResult == checkResult &&
  2493                         this.prevMark == mark;
  2497         MethodSymbol get(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
  2498             SoftReference<Map<TypeSymbol, Entry>> ref_cache = _map.get(ms);
  2499             Map<TypeSymbol, Entry> cache = ref_cache != null ? ref_cache.get() : null;
  2500             if (cache == null) {
  2501                 cache = new HashMap<TypeSymbol, Entry>();
  2502                 _map.put(ms, new SoftReference<Map<TypeSymbol, Entry>>(cache));
  2504             Entry e = cache.get(origin);
  2505             CompoundScope members = membersClosure(origin.type, true);
  2506             if (e == null ||
  2507                     !e.matches(implFilter, checkResult, members.getMark())) {
  2508                 MethodSymbol impl = implementationInternal(ms, origin, checkResult, implFilter);
  2509                 cache.put(origin, new Entry(impl, implFilter, checkResult, members.getMark()));
  2510                 return impl;
  2512             else {
  2513                 return e.cachedImpl;
  2517         private MethodSymbol implementationInternal(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
  2518             for (Type t = origin.type; t.tag == CLASS || t.tag == TYPEVAR; t = supertype(t)) {
  2519                 while (t.tag == TYPEVAR)
  2520                     t = t.getUpperBound();
  2521                 TypeSymbol c = t.tsym;
  2522                 for (Scope.Entry e = c.members().lookup(ms.name, implFilter);
  2523                      e.scope != null;
  2524                      e = e.next(implFilter)) {
  2525                     if (e.sym != null &&
  2526                              e.sym.overrides(ms, origin, Types.this, checkResult))
  2527                         return (MethodSymbol)e.sym;
  2530             return null;
  2534     private ImplementationCache implCache = new ImplementationCache();
  2536     public MethodSymbol implementation(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) {
  2537         return implCache.get(ms, origin, checkResult, implFilter);
  2539     // </editor-fold>
  2541     // <editor-fold defaultstate="collapsed" desc="compute transitive closure of all members in given site">
  2542     class MembersClosureCache extends SimpleVisitor<CompoundScope, Boolean> {
  2544         private WeakHashMap<TypeSymbol, Entry> _map =
  2545                 new WeakHashMap<TypeSymbol, Entry>();
  2547         class Entry {
  2548             final boolean skipInterfaces;
  2549             final CompoundScope compoundScope;
  2551             public Entry(boolean skipInterfaces, CompoundScope compoundScope) {
  2552                 this.skipInterfaces = skipInterfaces;
  2553                 this.compoundScope = compoundScope;
  2556             boolean matches(boolean skipInterfaces) {
  2557                 return this.skipInterfaces == skipInterfaces;
  2561         List<TypeSymbol> seenTypes = List.nil();
  2563         /** members closure visitor methods **/
  2565         public CompoundScope visitType(Type t, Boolean skipInterface) {
  2566             return null;
  2569         @Override
  2570         public CompoundScope visitClassType(ClassType t, Boolean skipInterface) {
  2571             if (seenTypes.contains(t.tsym)) {
  2572                 //this is possible when an interface is implemented in multiple
  2573                 //superclasses, or when a classs hierarchy is circular - in such
  2574                 //cases we don't need to recurse (empty scope is returned)
  2575                 return new CompoundScope(t.tsym);
  2577             try {
  2578                 seenTypes = seenTypes.prepend(t.tsym);
  2579                 ClassSymbol csym = (ClassSymbol)t.tsym;
  2580                 Entry e = _map.get(csym);
  2581                 if (e == null || !e.matches(skipInterface)) {
  2582                     CompoundScope membersClosure = new CompoundScope(csym);
  2583                     if (!skipInterface) {
  2584                         for (Type i : interfaces(t)) {
  2585                             membersClosure.addSubScope(visit(i, skipInterface));
  2588                     membersClosure.addSubScope(visit(supertype(t), skipInterface));
  2589                     membersClosure.addSubScope(csym.members());
  2590                     e = new Entry(skipInterface, membersClosure);
  2591                     _map.put(csym, e);
  2593                 return e.compoundScope;
  2595             finally {
  2596                 seenTypes = seenTypes.tail;
  2600         @Override
  2601         public CompoundScope visitTypeVar(TypeVar t, Boolean skipInterface) {
  2602             return visit(t.getUpperBound(), skipInterface);
  2606     private MembersClosureCache membersCache = new MembersClosureCache();
  2608     public CompoundScope membersClosure(Type site, boolean skipInterface) {
  2609         return membersCache.visit(site, skipInterface);
  2611     // </editor-fold>
  2614     //where
  2615     public List<MethodSymbol> interfaceCandidates(Type site, MethodSymbol ms) {
  2616         Filter<Symbol> filter = new MethodFilter(ms, site);
  2617         List<MethodSymbol> candidates = List.nil();
  2618         for (Symbol s : membersClosure(site, false).getElements(filter)) {
  2619             if (!site.tsym.isInterface() && !s.owner.isInterface()) {
  2620                 return List.of((MethodSymbol)s);
  2621             } else if (!candidates.contains(s)) {
  2622                 candidates = candidates.prepend((MethodSymbol)s);
  2625         return prune(candidates);
  2628     public List<MethodSymbol> prune(List<MethodSymbol> methods) {
  2629         ListBuffer<MethodSymbol> methodsMin = ListBuffer.lb();
  2630         for (MethodSymbol m1 : methods) {
  2631             boolean isMin_m1 = true;
  2632             for (MethodSymbol m2 : methods) {
  2633                 if (m1 == m2) continue;
  2634                 if (m2.owner != m1.owner &&
  2635                         asSuper(m2.owner.type, m1.owner) != null) {
  2636                     isMin_m1 = false;
  2637                     break;
  2640             if (isMin_m1)
  2641                 methodsMin.append(m1);
  2643         return methodsMin.toList();
  2645     // where
  2646             private class MethodFilter implements Filter<Symbol> {
  2648                 Symbol msym;
  2649                 Type site;
  2651                 MethodFilter(Symbol msym, Type site) {
  2652                     this.msym = msym;
  2653                     this.site = site;
  2656                 public boolean accepts(Symbol s) {
  2657                     return s.kind == Kinds.MTH &&
  2658                             s.name == msym.name &&
  2659                             s.isInheritedIn(site.tsym, Types.this) &&
  2660                             overrideEquivalent(memberType(site, s), memberType(site, msym));
  2662             };
  2663     // </editor-fold>
  2665     /**
  2666      * Does t have the same arguments as s?  It is assumed that both
  2667      * types are (possibly polymorphic) method types.  Monomorphic
  2668      * method types "have the same arguments", if their argument lists
  2669      * are equal.  Polymorphic method types "have the same arguments",
  2670      * if they have the same arguments after renaming all type
  2671      * variables of one to corresponding type variables in the other,
  2672      * where correspondence is by position in the type parameter list.
  2673      */
  2674     public boolean hasSameArgs(Type t, Type s) {
  2675         return hasSameArgs(t, s, true);
  2678     public boolean hasSameArgs(Type t, Type s, boolean strict) {
  2679         return hasSameArgs(t, s, strict ? hasSameArgs_strict : hasSameArgs_nonstrict);
  2682     private boolean hasSameArgs(Type t, Type s, TypeRelation hasSameArgs) {
  2683         return hasSameArgs.visit(t, s);
  2685     // where
  2686         private class HasSameArgs extends TypeRelation {
  2688             boolean strict;
  2690             public HasSameArgs(boolean strict) {
  2691                 this.strict = strict;
  2694             public Boolean visitType(Type t, Type s) {
  2695                 throw new AssertionError();
  2698             @Override
  2699             public Boolean visitMethodType(MethodType t, Type s) {
  2700                 return s.tag == METHOD
  2701                     && containsTypeEquivalent(t.argtypes, s.getParameterTypes());
  2704             @Override
  2705             public Boolean visitForAll(ForAll t, Type s) {
  2706                 if (s.tag != FORALL)
  2707                     return strict ? false : visitMethodType(t.asMethodType(), s);
  2709                 ForAll forAll = (ForAll)s;
  2710                 return hasSameBounds(t, forAll)
  2711                     && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
  2714             @Override
  2715             public Boolean visitErrorType(ErrorType t, Type s) {
  2716                 return false;
  2718         };
  2720         TypeRelation hasSameArgs_strict = new HasSameArgs(true);
  2721         TypeRelation hasSameArgs_nonstrict = new HasSameArgs(false);
  2723     // </editor-fold>
  2725     // <editor-fold defaultstate="collapsed" desc="subst">
  2726     public List<Type> subst(List<Type> ts,
  2727                             List<Type> from,
  2728                             List<Type> to) {
  2729         return new Subst(from, to).subst(ts);
  2732     /**
  2733      * Substitute all occurrences of a type in `from' with the
  2734      * corresponding type in `to' in 't'. Match lists `from' and `to'
  2735      * from the right: If lists have different length, discard leading
  2736      * elements of the longer list.
  2737      */
  2738     public Type subst(Type t, List<Type> from, List<Type> to) {
  2739         return new Subst(from, to).subst(t);
  2742     private class Subst extends UnaryVisitor<Type> {
  2743         List<Type> from;
  2744         List<Type> to;
  2746         public Subst(List<Type> from, List<Type> to) {
  2747             int fromLength = from.length();
  2748             int toLength = to.length();
  2749             while (fromLength > toLength) {
  2750                 fromLength--;
  2751                 from = from.tail;
  2753             while (fromLength < toLength) {
  2754                 toLength--;
  2755                 to = to.tail;
  2757             this.from = from;
  2758             this.to = to;
  2761         Type subst(Type t) {
  2762             if (from.tail == null)
  2763                 return t;
  2764             else
  2765                 return visit(t);
  2768         List<Type> subst(List<Type> ts) {
  2769             if (from.tail == null)
  2770                 return ts;
  2771             boolean wild = false;
  2772             if (ts.nonEmpty() && from.nonEmpty()) {
  2773                 Type head1 = subst(ts.head);
  2774                 List<Type> tail1 = subst(ts.tail);
  2775                 if (head1 != ts.head || tail1 != ts.tail)
  2776                     return tail1.prepend(head1);
  2778             return ts;
  2781         public Type visitType(Type t, Void ignored) {
  2782             return t;
  2785         @Override
  2786         public Type visitMethodType(MethodType t, Void ignored) {
  2787             List<Type> argtypes = subst(t.argtypes);
  2788             Type restype = subst(t.restype);
  2789             List<Type> thrown = subst(t.thrown);
  2790             if (argtypes == t.argtypes &&
  2791                 restype == t.restype &&
  2792                 thrown == t.thrown)
  2793                 return t;
  2794             else
  2795                 return new MethodType(argtypes, restype, thrown, t.tsym);
  2798         @Override
  2799         public Type visitTypeVar(TypeVar t, Void ignored) {
  2800             for (List<Type> from = this.from, to = this.to;
  2801                  from.nonEmpty();
  2802                  from = from.tail, to = to.tail) {
  2803                 if (t == from.head) {
  2804                     return to.head.withTypeVar(t);
  2807             return t;
  2810         @Override
  2811         public Type visitClassType(ClassType t, Void ignored) {
  2812             if (!t.isCompound()) {
  2813                 List<Type> typarams = t.getTypeArguments();
  2814                 List<Type> typarams1 = subst(typarams);
  2815                 Type outer = t.getEnclosingType();
  2816                 Type outer1 = subst(outer);
  2817                 if (typarams1 == typarams && outer1 == outer)
  2818                     return t;
  2819                 else
  2820                     return new ClassType(outer1, typarams1, t.tsym);
  2821             } else {
  2822                 Type st = subst(supertype(t));
  2823                 List<Type> is = upperBounds(subst(interfaces(t)));
  2824                 if (st == supertype(t) && is == interfaces(t))
  2825                     return t;
  2826                 else
  2827                     return makeCompoundType(is.prepend(st));
  2831         @Override
  2832         public Type visitWildcardType(WildcardType t, Void ignored) {
  2833             Type bound = t.type;
  2834             if (t.kind != BoundKind.UNBOUND)
  2835                 bound = subst(bound);
  2836             if (bound == t.type) {
  2837                 return t;
  2838             } else {
  2839                 if (t.isExtendsBound() && bound.isExtendsBound())
  2840                     bound = upperBound(bound);
  2841                 return new WildcardType(bound, t.kind, syms.boundClass, t.bound);
  2845         @Override
  2846         public Type visitArrayType(ArrayType t, Void ignored) {
  2847             Type elemtype = subst(t.elemtype);
  2848             if (elemtype == t.elemtype)
  2849                 return t;
  2850             else
  2851                 return new ArrayType(upperBound(elemtype), t.tsym);
  2854         @Override
  2855         public Type visitForAll(ForAll t, Void ignored) {
  2856             if (Type.containsAny(to, t.tvars)) {
  2857                 //perform alpha-renaming of free-variables in 't'
  2858                 //if 'to' types contain variables that are free in 't'
  2859                 List<Type> freevars = newInstances(t.tvars);
  2860                 t = new ForAll(freevars,
  2861                         Types.this.subst(t.qtype, t.tvars, freevars));
  2863             List<Type> tvars1 = substBounds(t.tvars, from, to);
  2864             Type qtype1 = subst(t.qtype);
  2865             if (tvars1 == t.tvars && qtype1 == t.qtype) {
  2866                 return t;
  2867             } else if (tvars1 == t.tvars) {
  2868                 return new ForAll(tvars1, qtype1);
  2869             } else {
  2870                 return new ForAll(tvars1, Types.this.subst(qtype1, t.tvars, tvars1));
  2874         @Override
  2875         public Type visitErrorType(ErrorType t, Void ignored) {
  2876             return t;
  2880     public List<Type> substBounds(List<Type> tvars,
  2881                                   List<Type> from,
  2882                                   List<Type> to) {
  2883         if (tvars.isEmpty())
  2884             return tvars;
  2885         ListBuffer<Type> newBoundsBuf = lb();
  2886         boolean changed = false;
  2887         // calculate new bounds
  2888         for (Type t : tvars) {
  2889             TypeVar tv = (TypeVar) t;
  2890             Type bound = subst(tv.bound, from, to);
  2891             if (bound != tv.bound)
  2892                 changed = true;
  2893             newBoundsBuf.append(bound);
  2895         if (!changed)
  2896             return tvars;
  2897         ListBuffer<Type> newTvars = lb();
  2898         // create new type variables without bounds
  2899         for (Type t : tvars) {
  2900             newTvars.append(new TypeVar(t.tsym, null, syms.botType));
  2902         // the new bounds should use the new type variables in place
  2903         // of the old
  2904         List<Type> newBounds = newBoundsBuf.toList();
  2905         from = tvars;
  2906         to = newTvars.toList();
  2907         for (; !newBounds.isEmpty(); newBounds = newBounds.tail) {
  2908             newBounds.head = subst(newBounds.head, from, to);
  2910         newBounds = newBoundsBuf.toList();
  2911         // set the bounds of new type variables to the new bounds
  2912         for (Type t : newTvars.toList()) {
  2913             TypeVar tv = (TypeVar) t;
  2914             tv.bound = newBounds.head;
  2915             newBounds = newBounds.tail;
  2917         return newTvars.toList();
  2920     public TypeVar substBound(TypeVar t, List<Type> from, List<Type> to) {
  2921         Type bound1 = subst(t.bound, from, to);
  2922         if (bound1 == t.bound)
  2923             return t;
  2924         else {
  2925             // create new type variable without bounds
  2926             TypeVar tv = new TypeVar(t.tsym, null, syms.botType);
  2927             // the new bound should use the new type variable in place
  2928             // of the old
  2929             tv.bound = subst(bound1, List.<Type>of(t), List.<Type>of(tv));
  2930             return tv;
  2933     // </editor-fold>
  2935     // <editor-fold defaultstate="collapsed" desc="hasSameBounds">
  2936     /**
  2937      * Does t have the same bounds for quantified variables as s?
  2938      */
  2939     boolean hasSameBounds(ForAll t, ForAll s) {
  2940         List<Type> l1 = t.tvars;
  2941         List<Type> l2 = s.tvars;
  2942         while (l1.nonEmpty() && l2.nonEmpty() &&
  2943                isSameType(l1.head.getUpperBound(),
  2944                           subst(l2.head.getUpperBound(),
  2945                                 s.tvars,
  2946                                 t.tvars))) {
  2947             l1 = l1.tail;
  2948             l2 = l2.tail;
  2950         return l1.isEmpty() && l2.isEmpty();
  2952     // </editor-fold>
  2954     // <editor-fold defaultstate="collapsed" desc="newInstances">
  2955     /** Create new vector of type variables from list of variables
  2956      *  changing all recursive bounds from old to new list.
  2957      */
  2958     public List<Type> newInstances(List<Type> tvars) {
  2959         List<Type> tvars1 = Type.map(tvars, newInstanceFun);
  2960         for (List<Type> l = tvars1; l.nonEmpty(); l = l.tail) {
  2961             TypeVar tv = (TypeVar) l.head;
  2962             tv.bound = subst(tv.bound, tvars, tvars1);
  2964         return tvars1;
  2966     private static final Mapping newInstanceFun = new Mapping("newInstanceFun") {
  2967             public Type apply(Type t) { return new TypeVar(t.tsym, t.getUpperBound(), t.getLowerBound()); }
  2968         };
  2969     // </editor-fold>
  2971     public Type createMethodTypeWithParameters(Type original, List<Type> newParams) {
  2972         return original.accept(methodWithParameters, newParams);
  2974     // where
  2975         private final MapVisitor<List<Type>> methodWithParameters = new MapVisitor<List<Type>>() {
  2976             public Type visitType(Type t, List<Type> newParams) {
  2977                 throw new IllegalArgumentException("Not a method type: " + t);
  2979             public Type visitMethodType(MethodType t, List<Type> newParams) {
  2980                 return new MethodType(newParams, t.restype, t.thrown, t.tsym);
  2982             public Type visitForAll(ForAll t, List<Type> newParams) {
  2983                 return new ForAll(t.tvars, t.qtype.accept(this, newParams));
  2985         };
  2987     public Type createMethodTypeWithThrown(Type original, List<Type> newThrown) {
  2988         return original.accept(methodWithThrown, newThrown);
  2990     // where
  2991         private final MapVisitor<List<Type>> methodWithThrown = new MapVisitor<List<Type>>() {
  2992             public Type visitType(Type t, List<Type> newThrown) {
  2993                 throw new IllegalArgumentException("Not a method type: " + t);
  2995             public Type visitMethodType(MethodType t, List<Type> newThrown) {
  2996                 return new MethodType(t.argtypes, t.restype, newThrown, t.tsym);
  2998             public Type visitForAll(ForAll t, List<Type> newThrown) {
  2999                 return new ForAll(t.tvars, t.qtype.accept(this, newThrown));
  3001         };
  3003     public Type createMethodTypeWithReturn(Type original, Type newReturn) {
  3004         return original.accept(methodWithReturn, newReturn);
  3006     // where
  3007         private final MapVisitor<Type> methodWithReturn = new MapVisitor<Type>() {
  3008             public Type visitType(Type t, Type newReturn) {
  3009                 throw new IllegalArgumentException("Not a method type: " + t);
  3011             public Type visitMethodType(MethodType t, Type newReturn) {
  3012                 return new MethodType(t.argtypes, newReturn, t.thrown, t.tsym);
  3014             public Type visitForAll(ForAll t, Type newReturn) {
  3015                 return new ForAll(t.tvars, t.qtype.accept(this, newReturn));
  3017         };
  3019     // <editor-fold defaultstate="collapsed" desc="createErrorType">
  3020     public Type createErrorType(Type originalType) {
  3021         return new ErrorType(originalType, syms.errSymbol);
  3024     public Type createErrorType(ClassSymbol c, Type originalType) {
  3025         return new ErrorType(c, originalType);
  3028     public Type createErrorType(Name name, TypeSymbol container, Type originalType) {
  3029         return new ErrorType(name, container, originalType);
  3031     // </editor-fold>
  3033     // <editor-fold defaultstate="collapsed" desc="rank">
  3034     /**
  3035      * The rank of a class is the length of the longest path between
  3036      * the class and java.lang.Object in the class inheritance
  3037      * graph. Undefined for all but reference types.
  3038      */
  3039     public int rank(Type t) {
  3040         t = t.unannotatedType();
  3041         switch(t.tag) {
  3042         case CLASS: {
  3043             ClassType cls = (ClassType)t;
  3044             if (cls.rank_field < 0) {
  3045                 Name fullname = cls.tsym.getQualifiedName();
  3046                 if (fullname == names.java_lang_Object)
  3047                     cls.rank_field = 0;
  3048                 else {
  3049                     int r = rank(supertype(cls));
  3050                     for (List<Type> l = interfaces(cls);
  3051                          l.nonEmpty();
  3052                          l = l.tail) {
  3053                         if (rank(l.head) > r)
  3054                             r = rank(l.head);
  3056                     cls.rank_field = r + 1;
  3059             return cls.rank_field;
  3061         case TYPEVAR: {
  3062             TypeVar tvar = (TypeVar)t;
  3063             if (tvar.rank_field < 0) {
  3064                 int r = rank(supertype(tvar));
  3065                 for (List<Type> l = interfaces(tvar);
  3066                      l.nonEmpty();
  3067                      l = l.tail) {
  3068                     if (rank(l.head) > r) r = rank(l.head);
  3070                 tvar.rank_field = r + 1;
  3072             return tvar.rank_field;
  3074         case ERROR:
  3075             return 0;
  3076         default:
  3077             throw new AssertionError();
  3080     // </editor-fold>
  3082     /**
  3083      * Helper method for generating a string representation of a given type
  3084      * accordingly to a given locale
  3085      */
  3086     public String toString(Type t, Locale locale) {
  3087         return Printer.createStandardPrinter(messages).visit(t, locale);
  3090     /**
  3091      * Helper method for generating a string representation of a given type
  3092      * accordingly to a given locale
  3093      */
  3094     public String toString(Symbol t, Locale locale) {
  3095         return Printer.createStandardPrinter(messages).visit(t, locale);
  3098     // <editor-fold defaultstate="collapsed" desc="toString">
  3099     /**
  3100      * This toString is slightly more descriptive than the one on Type.
  3102      * @deprecated Types.toString(Type t, Locale l) provides better support
  3103      * for localization
  3104      */
  3105     @Deprecated
  3106     public String toString(Type t) {
  3107         if (t.tag == FORALL) {
  3108             ForAll forAll = (ForAll)t;
  3109             return typaramsString(forAll.tvars) + forAll.qtype;
  3111         return "" + t;
  3113     // where
  3114         private String typaramsString(List<Type> tvars) {
  3115             StringBuilder s = new StringBuilder();
  3116             s.append('<');
  3117             boolean first = true;
  3118             for (Type t : tvars) {
  3119                 if (!first) s.append(", ");
  3120                 first = false;
  3121                 appendTyparamString(((TypeVar)t), s);
  3123             s.append('>');
  3124             return s.toString();
  3126         private void appendTyparamString(TypeVar t, StringBuilder buf) {
  3127             buf.append(t);
  3128             if (t.bound == null ||
  3129                 t.bound.tsym.getQualifiedName() == names.java_lang_Object)
  3130                 return;
  3131             buf.append(" extends "); // Java syntax; no need for i18n
  3132             Type bound = t.bound;
  3133             if (!bound.isCompound()) {
  3134                 buf.append(bound);
  3135             } else if ((erasure(t).tsym.flags() & INTERFACE) == 0) {
  3136                 buf.append(supertype(t));
  3137                 for (Type intf : interfaces(t)) {
  3138                     buf.append('&');
  3139                     buf.append(intf);
  3141             } else {
  3142                 // No superclass was given in bounds.
  3143                 // In this case, supertype is Object, erasure is first interface.
  3144                 boolean first = true;
  3145                 for (Type intf : interfaces(t)) {
  3146                     if (!first) buf.append('&');
  3147                     first = false;
  3148                     buf.append(intf);
  3152     // </editor-fold>
  3154     // <editor-fold defaultstate="collapsed" desc="Determining least upper bounds of types">
  3155     /**
  3156      * A cache for closures.
  3158      * <p>A closure is a list of all the supertypes and interfaces of
  3159      * a class or interface type, ordered by ClassSymbol.precedes
  3160      * (that is, subclasses come first, arbitrary but fixed
  3161      * otherwise).
  3162      */
  3163     private Map<Type,List<Type>> closureCache = new HashMap<Type,List<Type>>();
  3165     /**
  3166      * Returns the closure of a class or interface type.
  3167      */
  3168     public List<Type> closure(Type t) {
  3169         List<Type> cl = closureCache.get(t);
  3170         if (cl == null) {
  3171             Type st = supertype(t);
  3172             if (!t.isCompound()) {
  3173                 if (st.tag == CLASS) {
  3174                     cl = insert(closure(st), t);
  3175                 } else if (st.tag == TYPEVAR) {
  3176                     cl = closure(st).prepend(t);
  3177                 } else {
  3178                     cl = List.of(t);
  3180             } else {
  3181                 cl = closure(supertype(t));
  3183             for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail)
  3184                 cl = union(cl, closure(l.head));
  3185             closureCache.put(t, cl);
  3187         return cl;
  3190     /**
  3191      * Insert a type in a closure
  3192      */
  3193     public List<Type> insert(List<Type> cl, Type t) {
  3194         if (cl.isEmpty() || t.tsym.precedes(cl.head.tsym, this)) {
  3195             return cl.prepend(t);
  3196         } else if (cl.head.tsym.precedes(t.tsym, this)) {
  3197             return insert(cl.tail, t).prepend(cl.head);
  3198         } else {
  3199             return cl;
  3203     /**
  3204      * Form the union of two closures
  3205      */
  3206     public List<Type> union(List<Type> cl1, List<Type> cl2) {
  3207         if (cl1.isEmpty()) {
  3208             return cl2;
  3209         } else if (cl2.isEmpty()) {
  3210             return cl1;
  3211         } else if (cl1.head.tsym.precedes(cl2.head.tsym, this)) {
  3212             return union(cl1.tail, cl2).prepend(cl1.head);
  3213         } else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) {
  3214             return union(cl1, cl2.tail).prepend(cl2.head);
  3215         } else {
  3216             return union(cl1.tail, cl2.tail).prepend(cl1.head);
  3220     /**
  3221      * Intersect two closures
  3222      */
  3223     public List<Type> intersect(List<Type> cl1, List<Type> cl2) {
  3224         if (cl1 == cl2)
  3225             return cl1;
  3226         if (cl1.isEmpty() || cl2.isEmpty())
  3227             return List.nil();
  3228         if (cl1.head.tsym.precedes(cl2.head.tsym, this))
  3229             return intersect(cl1.tail, cl2);
  3230         if (cl2.head.tsym.precedes(cl1.head.tsym, this))
  3231             return intersect(cl1, cl2.tail);
  3232         if (isSameType(cl1.head, cl2.head))
  3233             return intersect(cl1.tail, cl2.tail).prepend(cl1.head);
  3234         if (cl1.head.tsym == cl2.head.tsym &&
  3235             cl1.head.tag == CLASS && cl2.head.tag == CLASS) {
  3236             if (cl1.head.isParameterized() && cl2.head.isParameterized()) {
  3237                 Type merge = merge(cl1.head,cl2.head);
  3238                 return intersect(cl1.tail, cl2.tail).prepend(merge);
  3240             if (cl1.head.isRaw() || cl2.head.isRaw())
  3241                 return intersect(cl1.tail, cl2.tail).prepend(erasure(cl1.head));
  3243         return intersect(cl1.tail, cl2.tail);
  3245     // where
  3246         class TypePair {
  3247             final Type t1;
  3248             final Type t2;
  3249             TypePair(Type t1, Type t2) {
  3250                 this.t1 = t1;
  3251                 this.t2 = t2;
  3253             @Override
  3254             public int hashCode() {
  3255                 return 127 * Types.this.hashCode(t1) + Types.this.hashCode(t2);
  3257             @Override
  3258             public boolean equals(Object obj) {
  3259                 if (!(obj instanceof TypePair))
  3260                     return false;
  3261                 TypePair typePair = (TypePair)obj;
  3262                 return isSameType(t1, typePair.t1)
  3263                     && isSameType(t2, typePair.t2);
  3266         Set<TypePair> mergeCache = new HashSet<TypePair>();
  3267         private Type merge(Type c1, Type c2) {
  3268             ClassType class1 = (ClassType) c1;
  3269             List<Type> act1 = class1.getTypeArguments();
  3270             ClassType class2 = (ClassType) c2;
  3271             List<Type> act2 = class2.getTypeArguments();
  3272             ListBuffer<Type> merged = new ListBuffer<Type>();
  3273             List<Type> typarams = class1.tsym.type.getTypeArguments();
  3275             while (act1.nonEmpty() && act2.nonEmpty() && typarams.nonEmpty()) {
  3276                 if (containsType(act1.head, act2.head)) {
  3277                     merged.append(act1.head);
  3278                 } else if (containsType(act2.head, act1.head)) {
  3279                     merged.append(act2.head);
  3280                 } else {
  3281                     TypePair pair = new TypePair(c1, c2);
  3282                     Type m;
  3283                     if (mergeCache.add(pair)) {
  3284                         m = new WildcardType(lub(upperBound(act1.head),
  3285                                                  upperBound(act2.head)),
  3286                                              BoundKind.EXTENDS,
  3287                                              syms.boundClass);
  3288                         mergeCache.remove(pair);
  3289                     } else {
  3290                         m = new WildcardType(syms.objectType,
  3291                                              BoundKind.UNBOUND,
  3292                                              syms.boundClass);
  3294                     merged.append(m.withTypeVar(typarams.head));
  3296                 act1 = act1.tail;
  3297                 act2 = act2.tail;
  3298                 typarams = typarams.tail;
  3300             Assert.check(act1.isEmpty() && act2.isEmpty() && typarams.isEmpty());
  3301             return new ClassType(class1.getEnclosingType(), merged.toList(), class1.tsym);
  3304     /**
  3305      * Return the minimum type of a closure, a compound type if no
  3306      * unique minimum exists.
  3307      */
  3308     private Type compoundMin(List<Type> cl) {
  3309         if (cl.isEmpty()) return syms.objectType;
  3310         List<Type> compound = closureMin(cl);
  3311         if (compound.isEmpty())
  3312             return null;
  3313         else if (compound.tail.isEmpty())
  3314             return compound.head;
  3315         else
  3316             return makeCompoundType(compound);
  3319     /**
  3320      * Return the minimum types of a closure, suitable for computing
  3321      * compoundMin or glb.
  3322      */
  3323     private List<Type> closureMin(List<Type> cl) {
  3324         ListBuffer<Type> classes = lb();
  3325         ListBuffer<Type> interfaces = lb();
  3326         while (!cl.isEmpty()) {
  3327             Type current = cl.head;
  3328             if (current.isInterface())
  3329                 interfaces.append(current);
  3330             else
  3331                 classes.append(current);
  3332             ListBuffer<Type> candidates = lb();
  3333             for (Type t : cl.tail) {
  3334                 if (!isSubtypeNoCapture(current, t))
  3335                     candidates.append(t);
  3337             cl = candidates.toList();
  3339         return classes.appendList(interfaces).toList();
  3342     /**
  3343      * Return the least upper bound of pair of types.  if the lub does
  3344      * not exist return null.
  3345      */
  3346     public Type lub(Type t1, Type t2) {
  3347         return lub(List.of(t1, t2));
  3350     /**
  3351      * Return the least upper bound (lub) of set of types.  If the lub
  3352      * does not exist return the type of null (bottom).
  3353      */
  3354     public Type lub(List<Type> ts) {
  3355         final int ARRAY_BOUND = 1;
  3356         final int CLASS_BOUND = 2;
  3357         int boundkind = 0;
  3358         for (Type t : ts) {
  3359             switch (t.tag) {
  3360             case CLASS:
  3361                 boundkind |= CLASS_BOUND;
  3362                 break;
  3363             case ARRAY:
  3364                 boundkind |= ARRAY_BOUND;
  3365                 break;
  3366             case  TYPEVAR:
  3367                 do {
  3368                     t = t.getUpperBound();
  3369                 } while (t.tag == TYPEVAR);
  3370                 if (t.tag == ARRAY) {
  3371                     boundkind |= ARRAY_BOUND;
  3372                 } else {
  3373                     boundkind |= CLASS_BOUND;
  3375                 break;
  3376             default:
  3377                 if (t.isPrimitive())
  3378                     return syms.errType;
  3381         switch (boundkind) {
  3382         case 0:
  3383             return syms.botType;
  3385         case ARRAY_BOUND:
  3386             // calculate lub(A[], B[])
  3387             List<Type> elements = Type.map(ts, elemTypeFun);
  3388             for (Type t : elements) {
  3389                 if (t.isPrimitive()) {
  3390                     // if a primitive type is found, then return
  3391                     // arraySuperType unless all the types are the
  3392                     // same
  3393                     Type first = ts.head;
  3394                     for (Type s : ts.tail) {
  3395                         if (!isSameType(first, s)) {
  3396                              // lub(int[], B[]) is Cloneable & Serializable
  3397                             return arraySuperType();
  3400                     // all the array types are the same, return one
  3401                     // lub(int[], int[]) is int[]
  3402                     return first;
  3405             // lub(A[], B[]) is lub(A, B)[]
  3406             return new ArrayType(lub(elements), syms.arrayClass);
  3408         case CLASS_BOUND:
  3409             // calculate lub(A, B)
  3410             while (ts.head.tag != CLASS && ts.head.tag != TYPEVAR)
  3411                 ts = ts.tail;
  3412             Assert.check(!ts.isEmpty());
  3413             //step 1 - compute erased candidate set (EC)
  3414             List<Type> cl = erasedSupertypes(ts.head);
  3415             for (Type t : ts.tail) {
  3416                 if (t.tag == CLASS || t.tag == TYPEVAR)
  3417                     cl = intersect(cl, erasedSupertypes(t));
  3419             //step 2 - compute minimal erased candidate set (MEC)
  3420             List<Type> mec = closureMin(cl);
  3421             //step 3 - for each element G in MEC, compute lci(Inv(G))
  3422             List<Type> candidates = List.nil();
  3423             for (Type erasedSupertype : mec) {
  3424                 List<Type> lci = List.of(asSuper(ts.head, erasedSupertype.tsym));
  3425                 for (Type t : ts) {
  3426                     lci = intersect(lci, List.of(asSuper(t, erasedSupertype.tsym)));
  3428                 candidates = candidates.appendList(lci);
  3430             //step 4 - let MEC be { G1, G2 ... Gn }, then we have that
  3431             //lub = lci(Inv(G1)) & lci(Inv(G2)) & ... & lci(Inv(Gn))
  3432             return compoundMin(candidates);
  3434         default:
  3435             // calculate lub(A, B[])
  3436             List<Type> classes = List.of(arraySuperType());
  3437             for (Type t : ts) {
  3438                 if (t.tag != ARRAY) // Filter out any arrays
  3439                     classes = classes.prepend(t);
  3441             // lub(A, B[]) is lub(A, arraySuperType)
  3442             return lub(classes);
  3445     // where
  3446         List<Type> erasedSupertypes(Type t) {
  3447             ListBuffer<Type> buf = lb();
  3448             for (Type sup : closure(t)) {
  3449                 if (sup.tag == TYPEVAR) {
  3450                     buf.append(sup);
  3451                 } else {
  3452                     buf.append(erasure(sup));
  3455             return buf.toList();
  3458         private Type arraySuperType = null;
  3459         private Type arraySuperType() {
  3460             // initialized lazily to avoid problems during compiler startup
  3461             if (arraySuperType == null) {
  3462                 synchronized (this) {
  3463                     if (arraySuperType == null) {
  3464                         // JLS 10.8: all arrays implement Cloneable and Serializable.
  3465                         arraySuperType = makeCompoundType(List.of(syms.serializableType,
  3466                                                                   syms.cloneableType), true);
  3470             return arraySuperType;
  3472     // </editor-fold>
  3474     // <editor-fold defaultstate="collapsed" desc="Greatest lower bound">
  3475     public Type glb(List<Type> ts) {
  3476         Type t1 = ts.head;
  3477         for (Type t2 : ts.tail) {
  3478             if (t1.isErroneous())
  3479                 return t1;
  3480             t1 = glb(t1, t2);
  3482         return t1;
  3484     //where
  3485     public Type glb(Type t, Type s) {
  3486         if (s == null)
  3487             return t;
  3488         else if (t.isPrimitive() || s.isPrimitive())
  3489             return syms.errType;
  3490         else if (isSubtypeNoCapture(t, s))
  3491             return t;
  3492         else if (isSubtypeNoCapture(s, t))
  3493             return s;
  3495         List<Type> closure = union(closure(t), closure(s));
  3496         List<Type> bounds = closureMin(closure);
  3498         if (bounds.isEmpty()) {             // length == 0
  3499             return syms.objectType;
  3500         } else if (bounds.tail.isEmpty()) { // length == 1
  3501             return bounds.head;
  3502         } else {                            // length > 1
  3503             int classCount = 0;
  3504             for (Type bound : bounds)
  3505                 if (!bound.isInterface())
  3506                     classCount++;
  3507             if (classCount > 1)
  3508                 return createErrorType(t);
  3510         return makeCompoundType(bounds);
  3512     // </editor-fold>
  3514     // <editor-fold defaultstate="collapsed" desc="hashCode">
  3515     /**
  3516      * Compute a hash code on a type.
  3517      */
  3518     public int hashCode(Type t) {
  3519         return hashCode.visit(t);
  3521     // where
  3522         private static final UnaryVisitor<Integer> hashCode = new UnaryVisitor<Integer>() {
  3524             public Integer visitType(Type t, Void ignored) {
  3525                 return t.tag.ordinal();
  3528             @Override
  3529             public Integer visitClassType(ClassType t, Void ignored) {
  3530                 int result = visit(t.getEnclosingType());
  3531                 result *= 127;
  3532                 result += t.tsym.flatName().hashCode();
  3533                 for (Type s : t.getTypeArguments()) {
  3534                     result *= 127;
  3535                     result += visit(s);
  3537                 return result;
  3540             @Override
  3541             public Integer visitMethodType(MethodType t, Void ignored) {
  3542                 int h = METHOD.ordinal();
  3543                 for (List<Type> thisargs = t.argtypes;
  3544                      thisargs.tail != null;
  3545                      thisargs = thisargs.tail)
  3546                     h = (h << 5) + visit(thisargs.head);
  3547                 return (h << 5) + visit(t.restype);
  3550             @Override
  3551             public Integer visitWildcardType(WildcardType t, Void ignored) {
  3552                 int result = t.kind.hashCode();
  3553                 if (t.type != null) {
  3554                     result *= 127;
  3555                     result += visit(t.type);
  3557                 return result;
  3560             @Override
  3561             public Integer visitArrayType(ArrayType t, Void ignored) {
  3562                 return visit(t.elemtype) + 12;
  3565             @Override
  3566             public Integer visitTypeVar(TypeVar t, Void ignored) {
  3567                 return System.identityHashCode(t.tsym);
  3570             @Override
  3571             public Integer visitUndetVar(UndetVar t, Void ignored) {
  3572                 return System.identityHashCode(t);
  3575             @Override
  3576             public Integer visitErrorType(ErrorType t, Void ignored) {
  3577                 return 0;
  3579         };
  3580     // </editor-fold>
  3582     // <editor-fold defaultstate="collapsed" desc="Return-Type-Substitutable">
  3583     /**
  3584      * Does t have a result that is a subtype of the result type of s,
  3585      * suitable for covariant returns?  It is assumed that both types
  3586      * are (possibly polymorphic) method types.  Monomorphic method
  3587      * types are handled in the obvious way.  Polymorphic method types
  3588      * require renaming all type variables of one to corresponding
  3589      * type variables in the other, where correspondence is by
  3590      * position in the type parameter list. */
  3591     public boolean resultSubtype(Type t, Type s, Warner warner) {
  3592         List<Type> tvars = t.getTypeArguments();
  3593         List<Type> svars = s.getTypeArguments();
  3594         Type tres = t.getReturnType();
  3595         Type sres = subst(s.getReturnType(), svars, tvars);
  3596         return covariantReturnType(tres, sres, warner);
  3599     /**
  3600      * Return-Type-Substitutable.
  3601      * @jls section 8.4.5
  3602      */
  3603     public boolean returnTypeSubstitutable(Type r1, Type r2) {
  3604         if (hasSameArgs(r1, r2))
  3605             return resultSubtype(r1, r2, noWarnings);
  3606         else
  3607             return covariantReturnType(r1.getReturnType(),
  3608                                        erasure(r2.getReturnType()),
  3609                                        noWarnings);
  3612     public boolean returnTypeSubstitutable(Type r1,
  3613                                            Type r2, Type r2res,
  3614                                            Warner warner) {
  3615         if (isSameType(r1.getReturnType(), r2res))
  3616             return true;
  3617         if (r1.getReturnType().isPrimitive() || r2res.isPrimitive())
  3618             return false;
  3620         if (hasSameArgs(r1, r2))
  3621             return covariantReturnType(r1.getReturnType(), r2res, warner);
  3622         if (!allowCovariantReturns)
  3623             return false;
  3624         if (isSubtypeUnchecked(r1.getReturnType(), r2res, warner))
  3625             return true;
  3626         if (!isSubtype(r1.getReturnType(), erasure(r2res)))
  3627             return false;
  3628         warner.warn(LintCategory.UNCHECKED);
  3629         return true;
  3632     /**
  3633      * Is t an appropriate return type in an overrider for a
  3634      * method that returns s?
  3635      */
  3636     public boolean covariantReturnType(Type t, Type s, Warner warner) {
  3637         return
  3638             isSameType(t, s) ||
  3639             allowCovariantReturns &&
  3640             !t.isPrimitive() &&
  3641             !s.isPrimitive() &&
  3642             isAssignable(t, s, warner);
  3644     // </editor-fold>
  3646     // <editor-fold defaultstate="collapsed" desc="Box/unbox support">
  3647     /**
  3648      * Return the class that boxes the given primitive.
  3649      */
  3650     public ClassSymbol boxedClass(Type t) {
  3651         return reader.enterClass(syms.boxedName[t.tag.ordinal()]);
  3654     /**
  3655      * Return the boxed type if 't' is primitive, otherwise return 't' itself.
  3656      */
  3657     public Type boxedTypeOrType(Type t) {
  3658         return t.isPrimitive() ?
  3659             boxedClass(t).type :
  3660             t;
  3663     /**
  3664      * Return the primitive type corresponding to a boxed type.
  3665      */
  3666     public Type unboxedType(Type t) {
  3667         if (allowBoxing) {
  3668             for (int i=0; i<syms.boxedName.length; i++) {
  3669                 Name box = syms.boxedName[i];
  3670                 if (box != null &&
  3671                     asSuper(t, reader.enterClass(box)) != null)
  3672                     return syms.typeOfTag[i];
  3675         return Type.noType;
  3678     /**
  3679      * Return the unboxed type if 't' is a boxed class, otherwise return 't' itself.
  3680      */
  3681     public Type unboxedTypeOrType(Type t) {
  3682         Type unboxedType = unboxedType(t);
  3683         return unboxedType.tag == NONE ? t : unboxedType;
  3685     // </editor-fold>
  3687     // <editor-fold defaultstate="collapsed" desc="Capture conversion">
  3688     /*
  3689      * JLS 5.1.10 Capture Conversion:
  3691      * Let G name a generic type declaration with n formal type
  3692      * parameters A1 ... An with corresponding bounds U1 ... Un. There
  3693      * exists a capture conversion from G<T1 ... Tn> to G<S1 ... Sn>,
  3694      * where, for 1 <= i <= n:
  3696      * + If Ti is a wildcard type argument (4.5.1) of the form ? then
  3697      *   Si is a fresh type variable whose upper bound is
  3698      *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is the null
  3699      *   type.
  3701      * + If Ti is a wildcard type argument of the form ? extends Bi,
  3702      *   then Si is a fresh type variable whose upper bound is
  3703      *   glb(Bi, Ui[A1 := S1, ..., An := Sn]) and whose lower bound is
  3704      *   the null type, where glb(V1,... ,Vm) is V1 & ... & Vm. It is
  3705      *   a compile-time error if for any two classes (not interfaces)
  3706      *   Vi and Vj,Vi is not a subclass of Vj or vice versa.
  3708      * + If Ti is a wildcard type argument of the form ? super Bi,
  3709      *   then Si is a fresh type variable whose upper bound is
  3710      *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is Bi.
  3712      * + Otherwise, Si = Ti.
  3714      * Capture conversion on any type other than a parameterized type
  3715      * (4.5) acts as an identity conversion (5.1.1). Capture
  3716      * conversions never require a special action at run time and
  3717      * therefore never throw an exception at run time.
  3719      * Capture conversion is not applied recursively.
  3720      */
  3721     /**
  3722      * Capture conversion as specified by the JLS.
  3723      */
  3725     public List<Type> capture(List<Type> ts) {
  3726         List<Type> buf = List.nil();
  3727         for (Type t : ts) {
  3728             buf = buf.prepend(capture(t));
  3730         return buf.reverse();
  3732     public Type capture(Type t) {
  3733         if (t.tag != CLASS)
  3734             return t;
  3735         if (t.getEnclosingType() != Type.noType) {
  3736             Type capturedEncl = capture(t.getEnclosingType());
  3737             if (capturedEncl != t.getEnclosingType()) {
  3738                 Type type1 = memberType(capturedEncl, t.tsym);
  3739                 t = subst(type1, t.tsym.type.getTypeArguments(), t.getTypeArguments());
  3742         t = t.unannotatedType();
  3743         ClassType cls = (ClassType)t;
  3744         if (cls.isRaw() || !cls.isParameterized())
  3745             return cls;
  3747         ClassType G = (ClassType)cls.asElement().asType();
  3748         List<Type> A = G.getTypeArguments();
  3749         List<Type> T = cls.getTypeArguments();
  3750         List<Type> S = freshTypeVariables(T);
  3752         List<Type> currentA = A;
  3753         List<Type> currentT = T;
  3754         List<Type> currentS = S;
  3755         boolean captured = false;
  3756         while (!currentA.isEmpty() &&
  3757                !currentT.isEmpty() &&
  3758                !currentS.isEmpty()) {
  3759             if (currentS.head != currentT.head) {
  3760                 captured = true;
  3761                 WildcardType Ti = (WildcardType)currentT.head;
  3762                 Type Ui = currentA.head.getUpperBound();
  3763                 CapturedType Si = (CapturedType)currentS.head;
  3764                 if (Ui == null)
  3765                     Ui = syms.objectType;
  3766                 switch (Ti.kind) {
  3767                 case UNBOUND:
  3768                     Si.bound = subst(Ui, A, S);
  3769                     Si.lower = syms.botType;
  3770                     break;
  3771                 case EXTENDS:
  3772                     Si.bound = glb(Ti.getExtendsBound(), subst(Ui, A, S));
  3773                     Si.lower = syms.botType;
  3774                     break;
  3775                 case SUPER:
  3776                     Si.bound = subst(Ui, A, S);
  3777                     Si.lower = Ti.getSuperBound();
  3778                     break;
  3780                 if (Si.bound == Si.lower)
  3781                     currentS.head = Si.bound;
  3783             currentA = currentA.tail;
  3784             currentT = currentT.tail;
  3785             currentS = currentS.tail;
  3787         if (!currentA.isEmpty() || !currentT.isEmpty() || !currentS.isEmpty())
  3788             return erasure(t); // some "rare" type involved
  3790         if (captured)
  3791             return new ClassType(cls.getEnclosingType(), S, cls.tsym);
  3792         else
  3793             return t;
  3795     // where
  3796         public List<Type> freshTypeVariables(List<Type> types) {
  3797             ListBuffer<Type> result = lb();
  3798             for (Type t : types) {
  3799                 if (t.tag == WILDCARD) {
  3800                     Type bound = ((WildcardType)t).getExtendsBound();
  3801                     if (bound == null)
  3802                         bound = syms.objectType;
  3803                     result.append(new CapturedType(capturedName,
  3804                                                    syms.noSymbol,
  3805                                                    bound,
  3806                                                    syms.botType,
  3807                                                    (WildcardType)t));
  3808                 } else {
  3809                     result.append(t);
  3812             return result.toList();
  3814     // </editor-fold>
  3816     // <editor-fold defaultstate="collapsed" desc="Internal utility methods">
  3817     private List<Type> upperBounds(List<Type> ss) {
  3818         if (ss.isEmpty()) return ss;
  3819         Type head = upperBound(ss.head);
  3820         List<Type> tail = upperBounds(ss.tail);
  3821         if (head != ss.head || tail != ss.tail)
  3822             return tail.prepend(head);
  3823         else
  3824             return ss;
  3827     private boolean sideCast(Type from, Type to, Warner warn) {
  3828         // We are casting from type $from$ to type $to$, which are
  3829         // non-final unrelated types.  This method
  3830         // tries to reject a cast by transferring type parameters
  3831         // from $to$ to $from$ by common superinterfaces.
  3832         boolean reverse = false;
  3833         Type target = to;
  3834         if ((to.tsym.flags() & INTERFACE) == 0) {
  3835             Assert.check((from.tsym.flags() & INTERFACE) != 0);
  3836             reverse = true;
  3837             to = from;
  3838             from = target;
  3840         List<Type> commonSupers = superClosure(to, erasure(from));
  3841         boolean giveWarning = commonSupers.isEmpty();
  3842         // The arguments to the supers could be unified here to
  3843         // get a more accurate analysis
  3844         while (commonSupers.nonEmpty()) {
  3845             Type t1 = asSuper(from, commonSupers.head.tsym);
  3846             Type t2 = commonSupers.head; // same as asSuper(to, commonSupers.head.tsym);
  3847             if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
  3848                 return false;
  3849             giveWarning = giveWarning || (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2));
  3850             commonSupers = commonSupers.tail;
  3852         if (giveWarning && !isReifiable(reverse ? from : to))
  3853             warn.warn(LintCategory.UNCHECKED);
  3854         if (!allowCovariantReturns)
  3855             // reject if there is a common method signature with
  3856             // incompatible return types.
  3857             chk.checkCompatibleAbstracts(warn.pos(), from, to);
  3858         return true;
  3861     private boolean sideCastFinal(Type from, Type to, Warner warn) {
  3862         // We are casting from type $from$ to type $to$, which are
  3863         // unrelated types one of which is final and the other of
  3864         // which is an interface.  This method
  3865         // tries to reject a cast by transferring type parameters
  3866         // from the final class to the interface.
  3867         boolean reverse = false;
  3868         Type target = to;
  3869         if ((to.tsym.flags() & INTERFACE) == 0) {
  3870             Assert.check((from.tsym.flags() & INTERFACE) != 0);
  3871             reverse = true;
  3872             to = from;
  3873             from = target;
  3875         Assert.check((from.tsym.flags() & FINAL) != 0);
  3876         Type t1 = asSuper(from, to.tsym);
  3877         if (t1 == null) return false;
  3878         Type t2 = to;
  3879         if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
  3880             return false;
  3881         if (!allowCovariantReturns)
  3882             // reject if there is a common method signature with
  3883             // incompatible return types.
  3884             chk.checkCompatibleAbstracts(warn.pos(), from, to);
  3885         if (!isReifiable(target) &&
  3886             (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2)))
  3887             warn.warn(LintCategory.UNCHECKED);
  3888         return true;
  3891     private boolean giveWarning(Type from, Type to) {
  3892         Type subFrom = asSub(from, to.tsym);
  3893         return to.isParameterized() &&
  3894                 (!(isUnbounded(to) ||
  3895                 isSubtype(from, to) ||
  3896                 ((subFrom != null) && containsType(to.allparams(), subFrom.allparams()))));
  3899     private List<Type> superClosure(Type t, Type s) {
  3900         List<Type> cl = List.nil();
  3901         for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
  3902             if (isSubtype(s, erasure(l.head))) {
  3903                 cl = insert(cl, l.head);
  3904             } else {
  3905                 cl = union(cl, superClosure(l.head, s));
  3908         return cl;
  3911     private boolean containsTypeEquivalent(Type t, Type s) {
  3912         return
  3913             isSameType(t, s) || // shortcut
  3914             containsType(t, s) && containsType(s, t);
  3917     // <editor-fold defaultstate="collapsed" desc="adapt">
  3918     /**
  3919      * Adapt a type by computing a substitution which maps a source
  3920      * type to a target type.
  3922      * @param source    the source type
  3923      * @param target    the target type
  3924      * @param from      the type variables of the computed substitution
  3925      * @param to        the types of the computed substitution.
  3926      */
  3927     public void adapt(Type source,
  3928                        Type target,
  3929                        ListBuffer<Type> from,
  3930                        ListBuffer<Type> to) throws AdaptFailure {
  3931         new Adapter(from, to).adapt(source, target);
  3934     class Adapter extends SimpleVisitor<Void, Type> {
  3936         ListBuffer<Type> from;
  3937         ListBuffer<Type> to;
  3938         Map<Symbol,Type> mapping;
  3940         Adapter(ListBuffer<Type> from, ListBuffer<Type> to) {
  3941             this.from = from;
  3942             this.to = to;
  3943             mapping = new HashMap<Symbol,Type>();
  3946         public void adapt(Type source, Type target) throws AdaptFailure {
  3947             visit(source, target);
  3948             List<Type> fromList = from.toList();
  3949             List<Type> toList = to.toList();
  3950             while (!fromList.isEmpty()) {
  3951                 Type val = mapping.get(fromList.head.tsym);
  3952                 if (toList.head != val)
  3953                     toList.head = val;
  3954                 fromList = fromList.tail;
  3955                 toList = toList.tail;
  3959         @Override
  3960         public Void visitClassType(ClassType source, Type target) throws AdaptFailure {
  3961             if (target.tag == CLASS)
  3962                 adaptRecursive(source.allparams(), target.allparams());
  3963             return null;
  3966         @Override
  3967         public Void visitArrayType(ArrayType source, Type target) throws AdaptFailure {
  3968             if (target.tag == ARRAY)
  3969                 adaptRecursive(elemtype(source), elemtype(target));
  3970             return null;
  3973         @Override
  3974         public Void visitWildcardType(WildcardType source, Type target) throws AdaptFailure {
  3975             if (source.isExtendsBound())
  3976                 adaptRecursive(upperBound(source), upperBound(target));
  3977             else if (source.isSuperBound())
  3978                 adaptRecursive(lowerBound(source), lowerBound(target));
  3979             return null;
  3982         @Override
  3983         public Void visitTypeVar(TypeVar source, Type target) throws AdaptFailure {
  3984             // Check to see if there is
  3985             // already a mapping for $source$, in which case
  3986             // the old mapping will be merged with the new
  3987             Type val = mapping.get(source.tsym);
  3988             if (val != null) {
  3989                 if (val.isSuperBound() && target.isSuperBound()) {
  3990                     val = isSubtype(lowerBound(val), lowerBound(target))
  3991                         ? target : val;
  3992                 } else if (val.isExtendsBound() && target.isExtendsBound()) {
  3993                     val = isSubtype(upperBound(val), upperBound(target))
  3994                         ? val : target;
  3995                 } else if (!isSameType(val, target)) {
  3996                     throw new AdaptFailure();
  3998             } else {
  3999                 val = target;
  4000                 from.append(source);
  4001                 to.append(target);
  4003             mapping.put(source.tsym, val);
  4004             return null;
  4007         @Override
  4008         public Void visitType(Type source, Type target) {
  4009             return null;
  4012         private Set<TypePair> cache = new HashSet<TypePair>();
  4014         private void adaptRecursive(Type source, Type target) {
  4015             TypePair pair = new TypePair(source, target);
  4016             if (cache.add(pair)) {
  4017                 try {
  4018                     visit(source, target);
  4019                 } finally {
  4020                     cache.remove(pair);
  4025         private void adaptRecursive(List<Type> source, List<Type> target) {
  4026             if (source.length() == target.length()) {
  4027                 while (source.nonEmpty()) {
  4028                     adaptRecursive(source.head, target.head);
  4029                     source = source.tail;
  4030                     target = target.tail;
  4036     public static class AdaptFailure extends RuntimeException {
  4037         static final long serialVersionUID = -7490231548272701566L;
  4040     private void adaptSelf(Type t,
  4041                            ListBuffer<Type> from,
  4042                            ListBuffer<Type> to) {
  4043         try {
  4044             //if (t.tsym.type != t)
  4045                 adapt(t.tsym.type, t, from, to);
  4046         } catch (AdaptFailure ex) {
  4047             // Adapt should never fail calculating a mapping from
  4048             // t.tsym.type to t as there can be no merge problem.
  4049             throw new AssertionError(ex);
  4052     // </editor-fold>
  4054     /**
  4055      * Rewrite all type variables (universal quantifiers) in the given
  4056      * type to wildcards (existential quantifiers).  This is used to
  4057      * determine if a cast is allowed.  For example, if high is true
  4058      * and {@code T <: Number}, then {@code List<T>} is rewritten to
  4059      * {@code List<?  extends Number>}.  Since {@code List<Integer> <:
  4060      * List<? extends Number>} a {@code List<T>} can be cast to {@code
  4061      * List<Integer>} with a warning.
  4062      * @param t a type
  4063      * @param high if true return an upper bound; otherwise a lower
  4064      * bound
  4065      * @param rewriteTypeVars only rewrite captured wildcards if false;
  4066      * otherwise rewrite all type variables
  4067      * @return the type rewritten with wildcards (existential
  4068      * quantifiers) only
  4069      */
  4070     private Type rewriteQuantifiers(Type t, boolean high, boolean rewriteTypeVars) {
  4071         return new Rewriter(high, rewriteTypeVars).visit(t);
  4074     class Rewriter extends UnaryVisitor<Type> {
  4076         boolean high;
  4077         boolean rewriteTypeVars;
  4079         Rewriter(boolean high, boolean rewriteTypeVars) {
  4080             this.high = high;
  4081             this.rewriteTypeVars = rewriteTypeVars;
  4084         @Override
  4085         public Type visitClassType(ClassType t, Void s) {
  4086             ListBuffer<Type> rewritten = new ListBuffer<Type>();
  4087             boolean changed = false;
  4088             for (Type arg : t.allparams()) {
  4089                 Type bound = visit(arg);
  4090                 if (arg != bound) {
  4091                     changed = true;
  4093                 rewritten.append(bound);
  4095             if (changed)
  4096                 return subst(t.tsym.type,
  4097                         t.tsym.type.allparams(),
  4098                         rewritten.toList());
  4099             else
  4100                 return t;
  4103         public Type visitType(Type t, Void s) {
  4104             return high ? upperBound(t) : lowerBound(t);
  4107         @Override
  4108         public Type visitCapturedType(CapturedType t, Void s) {
  4109             Type w_bound = t.wildcard.type;
  4110             Type bound = w_bound.contains(t) ?
  4111                         erasure(w_bound) :
  4112                         visit(w_bound);
  4113             return rewriteAsWildcardType(visit(bound), t.wildcard.bound, t.wildcard.kind);
  4116         @Override
  4117         public Type visitTypeVar(TypeVar t, Void s) {
  4118             if (rewriteTypeVars) {
  4119                 Type bound = t.bound.contains(t) ?
  4120                         erasure(t.bound) :
  4121                         visit(t.bound);
  4122                 return rewriteAsWildcardType(bound, t, EXTENDS);
  4123             } else {
  4124                 return t;
  4128         @Override
  4129         public Type visitWildcardType(WildcardType t, Void s) {
  4130             Type bound2 = visit(t.type);
  4131             return t.type == bound2 ? t : rewriteAsWildcardType(bound2, t.bound, t.kind);
  4134         private Type rewriteAsWildcardType(Type bound, TypeVar formal, BoundKind bk) {
  4135             switch (bk) {
  4136                case EXTENDS: return high ?
  4137                        makeExtendsWildcard(B(bound), formal) :
  4138                        makeExtendsWildcard(syms.objectType, formal);
  4139                case SUPER: return high ?
  4140                        makeSuperWildcard(syms.botType, formal) :
  4141                        makeSuperWildcard(B(bound), formal);
  4142                case UNBOUND: return makeExtendsWildcard(syms.objectType, formal);
  4143                default:
  4144                    Assert.error("Invalid bound kind " + bk);
  4145                    return null;
  4149         Type B(Type t) {
  4150             while (t.tag == WILDCARD) {
  4151                 WildcardType w = (WildcardType)t;
  4152                 t = high ?
  4153                     w.getExtendsBound() :
  4154                     w.getSuperBound();
  4155                 if (t == null) {
  4156                     t = high ? syms.objectType : syms.botType;
  4159             return t;
  4164     /**
  4165      * Create a wildcard with the given upper (extends) bound; create
  4166      * an unbounded wildcard if bound is Object.
  4168      * @param bound the upper bound
  4169      * @param formal the formal type parameter that will be
  4170      * substituted by the wildcard
  4171      */
  4172     private WildcardType makeExtendsWildcard(Type bound, TypeVar formal) {
  4173         if (bound == syms.objectType) {
  4174             return new WildcardType(syms.objectType,
  4175                                     BoundKind.UNBOUND,
  4176                                     syms.boundClass,
  4177                                     formal);
  4178         } else {
  4179             return new WildcardType(bound,
  4180                                     BoundKind.EXTENDS,
  4181                                     syms.boundClass,
  4182                                     formal);
  4186     /**
  4187      * Create a wildcard with the given lower (super) bound; create an
  4188      * unbounded wildcard if bound is bottom (type of {@code null}).
  4190      * @param bound the lower bound
  4191      * @param formal the formal type parameter that will be
  4192      * substituted by the wildcard
  4193      */
  4194     private WildcardType makeSuperWildcard(Type bound, TypeVar formal) {
  4195         if (bound.tag == BOT) {
  4196             return new WildcardType(syms.objectType,
  4197                                     BoundKind.UNBOUND,
  4198                                     syms.boundClass,
  4199                                     formal);
  4200         } else {
  4201             return new WildcardType(bound,
  4202                                     BoundKind.SUPER,
  4203                                     syms.boundClass,
  4204                                     formal);
  4208     /**
  4209      * A wrapper for a type that allows use in sets.
  4210      */
  4211     public static class UniqueType {
  4212         public final Type type;
  4213         final Types types;
  4215         public UniqueType(Type type, Types types) {
  4216             this.type = type;
  4217             this.types = types;
  4220         public int hashCode() {
  4221             return types.hashCode(type);
  4224         public boolean equals(Object obj) {
  4225             return (obj instanceof UniqueType) &&
  4226                 types.isSameType(type, ((UniqueType)obj).type);
  4229         public String toString() {
  4230             return type.toString();
  4234     // </editor-fold>
  4236     // <editor-fold defaultstate="collapsed" desc="Visitors">
  4237     /**
  4238      * A default visitor for types.  All visitor methods except
  4239      * visitType are implemented by delegating to visitType.  Concrete
  4240      * subclasses must provide an implementation of visitType and can
  4241      * override other methods as needed.
  4243      * @param <R> the return type of the operation implemented by this
  4244      * visitor; use Void if no return type is needed.
  4245      * @param <S> the type of the second argument (the first being the
  4246      * type itself) of the operation implemented by this visitor; use
  4247      * Void if a second argument is not needed.
  4248      */
  4249     public static abstract class DefaultTypeVisitor<R,S> implements Type.Visitor<R,S> {
  4250         final public R visit(Type t, S s)               { return t.accept(this, s); }
  4251         public R visitClassType(ClassType t, S s)       { return visitType(t, s); }
  4252         public R visitWildcardType(WildcardType t, S s) { return visitType(t, s); }
  4253         public R visitArrayType(ArrayType t, S s)       { return visitType(t, s); }
  4254         public R visitMethodType(MethodType t, S s)     { return visitType(t, s); }
  4255         public R visitPackageType(PackageType t, S s)   { return visitType(t, s); }
  4256         public R visitTypeVar(TypeVar t, S s)           { return visitType(t, s); }
  4257         public R visitCapturedType(CapturedType t, S s) { return visitType(t, s); }
  4258         public R visitForAll(ForAll t, S s)             { return visitType(t, s); }
  4259         public R visitUndetVar(UndetVar t, S s)         { return visitType(t, s); }
  4260         public R visitErrorType(ErrorType t, S s)       { return visitType(t, s); }
  4261         // Pretend annotations don't exist
  4262         public R visitAnnotatedType(AnnotatedType t, S s) { return visit(t.underlyingType, s); }
  4265     /**
  4266      * A default visitor for symbols.  All visitor methods except
  4267      * visitSymbol are implemented by delegating to visitSymbol.  Concrete
  4268      * subclasses must provide an implementation of visitSymbol and can
  4269      * override other methods as needed.
  4271      * @param <R> the return type of the operation implemented by this
  4272      * visitor; use Void if no return type is needed.
  4273      * @param <S> the type of the second argument (the first being the
  4274      * symbol itself) of the operation implemented by this visitor; use
  4275      * Void if a second argument is not needed.
  4276      */
  4277     public static abstract class DefaultSymbolVisitor<R,S> implements Symbol.Visitor<R,S> {
  4278         final public R visit(Symbol s, S arg)                   { return s.accept(this, arg); }
  4279         public R visitClassSymbol(ClassSymbol s, S arg)         { return visitSymbol(s, arg); }
  4280         public R visitMethodSymbol(MethodSymbol s, S arg)       { return visitSymbol(s, arg); }
  4281         public R visitOperatorSymbol(OperatorSymbol s, S arg)   { return visitSymbol(s, arg); }
  4282         public R visitPackageSymbol(PackageSymbol s, S arg)     { return visitSymbol(s, arg); }
  4283         public R visitTypeSymbol(TypeSymbol s, S arg)           { return visitSymbol(s, arg); }
  4284         public R visitVarSymbol(VarSymbol s, S arg)             { return visitSymbol(s, arg); }
  4287     /**
  4288      * A <em>simple</em> visitor for types.  This visitor is simple as
  4289      * captured wildcards, for-all types (generic methods), and
  4290      * undetermined type variables (part of inference) are hidden.
  4291      * Captured wildcards are hidden by treating them as type
  4292      * variables and the rest are hidden by visiting their qtypes.
  4294      * @param <R> the return type of the operation implemented by this
  4295      * visitor; use Void if no return type is needed.
  4296      * @param <S> the type of the second argument (the first being the
  4297      * type itself) of the operation implemented by this visitor; use
  4298      * Void if a second argument is not needed.
  4299      */
  4300     public static abstract class SimpleVisitor<R,S> extends DefaultTypeVisitor<R,S> {
  4301         @Override
  4302         public R visitCapturedType(CapturedType t, S s) {
  4303             return visitTypeVar(t, s);
  4305         @Override
  4306         public R visitForAll(ForAll t, S s) {
  4307             return visit(t.qtype, s);
  4309         @Override
  4310         public R visitUndetVar(UndetVar t, S s) {
  4311             return visit(t.qtype, s);
  4315     /**
  4316      * A plain relation on types.  That is a 2-ary function on the
  4317      * form Type&nbsp;&times;&nbsp;Type&nbsp;&rarr;&nbsp;Boolean.
  4318      * <!-- In plain text: Type x Type -> Boolean -->
  4319      */
  4320     public static abstract class TypeRelation extends SimpleVisitor<Boolean,Type> {}
  4322     /**
  4323      * A convenience visitor for implementing operations that only
  4324      * require one argument (the type itself), that is, unary
  4325      * operations.
  4327      * @param <R> the return type of the operation implemented by this
  4328      * visitor; use Void if no return type is needed.
  4329      */
  4330     public static abstract class UnaryVisitor<R> extends SimpleVisitor<R,Void> {
  4331         final public R visit(Type t) { return t.accept(this, null); }
  4334     /**
  4335      * A visitor for implementing a mapping from types to types.  The
  4336      * default behavior of this class is to implement the identity
  4337      * mapping (mapping a type to itself).  This can be overridden in
  4338      * subclasses.
  4340      * @param <S> the type of the second argument (the first being the
  4341      * type itself) of this mapping; use Void if a second argument is
  4342      * not needed.
  4343      */
  4344     public static class MapVisitor<S> extends DefaultTypeVisitor<Type,S> {
  4345         final public Type visit(Type t) { return t.accept(this, null); }
  4346         public Type visitType(Type t, S s) { return t; }
  4348     // </editor-fold>
  4351     // <editor-fold defaultstate="collapsed" desc="Annotation support">
  4353     public RetentionPolicy getRetention(Attribute.Compound a) {
  4354         return getRetention(a.type.tsym);
  4357     public RetentionPolicy getRetention(Symbol sym) {
  4358         RetentionPolicy vis = RetentionPolicy.CLASS; // the default
  4359         Attribute.Compound c = sym.attribute(syms.retentionType.tsym);
  4360         if (c != null) {
  4361             Attribute value = c.member(names.value);
  4362             if (value != null && value instanceof Attribute.Enum) {
  4363                 Name levelName = ((Attribute.Enum)value).value.name;
  4364                 if (levelName == names.SOURCE) vis = RetentionPolicy.SOURCE;
  4365                 else if (levelName == names.CLASS) vis = RetentionPolicy.CLASS;
  4366                 else if (levelName == names.RUNTIME) vis = RetentionPolicy.RUNTIME;
  4367                 else ;// /* fail soft */ throw new AssertionError(levelName);
  4370         return vis;
  4372     // </editor-fold>
  4374     // <editor-fold defaultstate="collapsed" desc="Signature Generation">
  4376     public static abstract class SignatureGenerator {
  4378         private final Types types;
  4380         protected abstract void append(char ch);
  4381         protected abstract void append(byte[] ba);
  4382         protected abstract void append(Name name);
  4383         protected void classReference(ClassSymbol c) { /* by default: no-op */ }
  4385         protected SignatureGenerator(Types types) {
  4386             this.types = types;
  4389         /**
  4390          * Assemble signature of given type in string buffer.
  4391          */
  4392         public void assembleSig(Type type) {
  4393             type = type.unannotatedType();
  4394             switch (type.getTag()) {
  4395                 case BYTE:
  4396                     append('B');
  4397                     break;
  4398                 case SHORT:
  4399                     append('S');
  4400                     break;
  4401                 case CHAR:
  4402                     append('C');
  4403                     break;
  4404                 case INT:
  4405                     append('I');
  4406                     break;
  4407                 case LONG:
  4408                     append('J');
  4409                     break;
  4410                 case FLOAT:
  4411                     append('F');
  4412                     break;
  4413                 case DOUBLE:
  4414                     append('D');
  4415                     break;
  4416                 case BOOLEAN:
  4417                     append('Z');
  4418                     break;
  4419                 case VOID:
  4420                     append('V');
  4421                     break;
  4422                 case CLASS:
  4423                     append('L');
  4424                     assembleClassSig(type);
  4425                     append(';');
  4426                     break;
  4427                 case ARRAY:
  4428                     ArrayType at = (ArrayType) type;
  4429                     append('[');
  4430                     assembleSig(at.elemtype);
  4431                     break;
  4432                 case METHOD:
  4433                     MethodType mt = (MethodType) type;
  4434                     append('(');
  4435                     assembleSig(mt.argtypes);
  4436                     append(')');
  4437                     assembleSig(mt.restype);
  4438                     if (hasTypeVar(mt.thrown)) {
  4439                         for (List<Type> l = mt.thrown; l.nonEmpty(); l = l.tail) {
  4440                             append('^');
  4441                             assembleSig(l.head);
  4444                     break;
  4445                 case WILDCARD: {
  4446                     Type.WildcardType ta = (Type.WildcardType) type;
  4447                     switch (ta.kind) {
  4448                         case SUPER:
  4449                             append('-');
  4450                             assembleSig(ta.type);
  4451                             break;
  4452                         case EXTENDS:
  4453                             append('+');
  4454                             assembleSig(ta.type);
  4455                             break;
  4456                         case UNBOUND:
  4457                             append('*');
  4458                             break;
  4459                         default:
  4460                             throw new AssertionError(ta.kind);
  4462                     break;
  4464                 case TYPEVAR:
  4465                     append('T');
  4466                     append(type.tsym.name);
  4467                     append(';');
  4468                     break;
  4469                 case FORALL:
  4470                     Type.ForAll ft = (Type.ForAll) type;
  4471                     assembleParamsSig(ft.tvars);
  4472                     assembleSig(ft.qtype);
  4473                     break;
  4474                 default:
  4475                     throw new AssertionError("typeSig " + type.getTag());
  4479         public boolean hasTypeVar(List<Type> l) {
  4480             while (l.nonEmpty()) {
  4481                 if (l.head.hasTag(TypeTag.TYPEVAR)) {
  4482                     return true;
  4484                 l = l.tail;
  4486             return false;
  4489         public void assembleClassSig(Type type) {
  4490             type = type.unannotatedType();
  4491             ClassType ct = (ClassType) type;
  4492             ClassSymbol c = (ClassSymbol) ct.tsym;
  4493             classReference(c);
  4494             Type outer = ct.getEnclosingType();
  4495             if (outer.allparams().nonEmpty()) {
  4496                 boolean rawOuter =
  4497                         c.owner.kind == Kinds.MTH || // either a local class
  4498                         c.name == types.names.empty; // or anonymous
  4499                 assembleClassSig(rawOuter
  4500                         ? types.erasure(outer)
  4501                         : outer);
  4502                 append('.');
  4503                 Assert.check(c.flatname.startsWith(c.owner.enclClass().flatname));
  4504                 append(rawOuter
  4505                         ? c.flatname.subName(c.owner.enclClass().flatname.getByteLength() + 1, c.flatname.getByteLength())
  4506                         : c.name);
  4507             } else {
  4508                 append(externalize(c.flatname));
  4510             if (ct.getTypeArguments().nonEmpty()) {
  4511                 append('<');
  4512                 assembleSig(ct.getTypeArguments());
  4513                 append('>');
  4517         public void assembleParamsSig(List<Type> typarams) {
  4518             append('<');
  4519             for (List<Type> ts = typarams; ts.nonEmpty(); ts = ts.tail) {
  4520                 Type.TypeVar tvar = (Type.TypeVar) ts.head;
  4521                 append(tvar.tsym.name);
  4522                 List<Type> bounds = types.getBounds(tvar);
  4523                 if ((bounds.head.tsym.flags() & INTERFACE) != 0) {
  4524                     append(':');
  4526                 for (List<Type> l = bounds; l.nonEmpty(); l = l.tail) {
  4527                     append(':');
  4528                     assembleSig(l.head);
  4531             append('>');
  4534         private void assembleSig(List<Type> types) {
  4535             for (List<Type> ts = types; ts.nonEmpty(); ts = ts.tail) {
  4536                 assembleSig(ts.head);
  4540     // </editor-fold>

mercurial