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

Tue, 20 Jan 2009 18:23:13 -0800

author
jjg
date
Tue, 20 Jan 2009 18:23:13 -0800
changeset 198
b4b1f7732289
parent 196
1ca2dc8584e1
child 202
3b2c55b7bd01
permissions
-rw-r--r--

6795903: fix latent build warnings in langtools repository
Reviewed-by: darcy

     1 /*
     2  * Copyright 2003-2008 Sun Microsystems, Inc.  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.  Sun designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
    22  * CA 95054 USA or visit www.sun.com if you need additional information or
    23  * have any questions.
    24  */
    26 package com.sun.tools.javac.code;
    28 import java.util.*;
    30 import com.sun.tools.javac.util.*;
    31 import com.sun.tools.javac.util.List;
    33 import com.sun.tools.javac.jvm.ClassReader;
    34 import com.sun.tools.javac.comp.Check;
    36 import static com.sun.tools.javac.code.Type.*;
    37 import static com.sun.tools.javac.code.TypeTags.*;
    38 import static com.sun.tools.javac.code.Symbol.*;
    39 import static com.sun.tools.javac.code.Flags.*;
    40 import static com.sun.tools.javac.code.BoundKind.*;
    41 import static com.sun.tools.javac.util.ListBuffer.lb;
    43 /**
    44  * Utility class containing various operations on types.
    45  *
    46  * <p>Unless other names are more illustrative, the following naming
    47  * conventions should be observed in this file:
    48  *
    49  * <dl>
    50  * <dt>t</dt>
    51  * <dd>If the first argument to an operation is a type, it should be named t.</dd>
    52  * <dt>s</dt>
    53  * <dd>Similarly, if the second argument to an operation is a type, it should be named s.</dd>
    54  * <dt>ts</dt>
    55  * <dd>If an operations takes a list of types, the first should be named ts.</dd>
    56  * <dt>ss</dt>
    57  * <dd>A second list of types should be named ss.</dd>
    58  * </dl>
    59  *
    60  * <p><b>This is NOT part of any API supported by Sun Microsystems.
    61  * If you write code that depends on this, you do so at your own risk.
    62  * This code and its internal interfaces are subject to change or
    63  * deletion without notice.</b>
    64  */
    65 public class Types {
    66     protected static final Context.Key<Types> typesKey =
    67         new Context.Key<Types>();
    69     final Symtab syms;
    70     final JavacMessages messages;
    71     final Names names;
    72     final boolean allowBoxing;
    73     final ClassReader reader;
    74     final Source source;
    75     final Check chk;
    76     List<Warner> warnStack = List.nil();
    77     final Name capturedName;
    79     // <editor-fold defaultstate="collapsed" desc="Instantiating">
    80     public static Types instance(Context context) {
    81         Types instance = context.get(typesKey);
    82         if (instance == null)
    83             instance = new Types(context);
    84         return instance;
    85     }
    87     protected Types(Context context) {
    88         context.put(typesKey, this);
    89         syms = Symtab.instance(context);
    90         names = Names.instance(context);
    91         allowBoxing = Source.instance(context).allowBoxing();
    92         reader = ClassReader.instance(context);
    93         source = Source.instance(context);
    94         chk = Check.instance(context);
    95         capturedName = names.fromString("<captured wildcard>");
    96         messages = JavacMessages.instance(context);
    97     }
    98     // </editor-fold>
   100     // <editor-fold defaultstate="collapsed" desc="upperBound">
   101     /**
   102      * The "rvalue conversion".<br>
   103      * The upper bound of most types is the type
   104      * itself.  Wildcards, on the other hand have upper
   105      * and lower bounds.
   106      * @param t a type
   107      * @return the upper bound of the given type
   108      */
   109     public Type upperBound(Type t) {
   110         return upperBound.visit(t);
   111     }
   112     // where
   113         private final MapVisitor<Void> upperBound = new MapVisitor<Void>() {
   115             @Override
   116             public Type visitWildcardType(WildcardType t, Void ignored) {
   117                 if (t.isSuperBound())
   118                     return t.bound == null ? syms.objectType : t.bound.bound;
   119                 else
   120                     return visit(t.type);
   121             }
   123             @Override
   124             public Type visitCapturedType(CapturedType t, Void ignored) {
   125                 return visit(t.bound);
   126             }
   127         };
   128     // </editor-fold>
   130     // <editor-fold defaultstate="collapsed" desc="lowerBound">
   131     /**
   132      * The "lvalue conversion".<br>
   133      * The lower bound of most types is the type
   134      * itself.  Wildcards, on the other hand have upper
   135      * and lower bounds.
   136      * @param t a type
   137      * @return the lower bound of the given type
   138      */
   139     public Type lowerBound(Type t) {
   140         return lowerBound.visit(t);
   141     }
   142     // where
   143         private final MapVisitor<Void> lowerBound = new MapVisitor<Void>() {
   145             @Override
   146             public Type visitWildcardType(WildcardType t, Void ignored) {
   147                 return t.isExtendsBound() ? syms.botType : visit(t.type);
   148             }
   150             @Override
   151             public Type visitCapturedType(CapturedType t, Void ignored) {
   152                 return visit(t.getLowerBound());
   153             }
   154         };
   155     // </editor-fold>
   157     // <editor-fold defaultstate="collapsed" desc="isUnbounded">
   158     /**
   159      * Checks that all the arguments to a class are unbounded
   160      * wildcards or something else that doesn't make any restrictions
   161      * on the arguments. If a class isUnbounded, a raw super- or
   162      * subclass can be cast to it without a warning.
   163      * @param t a type
   164      * @return true iff the given type is unbounded or raw
   165      */
   166     public boolean isUnbounded(Type t) {
   167         return isUnbounded.visit(t);
   168     }
   169     // where
   170         private final UnaryVisitor<Boolean> isUnbounded = new UnaryVisitor<Boolean>() {
   172             public Boolean visitType(Type t, Void ignored) {
   173                 return true;
   174             }
   176             @Override
   177             public Boolean visitClassType(ClassType t, Void ignored) {
   178                 List<Type> parms = t.tsym.type.allparams();
   179                 List<Type> args = t.allparams();
   180                 while (parms.nonEmpty()) {
   181                     WildcardType unb = new WildcardType(syms.objectType,
   182                                                         BoundKind.UNBOUND,
   183                                                         syms.boundClass,
   184                                                         (TypeVar)parms.head);
   185                     if (!containsType(args.head, unb))
   186                         return false;
   187                     parms = parms.tail;
   188                     args = args.tail;
   189                 }
   190                 return true;
   191             }
   192         };
   193     // </editor-fold>
   195     // <editor-fold defaultstate="collapsed" desc="asSub">
   196     /**
   197      * Return the least specific subtype of t that starts with symbol
   198      * sym.  If none exists, return null.  The least specific subtype
   199      * is determined as follows:
   200      *
   201      * <p>If there is exactly one parameterized instance of sym that is a
   202      * subtype of t, that parameterized instance is returned.<br>
   203      * Otherwise, if the plain type or raw type `sym' is a subtype of
   204      * type t, the type `sym' itself is returned.  Otherwise, null is
   205      * returned.
   206      */
   207     public Type asSub(Type t, Symbol sym) {
   208         return asSub.visit(t, sym);
   209     }
   210     // where
   211         private final SimpleVisitor<Type,Symbol> asSub = new SimpleVisitor<Type,Symbol>() {
   213             public Type visitType(Type t, Symbol sym) {
   214                 return null;
   215             }
   217             @Override
   218             public Type visitClassType(ClassType t, Symbol sym) {
   219                 if (t.tsym == sym)
   220                     return t;
   221                 Type base = asSuper(sym.type, t.tsym);
   222                 if (base == null)
   223                     return null;
   224                 ListBuffer<Type> from = new ListBuffer<Type>();
   225                 ListBuffer<Type> to = new ListBuffer<Type>();
   226                 try {
   227                     adapt(base, t, from, to);
   228                 } catch (AdaptFailure ex) {
   229                     return null;
   230                 }
   231                 Type res = subst(sym.type, from.toList(), to.toList());
   232                 if (!isSubtype(res, t))
   233                     return null;
   234                 ListBuffer<Type> openVars = new ListBuffer<Type>();
   235                 for (List<Type> l = sym.type.allparams();
   236                      l.nonEmpty(); l = l.tail)
   237                     if (res.contains(l.head) && !t.contains(l.head))
   238                         openVars.append(l.head);
   239                 if (openVars.nonEmpty()) {
   240                     if (t.isRaw()) {
   241                         // The subtype of a raw type is raw
   242                         res = erasure(res);
   243                     } else {
   244                         // Unbound type arguments default to ?
   245                         List<Type> opens = openVars.toList();
   246                         ListBuffer<Type> qs = new ListBuffer<Type>();
   247                         for (List<Type> iter = opens; iter.nonEmpty(); iter = iter.tail) {
   248                             qs.append(new WildcardType(syms.objectType, BoundKind.UNBOUND, syms.boundClass, (TypeVar) iter.head));
   249                         }
   250                         res = subst(res, opens, qs.toList());
   251                     }
   252                 }
   253                 return res;
   254             }
   256             @Override
   257             public Type visitErrorType(ErrorType t, Symbol sym) {
   258                 return t;
   259             }
   260         };
   261     // </editor-fold>
   263     // <editor-fold defaultstate="collapsed" desc="isConvertible">
   264     /**
   265      * Is t a subtype of or convertiable via boxing/unboxing
   266      * convertions to s?
   267      */
   268     public boolean isConvertible(Type t, Type s, Warner warn) {
   269         boolean tPrimitive = t.isPrimitive();
   270         boolean sPrimitive = s.isPrimitive();
   271         if (tPrimitive == sPrimitive)
   272             return isSubtypeUnchecked(t, s, warn);
   273         if (!allowBoxing) return false;
   274         return tPrimitive
   275             ? isSubtype(boxedClass(t).type, s)
   276             : isSubtype(unboxedType(t), s);
   277     }
   279     /**
   280      * Is t a subtype of or convertiable via boxing/unboxing
   281      * convertions to s?
   282      */
   283     public boolean isConvertible(Type t, Type s) {
   284         return isConvertible(t, s, Warner.noWarnings);
   285     }
   286     // </editor-fold>
   288     // <editor-fold defaultstate="collapsed" desc="isSubtype">
   289     /**
   290      * Is t an unchecked subtype of s?
   291      */
   292     public boolean isSubtypeUnchecked(Type t, Type s) {
   293         return isSubtypeUnchecked(t, s, Warner.noWarnings);
   294     }
   295     /**
   296      * Is t an unchecked subtype of s?
   297      */
   298     public boolean isSubtypeUnchecked(Type t, Type s, Warner warn) {
   299         if (t.tag == ARRAY && s.tag == ARRAY) {
   300             return (((ArrayType)t).elemtype.tag <= lastBaseTag)
   301                 ? isSameType(elemtype(t), elemtype(s))
   302                 : isSubtypeUnchecked(elemtype(t), elemtype(s), warn);
   303         } else if (isSubtype(t, s)) {
   304             return true;
   305         }
   306         else if (t.tag == TYPEVAR) {
   307             return isSubtypeUnchecked(t.getUpperBound(), s, warn);
   308         }
   309         else if (s.tag == UNDETVAR) {
   310             UndetVar uv = (UndetVar)s;
   311             if (uv.inst != null)
   312                 return isSubtypeUnchecked(t, uv.inst, warn);
   313         }
   314         else if (!s.isRaw()) {
   315             Type t2 = asSuper(t, s.tsym);
   316             if (t2 != null && t2.isRaw()) {
   317                 if (isReifiable(s))
   318                     warn.silentUnchecked();
   319                 else
   320                     warn.warnUnchecked();
   321                 return true;
   322             }
   323         }
   324         return false;
   325     }
   327     /**
   328      * Is t a subtype of s?<br>
   329      * (not defined for Method and ForAll types)
   330      */
   331     final public boolean isSubtype(Type t, Type s) {
   332         return isSubtype(t, s, true);
   333     }
   334     final public boolean isSubtypeNoCapture(Type t, Type s) {
   335         return isSubtype(t, s, false);
   336     }
   337     public boolean isSubtype(Type t, Type s, boolean capture) {
   338         if (t == s)
   339             return true;
   341         if (s.tag >= firstPartialTag)
   342             return isSuperType(s, t);
   344         Type lower = lowerBound(s);
   345         if (s != lower)
   346             return isSubtype(capture ? capture(t) : t, lower, false);
   348         return isSubtype.visit(capture ? capture(t) : t, s);
   349     }
   350     // where
   351         private TypeRelation isSubtype = new TypeRelation()
   352         {
   353             public Boolean visitType(Type t, Type s) {
   354                 switch (t.tag) {
   355                 case BYTE: case CHAR:
   356                     return (t.tag == s.tag ||
   357                               t.tag + 2 <= s.tag && s.tag <= DOUBLE);
   358                 case SHORT: case INT: case LONG: case FLOAT: case DOUBLE:
   359                     return t.tag <= s.tag && s.tag <= DOUBLE;
   360                 case BOOLEAN: case VOID:
   361                     return t.tag == s.tag;
   362                 case TYPEVAR:
   363                     return isSubtypeNoCapture(t.getUpperBound(), s);
   364                 case BOT:
   365                     return
   366                         s.tag == BOT || s.tag == CLASS ||
   367                         s.tag == ARRAY || s.tag == TYPEVAR;
   368                 case NONE:
   369                     return false;
   370                 default:
   371                     throw new AssertionError("isSubtype " + t.tag);
   372                 }
   373             }
   375             private Set<TypePair> cache = new HashSet<TypePair>();
   377             private boolean containsTypeRecursive(Type t, Type s) {
   378                 TypePair pair = new TypePair(t, s);
   379                 if (cache.add(pair)) {
   380                     try {
   381                         return containsType(t.getTypeArguments(),
   382                                             s.getTypeArguments());
   383                     } finally {
   384                         cache.remove(pair);
   385                     }
   386                 } else {
   387                     return containsType(t.getTypeArguments(),
   388                                         rewriteSupers(s).getTypeArguments());
   389                 }
   390             }
   392             private Type rewriteSupers(Type t) {
   393                 if (!t.isParameterized())
   394                     return t;
   395                 ListBuffer<Type> from = lb();
   396                 ListBuffer<Type> to = lb();
   397                 adaptSelf(t, from, to);
   398                 if (from.isEmpty())
   399                     return t;
   400                 ListBuffer<Type> rewrite = lb();
   401                 boolean changed = false;
   402                 for (Type orig : to.toList()) {
   403                     Type s = rewriteSupers(orig);
   404                     if (s.isSuperBound() && !s.isExtendsBound()) {
   405                         s = new WildcardType(syms.objectType,
   406                                              BoundKind.UNBOUND,
   407                                              syms.boundClass);
   408                         changed = true;
   409                     } else if (s != orig) {
   410                         s = new WildcardType(upperBound(s),
   411                                              BoundKind.EXTENDS,
   412                                              syms.boundClass);
   413                         changed = true;
   414                     }
   415                     rewrite.append(s);
   416                 }
   417                 if (changed)
   418                     return subst(t.tsym.type, from.toList(), rewrite.toList());
   419                 else
   420                     return t;
   421             }
   423             @Override
   424             public Boolean visitClassType(ClassType t, Type s) {
   425                 Type sup = asSuper(t, s.tsym);
   426                 return sup != null
   427                     && sup.tsym == s.tsym
   428                     // You're not allowed to write
   429                     //     Vector<Object> vec = new Vector<String>();
   430                     // But with wildcards you can write
   431                     //     Vector<? extends Object> vec = new Vector<String>();
   432                     // which means that subtype checking must be done
   433                     // here instead of same-type checking (via containsType).
   434                     && (!s.isParameterized() || containsTypeRecursive(s, sup))
   435                     && isSubtypeNoCapture(sup.getEnclosingType(),
   436                                           s.getEnclosingType());
   437             }
   439             @Override
   440             public Boolean visitArrayType(ArrayType t, Type s) {
   441                 if (s.tag == ARRAY) {
   442                     if (t.elemtype.tag <= lastBaseTag)
   443                         return isSameType(t.elemtype, elemtype(s));
   444                     else
   445                         return isSubtypeNoCapture(t.elemtype, elemtype(s));
   446                 }
   448                 if (s.tag == CLASS) {
   449                     Name sname = s.tsym.getQualifiedName();
   450                     return sname == names.java_lang_Object
   451                         || sname == names.java_lang_Cloneable
   452                         || sname == names.java_io_Serializable;
   453                 }
   455                 return false;
   456             }
   458             @Override
   459             public Boolean visitUndetVar(UndetVar t, Type s) {
   460                 //todo: test against origin needed? or replace with substitution?
   461                 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN)
   462                     return true;
   464                 if (t.inst != null)
   465                     return isSubtypeNoCapture(t.inst, s); // TODO: ", warn"?
   467                 t.hibounds = t.hibounds.prepend(s);
   468                 return true;
   469             }
   471             @Override
   472             public Boolean visitErrorType(ErrorType t, Type s) {
   473                 return true;
   474             }
   475         };
   477     /**
   478      * Is t a subtype of every type in given list `ts'?<br>
   479      * (not defined for Method and ForAll types)<br>
   480      * Allows unchecked conversions.
   481      */
   482     public boolean isSubtypeUnchecked(Type t, List<Type> ts, Warner warn) {
   483         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
   484             if (!isSubtypeUnchecked(t, l.head, warn))
   485                 return false;
   486         return true;
   487     }
   489     /**
   490      * Are corresponding elements of ts subtypes of ss?  If lists are
   491      * of different length, return false.
   492      */
   493     public boolean isSubtypes(List<Type> ts, List<Type> ss) {
   494         while (ts.tail != null && ss.tail != null
   495                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   496                isSubtype(ts.head, ss.head)) {
   497             ts = ts.tail;
   498             ss = ss.tail;
   499         }
   500         return ts.tail == null && ss.tail == null;
   501         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   502     }
   504     /**
   505      * Are corresponding elements of ts subtypes of ss, allowing
   506      * unchecked conversions?  If lists are of different length,
   507      * return false.
   508      **/
   509     public boolean isSubtypesUnchecked(List<Type> ts, List<Type> ss, Warner warn) {
   510         while (ts.tail != null && ss.tail != null
   511                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   512                isSubtypeUnchecked(ts.head, ss.head, warn)) {
   513             ts = ts.tail;
   514             ss = ss.tail;
   515         }
   516         return ts.tail == null && ss.tail == null;
   517         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   518     }
   519     // </editor-fold>
   521     // <editor-fold defaultstate="collapsed" desc="isSuperType">
   522     /**
   523      * Is t a supertype of s?
   524      */
   525     public boolean isSuperType(Type t, Type s) {
   526         switch (t.tag) {
   527         case ERROR:
   528             return true;
   529         case UNDETVAR: {
   530             UndetVar undet = (UndetVar)t;
   531             if (t == s ||
   532                 undet.qtype == s ||
   533                 s.tag == ERROR ||
   534                 s.tag == BOT) return true;
   535             if (undet.inst != null)
   536                 return isSubtype(s, undet.inst);
   537             undet.lobounds = undet.lobounds.prepend(s);
   538             return true;
   539         }
   540         default:
   541             return isSubtype(s, t);
   542         }
   543     }
   544     // </editor-fold>
   546     // <editor-fold defaultstate="collapsed" desc="isSameType">
   547     /**
   548      * Are corresponding elements of the lists the same type?  If
   549      * lists are of different length, return false.
   550      */
   551     public boolean isSameTypes(List<Type> ts, List<Type> ss) {
   552         while (ts.tail != null && ss.tail != null
   553                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   554                isSameType(ts.head, ss.head)) {
   555             ts = ts.tail;
   556             ss = ss.tail;
   557         }
   558         return ts.tail == null && ss.tail == null;
   559         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   560     }
   562     /**
   563      * Is t the same type as s?
   564      */
   565     public boolean isSameType(Type t, Type s) {
   566         return isSameType.visit(t, s);
   567     }
   568     // where
   569         private TypeRelation isSameType = new TypeRelation() {
   571             public Boolean visitType(Type t, Type s) {
   572                 if (t == s)
   573                     return true;
   575                 if (s.tag >= firstPartialTag)
   576                     return visit(s, t);
   578                 switch (t.tag) {
   579                 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
   580                 case DOUBLE: case BOOLEAN: case VOID: case BOT: case NONE:
   581                     return t.tag == s.tag;
   582                 case TYPEVAR:
   583                     return s.isSuperBound()
   584                         && !s.isExtendsBound()
   585                         && visit(t, upperBound(s));
   586                 default:
   587                     throw new AssertionError("isSameType " + t.tag);
   588                 }
   589             }
   591             @Override
   592             public Boolean visitWildcardType(WildcardType t, Type s) {
   593                 if (s.tag >= firstPartialTag)
   594                     return visit(s, t);
   595                 else
   596                     return false;
   597             }
   599             @Override
   600             public Boolean visitClassType(ClassType t, Type s) {
   601                 if (t == s)
   602                     return true;
   604                 if (s.tag >= firstPartialTag)
   605                     return visit(s, t);
   607                 if (s.isSuperBound() && !s.isExtendsBound())
   608                     return visit(t, upperBound(s)) && visit(t, lowerBound(s));
   610                 if (t.isCompound() && s.isCompound()) {
   611                     if (!visit(supertype(t), supertype(s)))
   612                         return false;
   614                     HashSet<SingletonType> set = new HashSet<SingletonType>();
   615                     for (Type x : interfaces(t))
   616                         set.add(new SingletonType(x));
   617                     for (Type x : interfaces(s)) {
   618                         if (!set.remove(new SingletonType(x)))
   619                             return false;
   620                     }
   621                     return (set.size() == 0);
   622                 }
   623                 return t.tsym == s.tsym
   624                     && visit(t.getEnclosingType(), s.getEnclosingType())
   625                     && containsTypeEquivalent(t.getTypeArguments(), s.getTypeArguments());
   626             }
   628             @Override
   629             public Boolean visitArrayType(ArrayType t, Type s) {
   630                 if (t == s)
   631                     return true;
   633                 if (s.tag >= firstPartialTag)
   634                     return visit(s, t);
   636                 return s.tag == ARRAY
   637                     && containsTypeEquivalent(t.elemtype, elemtype(s));
   638             }
   640             @Override
   641             public Boolean visitMethodType(MethodType t, Type s) {
   642                 // isSameType for methods does not take thrown
   643                 // exceptions into account!
   644                 return hasSameArgs(t, s) && visit(t.getReturnType(), s.getReturnType());
   645             }
   647             @Override
   648             public Boolean visitPackageType(PackageType t, Type s) {
   649                 return t == s;
   650             }
   652             @Override
   653             public Boolean visitForAll(ForAll t, Type s) {
   654                 if (s.tag != FORALL)
   655                     return false;
   657                 ForAll forAll = (ForAll)s;
   658                 return hasSameBounds(t, forAll)
   659                     && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
   660             }
   662             @Override
   663             public Boolean visitUndetVar(UndetVar t, Type s) {
   664                 if (s.tag == WILDCARD)
   665                     // FIXME, this might be leftovers from before capture conversion
   666                     return false;
   668                 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN)
   669                     return true;
   671                 if (t.inst != null)
   672                     return visit(t.inst, s);
   674                 t.inst = fromUnknownFun.apply(s);
   675                 for (List<Type> l = t.lobounds; l.nonEmpty(); l = l.tail) {
   676                     if (!isSubtype(l.head, t.inst))
   677                         return false;
   678                 }
   679                 for (List<Type> l = t.hibounds; l.nonEmpty(); l = l.tail) {
   680                     if (!isSubtype(t.inst, l.head))
   681                         return false;
   682                 }
   683                 return true;
   684             }
   686             @Override
   687             public Boolean visitErrorType(ErrorType t, Type s) {
   688                 return true;
   689             }
   690         };
   691     // </editor-fold>
   693     // <editor-fold defaultstate="collapsed" desc="fromUnknownFun">
   694     /**
   695      * A mapping that turns all unknown types in this type to fresh
   696      * unknown variables.
   697      */
   698     public Mapping fromUnknownFun = new Mapping("fromUnknownFun") {
   699             public Type apply(Type t) {
   700                 if (t.tag == UNKNOWN) return new UndetVar(t);
   701                 else return t.map(this);
   702             }
   703         };
   704     // </editor-fold>
   706     // <editor-fold defaultstate="collapsed" desc="Contains Type">
   707     public boolean containedBy(Type t, Type s) {
   708         switch (t.tag) {
   709         case UNDETVAR:
   710             if (s.tag == WILDCARD) {
   711                 UndetVar undetvar = (UndetVar)t;
   712                 undetvar.inst = glb(upperBound(s), undetvar.inst);
   713                 // We should check instantiated type against any of the
   714                 // undetvar's lower bounds.
   715                 for (Type t2 : undetvar.lobounds) {
   716                     if (!isSubtype(t2, undetvar.inst))
   717                         return false;
   718                 }
   719                 return true;
   720             } else {
   721                 return isSameType(t, s);
   722             }
   723         case ERROR:
   724             return true;
   725         default:
   726             return containsType(s, t);
   727         }
   728     }
   730     boolean containsType(List<Type> ts, List<Type> ss) {
   731         while (ts.nonEmpty() && ss.nonEmpty()
   732                && containsType(ts.head, ss.head)) {
   733             ts = ts.tail;
   734             ss = ss.tail;
   735         }
   736         return ts.isEmpty() && ss.isEmpty();
   737     }
   739     /**
   740      * Check if t contains s.
   741      *
   742      * <p>T contains S if:
   743      *
   744      * <p>{@code L(T) <: L(S) && U(S) <: U(T)}
   745      *
   746      * <p>This relation is only used by ClassType.isSubtype(), that
   747      * is,
   748      *
   749      * <p>{@code C<S> <: C<T> if T contains S.}
   750      *
   751      * <p>Because of F-bounds, this relation can lead to infinite
   752      * recursion.  Thus we must somehow break that recursion.  Notice
   753      * that containsType() is only called from ClassType.isSubtype().
   754      * Since the arguments have already been checked against their
   755      * bounds, we know:
   756      *
   757      * <p>{@code U(S) <: U(T) if T is "super" bound (U(T) *is* the bound)}
   758      *
   759      * <p>{@code L(T) <: L(S) if T is "extends" bound (L(T) is bottom)}
   760      *
   761      * @param t a type
   762      * @param s a type
   763      */
   764     public boolean containsType(Type t, Type s) {
   765         return containsType.visit(t, s);
   766     }
   767     // where
   768         private TypeRelation containsType = new TypeRelation() {
   770             private Type U(Type t) {
   771                 while (t.tag == WILDCARD) {
   772                     WildcardType w = (WildcardType)t;
   773                     if (w.isSuperBound())
   774                         return w.bound == null ? syms.objectType : w.bound.bound;
   775                     else
   776                         t = w.type;
   777                 }
   778                 return t;
   779             }
   781             private Type L(Type t) {
   782                 while (t.tag == WILDCARD) {
   783                     WildcardType w = (WildcardType)t;
   784                     if (w.isExtendsBound())
   785                         return syms.botType;
   786                     else
   787                         t = w.type;
   788                 }
   789                 return t;
   790             }
   792             public Boolean visitType(Type t, Type s) {
   793                 if (s.tag >= firstPartialTag)
   794                     return containedBy(s, t);
   795                 else
   796                     return isSameType(t, s);
   797             }
   799             void debugContainsType(WildcardType t, Type s) {
   800                 System.err.println();
   801                 System.err.format(" does %s contain %s?%n", t, s);
   802                 System.err.format(" %s U(%s) <: U(%s) %s = %s%n",
   803                                   upperBound(s), s, t, U(t),
   804                                   t.isSuperBound()
   805                                   || isSubtypeNoCapture(upperBound(s), U(t)));
   806                 System.err.format(" %s L(%s) <: L(%s) %s = %s%n",
   807                                   L(t), t, s, lowerBound(s),
   808                                   t.isExtendsBound()
   809                                   || isSubtypeNoCapture(L(t), lowerBound(s)));
   810                 System.err.println();
   811             }
   813             @Override
   814             public Boolean visitWildcardType(WildcardType t, Type s) {
   815                 if (s.tag >= firstPartialTag)
   816                     return containedBy(s, t);
   817                 else {
   818                     // debugContainsType(t, s);
   819                     return isSameWildcard(t, s)
   820                         || isCaptureOf(s, t)
   821                         || ((t.isExtendsBound() || isSubtypeNoCapture(L(t), lowerBound(s))) &&
   822                             (t.isSuperBound() || isSubtypeNoCapture(upperBound(s), U(t))));
   823                 }
   824             }
   826             @Override
   827             public Boolean visitUndetVar(UndetVar t, Type s) {
   828                 if (s.tag != WILDCARD)
   829                     return isSameType(t, s);
   830                 else
   831                     return false;
   832             }
   834             @Override
   835             public Boolean visitErrorType(ErrorType t, Type s) {
   836                 return true;
   837             }
   838         };
   840     public boolean isCaptureOf(Type s, WildcardType t) {
   841         if (s.tag != TYPEVAR || !((TypeVar)s).isCaptured())
   842             return false;
   843         return isSameWildcard(t, ((CapturedType)s).wildcard);
   844     }
   846     public boolean isSameWildcard(WildcardType t, Type s) {
   847         if (s.tag != WILDCARD)
   848             return false;
   849         WildcardType w = (WildcardType)s;
   850         return w.kind == t.kind && w.type == t.type;
   851     }
   853     public boolean containsTypeEquivalent(List<Type> ts, List<Type> ss) {
   854         while (ts.nonEmpty() && ss.nonEmpty()
   855                && containsTypeEquivalent(ts.head, ss.head)) {
   856             ts = ts.tail;
   857             ss = ss.tail;
   858         }
   859         return ts.isEmpty() && ss.isEmpty();
   860     }
   861     // </editor-fold>
   863     // <editor-fold defaultstate="collapsed" desc="isCastable">
   864     public boolean isCastable(Type t, Type s) {
   865         return isCastable(t, s, Warner.noWarnings);
   866     }
   868     /**
   869      * Is t is castable to s?<br>
   870      * s is assumed to be an erased type.<br>
   871      * (not defined for Method and ForAll types).
   872      */
   873     public boolean isCastable(Type t, Type s, Warner warn) {
   874         if (t == s)
   875             return true;
   877         if (t.isPrimitive() != s.isPrimitive())
   878             return allowBoxing && isConvertible(t, s, warn);
   880         if (warn != warnStack.head) {
   881             try {
   882                 warnStack = warnStack.prepend(warn);
   883                 return isCastable.visit(t,s);
   884             } finally {
   885                 warnStack = warnStack.tail;
   886             }
   887         } else {
   888             return isCastable.visit(t,s);
   889         }
   890     }
   891     // where
   892         private TypeRelation isCastable = new TypeRelation() {
   894             public Boolean visitType(Type t, Type s) {
   895                 if (s.tag == ERROR)
   896                     return true;
   898                 switch (t.tag) {
   899                 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
   900                 case DOUBLE:
   901                     return s.tag <= DOUBLE;
   902                 case BOOLEAN:
   903                     return s.tag == BOOLEAN;
   904                 case VOID:
   905                     return false;
   906                 case BOT:
   907                     return isSubtype(t, s);
   908                 default:
   909                     throw new AssertionError();
   910                 }
   911             }
   913             @Override
   914             public Boolean visitWildcardType(WildcardType t, Type s) {
   915                 return isCastable(upperBound(t), s, warnStack.head);
   916             }
   918             @Override
   919             public Boolean visitClassType(ClassType t, Type s) {
   920                 if (s.tag == ERROR || s.tag == BOT)
   921                     return true;
   923                 if (s.tag == TYPEVAR) {
   924                     if (isCastable(s.getUpperBound(), t, Warner.noWarnings)) {
   925                         warnStack.head.warnUnchecked();
   926                         return true;
   927                     } else {
   928                         return false;
   929                     }
   930                 }
   932                 if (t.isCompound()) {
   933                     if (!visit(supertype(t), s))
   934                         return false;
   935                     for (Type intf : interfaces(t)) {
   936                         if (!visit(intf, s))
   937                             return false;
   938                     }
   939                     return true;
   940                 }
   942                 if (s.isCompound()) {
   943                     // call recursively to reuse the above code
   944                     return visitClassType((ClassType)s, t);
   945                 }
   947                 if (s.tag == CLASS || s.tag == ARRAY) {
   948                     boolean upcast;
   949                     if ((upcast = isSubtype(erasure(t), erasure(s)))
   950                         || isSubtype(erasure(s), erasure(t))) {
   951                         if (!upcast && s.tag == ARRAY) {
   952                             if (!isReifiable(s))
   953                                 warnStack.head.warnUnchecked();
   954                             return true;
   955                         } else if (s.isRaw()) {
   956                             return true;
   957                         } else if (t.isRaw()) {
   958                             if (!isUnbounded(s))
   959                                 warnStack.head.warnUnchecked();
   960                             return true;
   961                         }
   962                         // Assume |a| <: |b|
   963                         final Type a = upcast ? t : s;
   964                         final Type b = upcast ? s : t;
   965                         final boolean HIGH = true;
   966                         final boolean LOW = false;
   967                         final boolean DONT_REWRITE_TYPEVARS = false;
   968                         Type aHigh = rewriteQuantifiers(a, HIGH, DONT_REWRITE_TYPEVARS);
   969                         Type aLow  = rewriteQuantifiers(a, LOW,  DONT_REWRITE_TYPEVARS);
   970                         Type bHigh = rewriteQuantifiers(b, HIGH, DONT_REWRITE_TYPEVARS);
   971                         Type bLow  = rewriteQuantifiers(b, LOW,  DONT_REWRITE_TYPEVARS);
   972                         Type lowSub = asSub(bLow, aLow.tsym);
   973                         Type highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
   974                         if (highSub == null) {
   975                             final boolean REWRITE_TYPEVARS = true;
   976                             aHigh = rewriteQuantifiers(a, HIGH, REWRITE_TYPEVARS);
   977                             aLow  = rewriteQuantifiers(a, LOW,  REWRITE_TYPEVARS);
   978                             bHigh = rewriteQuantifiers(b, HIGH, REWRITE_TYPEVARS);
   979                             bLow  = rewriteQuantifiers(b, LOW,  REWRITE_TYPEVARS);
   980                             lowSub = asSub(bLow, aLow.tsym);
   981                             highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
   982                         }
   983                         if (highSub != null) {
   984                             assert a.tsym == highSub.tsym && a.tsym == lowSub.tsym
   985                                 : a.tsym + " != " + highSub.tsym + " != " + lowSub.tsym;
   986                             if (!disjointTypes(aHigh.allparams(), highSub.allparams())
   987                                 && !disjointTypes(aHigh.allparams(), lowSub.allparams())
   988                                 && !disjointTypes(aLow.allparams(), highSub.allparams())
   989                                 && !disjointTypes(aLow.allparams(), lowSub.allparams())) {
   990                                 if (upcast ? giveWarning(a, highSub) || giveWarning(a, lowSub)
   991                                            : giveWarning(highSub, a) || giveWarning(lowSub, a))
   992                                     warnStack.head.warnUnchecked();
   993                                 return true;
   994                             }
   995                         }
   996                         if (isReifiable(s))
   997                             return isSubtypeUnchecked(a, b);
   998                         else
   999                             return isSubtypeUnchecked(a, b, warnStack.head);
  1002                     // Sidecast
  1003                     if (s.tag == CLASS) {
  1004                         if ((s.tsym.flags() & INTERFACE) != 0) {
  1005                             return ((t.tsym.flags() & FINAL) == 0)
  1006                                 ? sideCast(t, s, warnStack.head)
  1007                                 : sideCastFinal(t, s, warnStack.head);
  1008                         } else if ((t.tsym.flags() & INTERFACE) != 0) {
  1009                             return ((s.tsym.flags() & FINAL) == 0)
  1010                                 ? sideCast(t, s, warnStack.head)
  1011                                 : sideCastFinal(t, s, warnStack.head);
  1012                         } else {
  1013                             // unrelated class types
  1014                             return false;
  1018                 return false;
  1021             @Override
  1022             public Boolean visitArrayType(ArrayType t, Type s) {
  1023                 switch (s.tag) {
  1024                 case ERROR:
  1025                 case BOT:
  1026                     return true;
  1027                 case TYPEVAR:
  1028                     if (isCastable(s, t, Warner.noWarnings)) {
  1029                         warnStack.head.warnUnchecked();
  1030                         return true;
  1031                     } else {
  1032                         return false;
  1034                 case CLASS:
  1035                     return isSubtype(t, s);
  1036                 case ARRAY:
  1037                     if (elemtype(t).tag <= lastBaseTag) {
  1038                         return elemtype(t).tag == elemtype(s).tag;
  1039                     } else {
  1040                         return visit(elemtype(t), elemtype(s));
  1042                 default:
  1043                     return false;
  1047             @Override
  1048             public Boolean visitTypeVar(TypeVar t, Type s) {
  1049                 switch (s.tag) {
  1050                 case ERROR:
  1051                 case BOT:
  1052                     return true;
  1053                 case TYPEVAR:
  1054                     if (isSubtype(t, s)) {
  1055                         return true;
  1056                     } else if (isCastable(t.bound, s, Warner.noWarnings)) {
  1057                         warnStack.head.warnUnchecked();
  1058                         return true;
  1059                     } else {
  1060                         return false;
  1062                 default:
  1063                     return isCastable(t.bound, s, warnStack.head);
  1067             @Override
  1068             public Boolean visitErrorType(ErrorType t, Type s) {
  1069                 return true;
  1071         };
  1072     // </editor-fold>
  1074     // <editor-fold defaultstate="collapsed" desc="disjointTypes">
  1075     public boolean disjointTypes(List<Type> ts, List<Type> ss) {
  1076         while (ts.tail != null && ss.tail != null) {
  1077             if (disjointType(ts.head, ss.head)) return true;
  1078             ts = ts.tail;
  1079             ss = ss.tail;
  1081         return false;
  1084     /**
  1085      * Two types or wildcards are considered disjoint if it can be
  1086      * proven that no type can be contained in both. It is
  1087      * conservative in that it is allowed to say that two types are
  1088      * not disjoint, even though they actually are.
  1090      * The type C<X> is castable to C<Y> exactly if X and Y are not
  1091      * disjoint.
  1092      */
  1093     public boolean disjointType(Type t, Type s) {
  1094         return disjointType.visit(t, s);
  1096     // where
  1097         private TypeRelation disjointType = new TypeRelation() {
  1099             private Set<TypePair> cache = new HashSet<TypePair>();
  1101             public Boolean visitType(Type t, Type s) {
  1102                 if (s.tag == WILDCARD)
  1103                     return visit(s, t);
  1104                 else
  1105                     return notSoftSubtypeRecursive(t, s) || notSoftSubtypeRecursive(s, t);
  1108             private boolean isCastableRecursive(Type t, Type s) {
  1109                 TypePair pair = new TypePair(t, s);
  1110                 if (cache.add(pair)) {
  1111                     try {
  1112                         return Types.this.isCastable(t, s);
  1113                     } finally {
  1114                         cache.remove(pair);
  1116                 } else {
  1117                     return true;
  1121             private boolean notSoftSubtypeRecursive(Type t, Type s) {
  1122                 TypePair pair = new TypePair(t, s);
  1123                 if (cache.add(pair)) {
  1124                     try {
  1125                         return Types.this.notSoftSubtype(t, s);
  1126                     } finally {
  1127                         cache.remove(pair);
  1129                 } else {
  1130                     return false;
  1134             @Override
  1135             public Boolean visitWildcardType(WildcardType t, Type s) {
  1136                 if (t.isUnbound())
  1137                     return false;
  1139                 if (s.tag != WILDCARD) {
  1140                     if (t.isExtendsBound())
  1141                         return notSoftSubtypeRecursive(s, t.type);
  1142                     else // isSuperBound()
  1143                         return notSoftSubtypeRecursive(t.type, s);
  1146                 if (s.isUnbound())
  1147                     return false;
  1149                 if (t.isExtendsBound()) {
  1150                     if (s.isExtendsBound())
  1151                         return !isCastableRecursive(t.type, upperBound(s));
  1152                     else if (s.isSuperBound())
  1153                         return notSoftSubtypeRecursive(lowerBound(s), t.type);
  1154                 } else if (t.isSuperBound()) {
  1155                     if (s.isExtendsBound())
  1156                         return notSoftSubtypeRecursive(t.type, upperBound(s));
  1158                 return false;
  1160         };
  1161     // </editor-fold>
  1163     // <editor-fold defaultstate="collapsed" desc="lowerBoundArgtypes">
  1164     /**
  1165      * Returns the lower bounds of the formals of a method.
  1166      */
  1167     public List<Type> lowerBoundArgtypes(Type t) {
  1168         return map(t.getParameterTypes(), lowerBoundMapping);
  1170     private final Mapping lowerBoundMapping = new Mapping("lowerBound") {
  1171             public Type apply(Type t) {
  1172                 return lowerBound(t);
  1174         };
  1175     // </editor-fold>
  1177     // <editor-fold defaultstate="collapsed" desc="notSoftSubtype">
  1178     /**
  1179      * This relation answers the question: is impossible that
  1180      * something of type `t' can be a subtype of `s'? This is
  1181      * different from the question "is `t' not a subtype of `s'?"
  1182      * when type variables are involved: Integer is not a subtype of T
  1183      * where <T extends Number> but it is not true that Integer cannot
  1184      * possibly be a subtype of T.
  1185      */
  1186     public boolean notSoftSubtype(Type t, Type s) {
  1187         if (t == s) return false;
  1188         if (t.tag == TYPEVAR) {
  1189             TypeVar tv = (TypeVar) t;
  1190             if (s.tag == TYPEVAR)
  1191                 s = s.getUpperBound();
  1192             return !isCastable(tv.bound,
  1193                                s,
  1194                                Warner.noWarnings);
  1196         if (s.tag != WILDCARD)
  1197             s = upperBound(s);
  1198         if (s.tag == TYPEVAR)
  1199             s = s.getUpperBound();
  1201         return !isSubtype(t, s);
  1203     // </editor-fold>
  1205     // <editor-fold defaultstate="collapsed" desc="isReifiable">
  1206     public boolean isReifiable(Type t) {
  1207         return isReifiable.visit(t);
  1209     // where
  1210         private UnaryVisitor<Boolean> isReifiable = new UnaryVisitor<Boolean>() {
  1212             public Boolean visitType(Type t, Void ignored) {
  1213                 return true;
  1216             @Override
  1217             public Boolean visitClassType(ClassType t, Void ignored) {
  1218                 if (!t.isParameterized())
  1219                     return true;
  1221                 for (Type param : t.allparams()) {
  1222                     if (!param.isUnbound())
  1223                         return false;
  1225                 return true;
  1228             @Override
  1229             public Boolean visitArrayType(ArrayType t, Void ignored) {
  1230                 return visit(t.elemtype);
  1233             @Override
  1234             public Boolean visitTypeVar(TypeVar t, Void ignored) {
  1235                 return false;
  1237         };
  1238     // </editor-fold>
  1240     // <editor-fold defaultstate="collapsed" desc="Array Utils">
  1241     public boolean isArray(Type t) {
  1242         while (t.tag == WILDCARD)
  1243             t = upperBound(t);
  1244         return t.tag == ARRAY;
  1247     /**
  1248      * The element type of an array.
  1249      */
  1250     public Type elemtype(Type t) {
  1251         switch (t.tag) {
  1252         case WILDCARD:
  1253             return elemtype(upperBound(t));
  1254         case ARRAY:
  1255             return ((ArrayType)t).elemtype;
  1256         case FORALL:
  1257             return elemtype(((ForAll)t).qtype);
  1258         case ERROR:
  1259             return t;
  1260         default:
  1261             return null;
  1265     /**
  1266      * Mapping to take element type of an arraytype
  1267      */
  1268     private Mapping elemTypeFun = new Mapping ("elemTypeFun") {
  1269         public Type apply(Type t) { return elemtype(t); }
  1270     };
  1272     /**
  1273      * The number of dimensions of an array type.
  1274      */
  1275     public int dimensions(Type t) {
  1276         int result = 0;
  1277         while (t.tag == ARRAY) {
  1278             result++;
  1279             t = elemtype(t);
  1281         return result;
  1283     // </editor-fold>
  1285     // <editor-fold defaultstate="collapsed" desc="asSuper">
  1286     /**
  1287      * Return the (most specific) base type of t that starts with the
  1288      * given symbol.  If none exists, return null.
  1290      * @param t a type
  1291      * @param sym a symbol
  1292      */
  1293     public Type asSuper(Type t, Symbol sym) {
  1294         return asSuper.visit(t, sym);
  1296     // where
  1297         private SimpleVisitor<Type,Symbol> asSuper = new SimpleVisitor<Type,Symbol>() {
  1299             public Type visitType(Type t, Symbol sym) {
  1300                 return null;
  1303             @Override
  1304             public Type visitClassType(ClassType t, Symbol sym) {
  1305                 if (t.tsym == sym)
  1306                     return t;
  1308                 Type st = supertype(t);
  1309                 if (st.tag == CLASS || st.tag == TYPEVAR || st.tag == ERROR) {
  1310                     Type x = asSuper(st, sym);
  1311                     if (x != null)
  1312                         return x;
  1314                 if ((sym.flags() & INTERFACE) != 0) {
  1315                     for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
  1316                         Type x = asSuper(l.head, sym);
  1317                         if (x != null)
  1318                             return x;
  1321                 return null;
  1324             @Override
  1325             public Type visitArrayType(ArrayType t, Symbol sym) {
  1326                 return isSubtype(t, sym.type) ? sym.type : null;
  1329             @Override
  1330             public Type visitTypeVar(TypeVar t, Symbol sym) {
  1331                 if (t.tsym == sym)
  1332                     return t;
  1333                 else
  1334                     return asSuper(t.bound, sym);
  1337             @Override
  1338             public Type visitErrorType(ErrorType t, Symbol sym) {
  1339                 return t;
  1341         };
  1343     /**
  1344      * Return the base type of t or any of its outer types that starts
  1345      * with the given symbol.  If none exists, return null.
  1347      * @param t a type
  1348      * @param sym a symbol
  1349      */
  1350     public Type asOuterSuper(Type t, Symbol sym) {
  1351         switch (t.tag) {
  1352         case CLASS:
  1353             do {
  1354                 Type s = asSuper(t, sym);
  1355                 if (s != null) return s;
  1356                 t = t.getEnclosingType();
  1357             } while (t.tag == CLASS);
  1358             return null;
  1359         case ARRAY:
  1360             return isSubtype(t, sym.type) ? sym.type : null;
  1361         case TYPEVAR:
  1362             return asSuper(t, sym);
  1363         case ERROR:
  1364             return t;
  1365         default:
  1366             return null;
  1370     /**
  1371      * Return the base type of t or any of its enclosing types that
  1372      * starts with the given symbol.  If none exists, return null.
  1374      * @param t a type
  1375      * @param sym a symbol
  1376      */
  1377     public Type asEnclosingSuper(Type t, Symbol sym) {
  1378         switch (t.tag) {
  1379         case CLASS:
  1380             do {
  1381                 Type s = asSuper(t, sym);
  1382                 if (s != null) return s;
  1383                 Type outer = t.getEnclosingType();
  1384                 t = (outer.tag == CLASS) ? outer :
  1385                     (t.tsym.owner.enclClass() != null) ? t.tsym.owner.enclClass().type :
  1386                     Type.noType;
  1387             } while (t.tag == CLASS);
  1388             return null;
  1389         case ARRAY:
  1390             return isSubtype(t, sym.type) ? sym.type : null;
  1391         case TYPEVAR:
  1392             return asSuper(t, sym);
  1393         case ERROR:
  1394             return t;
  1395         default:
  1396             return null;
  1399     // </editor-fold>
  1401     // <editor-fold defaultstate="collapsed" desc="memberType">
  1402     /**
  1403      * The type of given symbol, seen as a member of t.
  1405      * @param t a type
  1406      * @param sym a symbol
  1407      */
  1408     public Type memberType(Type t, Symbol sym) {
  1409         return (sym.flags() & STATIC) != 0
  1410             ? sym.type
  1411             : memberType.visit(t, sym);
  1413     // where
  1414         private SimpleVisitor<Type,Symbol> memberType = new SimpleVisitor<Type,Symbol>() {
  1416             public Type visitType(Type t, Symbol sym) {
  1417                 return sym.type;
  1420             @Override
  1421             public Type visitWildcardType(WildcardType t, Symbol sym) {
  1422                 return memberType(upperBound(t), sym);
  1425             @Override
  1426             public Type visitClassType(ClassType t, Symbol sym) {
  1427                 Symbol owner = sym.owner;
  1428                 long flags = sym.flags();
  1429                 if (((flags & STATIC) == 0) && owner.type.isParameterized()) {
  1430                     Type base = asOuterSuper(t, owner);
  1431                     //if t is an intersection type T = CT & I1 & I2 ... & In
  1432                     //its supertypes CT, I1, ... In might contain wildcards
  1433                     //so we need to go through capture conversion
  1434                     base = t.isCompound() ? capture(base) : base;
  1435                     if (base != null) {
  1436                         List<Type> ownerParams = owner.type.allparams();
  1437                         List<Type> baseParams = base.allparams();
  1438                         if (ownerParams.nonEmpty()) {
  1439                             if (baseParams.isEmpty()) {
  1440                                 // then base is a raw type
  1441                                 return erasure(sym.type);
  1442                             } else {
  1443                                 return subst(sym.type, ownerParams, baseParams);
  1448                 return sym.type;
  1451             @Override
  1452             public Type visitTypeVar(TypeVar t, Symbol sym) {
  1453                 return memberType(t.bound, sym);
  1456             @Override
  1457             public Type visitErrorType(ErrorType t, Symbol sym) {
  1458                 return t;
  1460         };
  1461     // </editor-fold>
  1463     // <editor-fold defaultstate="collapsed" desc="isAssignable">
  1464     public boolean isAssignable(Type t, Type s) {
  1465         return isAssignable(t, s, Warner.noWarnings);
  1468     /**
  1469      * Is t assignable to s?<br>
  1470      * Equivalent to subtype except for constant values and raw
  1471      * types.<br>
  1472      * (not defined for Method and ForAll types)
  1473      */
  1474     public boolean isAssignable(Type t, Type s, Warner warn) {
  1475         if (t.tag == ERROR)
  1476             return true;
  1477         if (t.tag <= INT && t.constValue() != null) {
  1478             int value = ((Number)t.constValue()).intValue();
  1479             switch (s.tag) {
  1480             case BYTE:
  1481                 if (Byte.MIN_VALUE <= value && value <= Byte.MAX_VALUE)
  1482                     return true;
  1483                 break;
  1484             case CHAR:
  1485                 if (Character.MIN_VALUE <= value && value <= Character.MAX_VALUE)
  1486                     return true;
  1487                 break;
  1488             case SHORT:
  1489                 if (Short.MIN_VALUE <= value && value <= Short.MAX_VALUE)
  1490                     return true;
  1491                 break;
  1492             case INT:
  1493                 return true;
  1494             case CLASS:
  1495                 switch (unboxedType(s).tag) {
  1496                 case BYTE:
  1497                 case CHAR:
  1498                 case SHORT:
  1499                     return isAssignable(t, unboxedType(s), warn);
  1501                 break;
  1504         return isConvertible(t, s, warn);
  1506     // </editor-fold>
  1508     // <editor-fold defaultstate="collapsed" desc="erasure">
  1509     /**
  1510      * The erasure of t {@code |t|} -- the type that results when all
  1511      * type parameters in t are deleted.
  1512      */
  1513     public Type erasure(Type t) {
  1514         return erasure(t, false);
  1516     //where
  1517     private Type erasure(Type t, boolean recurse) {
  1518         if (t.tag <= lastBaseTag)
  1519             return t; /* fast special case */
  1520         else
  1521             return erasure.visit(t, recurse);
  1523     // where
  1524         private SimpleVisitor<Type, Boolean> erasure = new SimpleVisitor<Type, Boolean>() {
  1525             public Type visitType(Type t, Boolean recurse) {
  1526                 if (t.tag <= lastBaseTag)
  1527                     return t; /*fast special case*/
  1528                 else
  1529                     return t.map(recurse ? erasureRecFun : erasureFun);
  1532             @Override
  1533             public Type visitWildcardType(WildcardType t, Boolean recurse) {
  1534                 return erasure(upperBound(t), recurse);
  1537             @Override
  1538             public Type visitClassType(ClassType t, Boolean recurse) {
  1539                 Type erased = t.tsym.erasure(Types.this);
  1540                 if (recurse) {
  1541                     erased = new ErasedClassType(erased.getEnclosingType(),erased.tsym);
  1543                 return erased;
  1546             @Override
  1547             public Type visitTypeVar(TypeVar t, Boolean recurse) {
  1548                 return erasure(t.bound, recurse);
  1551             @Override
  1552             public Type visitErrorType(ErrorType t, Boolean recurse) {
  1553                 return t;
  1555         };
  1557     private Mapping erasureFun = new Mapping ("erasure") {
  1558             public Type apply(Type t) { return erasure(t); }
  1559         };
  1561     private Mapping erasureRecFun = new Mapping ("erasureRecursive") {
  1562         public Type apply(Type t) { return erasureRecursive(t); }
  1563     };
  1565     public List<Type> erasure(List<Type> ts) {
  1566         return Type.map(ts, erasureFun);
  1569     public Type erasureRecursive(Type t) {
  1570         return erasure(t, true);
  1573     public List<Type> erasureRecursive(List<Type> ts) {
  1574         return Type.map(ts, erasureRecFun);
  1576     // </editor-fold>
  1578     // <editor-fold defaultstate="collapsed" desc="makeCompoundType">
  1579     /**
  1580      * Make a compound type from non-empty list of types
  1582      * @param bounds            the types from which the compound type is formed
  1583      * @param supertype         is objectType if all bounds are interfaces,
  1584      *                          null otherwise.
  1585      */
  1586     public Type makeCompoundType(List<Type> bounds,
  1587                                  Type supertype) {
  1588         ClassSymbol bc =
  1589             new ClassSymbol(ABSTRACT|PUBLIC|SYNTHETIC|COMPOUND|ACYCLIC,
  1590                             Type.moreInfo
  1591                                 ? names.fromString(bounds.toString())
  1592                                 : names.empty,
  1593                             syms.noSymbol);
  1594         if (bounds.head.tag == TYPEVAR)
  1595             // error condition, recover
  1596                 bc.erasure_field = syms.objectType;
  1597             else
  1598                 bc.erasure_field = erasure(bounds.head);
  1599             bc.members_field = new Scope(bc);
  1600         ClassType bt = (ClassType)bc.type;
  1601         bt.allparams_field = List.nil();
  1602         if (supertype != null) {
  1603             bt.supertype_field = supertype;
  1604             bt.interfaces_field = bounds;
  1605         } else {
  1606             bt.supertype_field = bounds.head;
  1607             bt.interfaces_field = bounds.tail;
  1609         assert bt.supertype_field.tsym.completer != null
  1610             || !bt.supertype_field.isInterface()
  1611             : bt.supertype_field;
  1612         return bt;
  1615     /**
  1616      * Same as {@link #makeCompoundType(List,Type)}, except that the
  1617      * second parameter is computed directly. Note that this might
  1618      * cause a symbol completion.  Hence, this version of
  1619      * makeCompoundType may not be called during a classfile read.
  1620      */
  1621     public Type makeCompoundType(List<Type> bounds) {
  1622         Type supertype = (bounds.head.tsym.flags() & INTERFACE) != 0 ?
  1623             supertype(bounds.head) : null;
  1624         return makeCompoundType(bounds, supertype);
  1627     /**
  1628      * A convenience wrapper for {@link #makeCompoundType(List)}; the
  1629      * arguments are converted to a list and passed to the other
  1630      * method.  Note that this might cause a symbol completion.
  1631      * Hence, this version of makeCompoundType may not be called
  1632      * during a classfile read.
  1633      */
  1634     public Type makeCompoundType(Type bound1, Type bound2) {
  1635         return makeCompoundType(List.of(bound1, bound2));
  1637     // </editor-fold>
  1639     // <editor-fold defaultstate="collapsed" desc="supertype">
  1640     public Type supertype(Type t) {
  1641         return supertype.visit(t);
  1643     // where
  1644         private UnaryVisitor<Type> supertype = new UnaryVisitor<Type>() {
  1646             public Type visitType(Type t, Void ignored) {
  1647                 // A note on wildcards: there is no good way to
  1648                 // determine a supertype for a super bounded wildcard.
  1649                 return null;
  1652             @Override
  1653             public Type visitClassType(ClassType t, Void ignored) {
  1654                 if (t.supertype_field == null) {
  1655                     Type supertype = ((ClassSymbol)t.tsym).getSuperclass();
  1656                     // An interface has no superclass; its supertype is Object.
  1657                     if (t.isInterface())
  1658                         supertype = ((ClassType)t.tsym.type).supertype_field;
  1659                     if (t.supertype_field == null) {
  1660                         List<Type> actuals = classBound(t).allparams();
  1661                         List<Type> formals = t.tsym.type.allparams();
  1662                         if (t.hasErasedSupertypes()) {
  1663                             t.supertype_field = erasureRecursive(supertype);
  1664                         } else if (formals.nonEmpty()) {
  1665                             t.supertype_field = subst(supertype, formals, actuals);
  1667                         else {
  1668                             t.supertype_field = supertype;
  1672                 return t.supertype_field;
  1675             /**
  1676              * The supertype is always a class type. If the type
  1677              * variable's bounds start with a class type, this is also
  1678              * the supertype.  Otherwise, the supertype is
  1679              * java.lang.Object.
  1680              */
  1681             @Override
  1682             public Type visitTypeVar(TypeVar t, Void ignored) {
  1683                 if (t.bound.tag == TYPEVAR ||
  1684                     (!t.bound.isCompound() && !t.bound.isInterface())) {
  1685                     return t.bound;
  1686                 } else {
  1687                     return supertype(t.bound);
  1691             @Override
  1692             public Type visitArrayType(ArrayType t, Void ignored) {
  1693                 if (t.elemtype.isPrimitive() || isSameType(t.elemtype, syms.objectType))
  1694                     return arraySuperType();
  1695                 else
  1696                     return new ArrayType(supertype(t.elemtype), t.tsym);
  1699             @Override
  1700             public Type visitErrorType(ErrorType t, Void ignored) {
  1701                 return t;
  1703         };
  1704     // </editor-fold>
  1706     // <editor-fold defaultstate="collapsed" desc="interfaces">
  1707     /**
  1708      * Return the interfaces implemented by this class.
  1709      */
  1710     public List<Type> interfaces(Type t) {
  1711         return interfaces.visit(t);
  1713     // where
  1714         private UnaryVisitor<List<Type>> interfaces = new UnaryVisitor<List<Type>>() {
  1716             public List<Type> visitType(Type t, Void ignored) {
  1717                 return List.nil();
  1720             @Override
  1721             public List<Type> visitClassType(ClassType t, Void ignored) {
  1722                 if (t.interfaces_field == null) {
  1723                     List<Type> interfaces = ((ClassSymbol)t.tsym).getInterfaces();
  1724                     if (t.interfaces_field == null) {
  1725                         // If t.interfaces_field is null, then t must
  1726                         // be a parameterized type (not to be confused
  1727                         // with a generic type declaration).
  1728                         // Terminology:
  1729                         //    Parameterized type: List<String>
  1730                         //    Generic type declaration: class List<E> { ... }
  1731                         // So t corresponds to List<String> and
  1732                         // t.tsym.type corresponds to List<E>.
  1733                         // The reason t must be parameterized type is
  1734                         // that completion will happen as a side
  1735                         // effect of calling
  1736                         // ClassSymbol.getInterfaces.  Since
  1737                         // t.interfaces_field is null after
  1738                         // completion, we can assume that t is not the
  1739                         // type of a class/interface declaration.
  1740                         assert t != t.tsym.type : t.toString();
  1741                         List<Type> actuals = t.allparams();
  1742                         List<Type> formals = t.tsym.type.allparams();
  1743                         if (t.hasErasedSupertypes()) {
  1744                             t.interfaces_field = erasureRecursive(interfaces);
  1745                         } else if (formals.nonEmpty()) {
  1746                             t.interfaces_field =
  1747                                 upperBounds(subst(interfaces, formals, actuals));
  1749                         else {
  1750                             t.interfaces_field = interfaces;
  1754                 return t.interfaces_field;
  1757             @Override
  1758             public List<Type> visitTypeVar(TypeVar t, Void ignored) {
  1759                 if (t.bound.isCompound())
  1760                     return interfaces(t.bound);
  1762                 if (t.bound.isInterface())
  1763                     return List.of(t.bound);
  1765                 return List.nil();
  1767         };
  1768     // </editor-fold>
  1770     // <editor-fold defaultstate="collapsed" desc="isDerivedRaw">
  1771     Map<Type,Boolean> isDerivedRawCache = new HashMap<Type,Boolean>();
  1773     public boolean isDerivedRaw(Type t) {
  1774         Boolean result = isDerivedRawCache.get(t);
  1775         if (result == null) {
  1776             result = isDerivedRawInternal(t);
  1777             isDerivedRawCache.put(t, result);
  1779         return result;
  1782     public boolean isDerivedRawInternal(Type t) {
  1783         if (t.isErroneous())
  1784             return false;
  1785         return
  1786             t.isRaw() ||
  1787             supertype(t) != null && isDerivedRaw(supertype(t)) ||
  1788             isDerivedRaw(interfaces(t));
  1791     public boolean isDerivedRaw(List<Type> ts) {
  1792         List<Type> l = ts;
  1793         while (l.nonEmpty() && !isDerivedRaw(l.head)) l = l.tail;
  1794         return l.nonEmpty();
  1796     // </editor-fold>
  1798     // <editor-fold defaultstate="collapsed" desc="setBounds">
  1799     /**
  1800      * Set the bounds field of the given type variable to reflect a
  1801      * (possibly multiple) list of bounds.
  1802      * @param t                 a type variable
  1803      * @param bounds            the bounds, must be nonempty
  1804      * @param supertype         is objectType if all bounds are interfaces,
  1805      *                          null otherwise.
  1806      */
  1807     public void setBounds(TypeVar t, List<Type> bounds, Type supertype) {
  1808         if (bounds.tail.isEmpty())
  1809             t.bound = bounds.head;
  1810         else
  1811             t.bound = makeCompoundType(bounds, supertype);
  1812         t.rank_field = -1;
  1815     /**
  1816      * Same as {@link #setBounds(Type.TypeVar,List,Type)}, except that
  1817      * third parameter is computed directly.  Note that this test
  1818      * might cause a symbol completion.  Hence, this version of
  1819      * setBounds may not be called during a classfile read.
  1820      */
  1821     public void setBounds(TypeVar t, List<Type> bounds) {
  1822         Type supertype = (bounds.head.tsym.flags() & INTERFACE) != 0 ?
  1823             supertype(bounds.head) : null;
  1824         setBounds(t, bounds, supertype);
  1825         t.rank_field = -1;
  1827     // </editor-fold>
  1829     // <editor-fold defaultstate="collapsed" desc="getBounds">
  1830     /**
  1831      * Return list of bounds of the given type variable.
  1832      */
  1833     public List<Type> getBounds(TypeVar t) {
  1834         if (t.bound.isErroneous() || !t.bound.isCompound())
  1835             return List.of(t.bound);
  1836         else if ((erasure(t).tsym.flags() & INTERFACE) == 0)
  1837             return interfaces(t).prepend(supertype(t));
  1838         else
  1839             // No superclass was given in bounds.
  1840             // In this case, supertype is Object, erasure is first interface.
  1841             return interfaces(t);
  1843     // </editor-fold>
  1845     // <editor-fold defaultstate="collapsed" desc="classBound">
  1846     /**
  1847      * If the given type is a (possibly selected) type variable,
  1848      * return the bounding class of this type, otherwise return the
  1849      * type itself.
  1850      */
  1851     public Type classBound(Type t) {
  1852         return classBound.visit(t);
  1854     // where
  1855         private UnaryVisitor<Type> classBound = new UnaryVisitor<Type>() {
  1857             public Type visitType(Type t, Void ignored) {
  1858                 return t;
  1861             @Override
  1862             public Type visitClassType(ClassType t, Void ignored) {
  1863                 Type outer1 = classBound(t.getEnclosingType());
  1864                 if (outer1 != t.getEnclosingType())
  1865                     return new ClassType(outer1, t.getTypeArguments(), t.tsym);
  1866                 else
  1867                     return t;
  1870             @Override
  1871             public Type visitTypeVar(TypeVar t, Void ignored) {
  1872                 return classBound(supertype(t));
  1875             @Override
  1876             public Type visitErrorType(ErrorType t, Void ignored) {
  1877                 return t;
  1879         };
  1880     // </editor-fold>
  1882     // <editor-fold defaultstate="collapsed" desc="sub signature / override equivalence">
  1883     /**
  1884      * Returns true iff the first signature is a <em>sub
  1885      * signature</em> of the other.  This is <b>not</b> an equivalence
  1886      * relation.
  1888      * @see "The Java Language Specification, Third Ed. (8.4.2)."
  1889      * @see #overrideEquivalent(Type t, Type s)
  1890      * @param t first signature (possibly raw).
  1891      * @param s second signature (could be subjected to erasure).
  1892      * @return true if t is a sub signature of s.
  1893      */
  1894     public boolean isSubSignature(Type t, Type s) {
  1895         return hasSameArgs(t, s) || hasSameArgs(t, erasure(s));
  1898     /**
  1899      * Returns true iff these signatures are related by <em>override
  1900      * equivalence</em>.  This is the natural extension of
  1901      * isSubSignature to an equivalence relation.
  1903      * @see "The Java Language Specification, Third Ed. (8.4.2)."
  1904      * @see #isSubSignature(Type t, Type s)
  1905      * @param t a signature (possible raw, could be subjected to
  1906      * erasure).
  1907      * @param s a signature (possible raw, could be subjected to
  1908      * erasure).
  1909      * @return true if either argument is a sub signature of the other.
  1910      */
  1911     public boolean overrideEquivalent(Type t, Type s) {
  1912         return hasSameArgs(t, s) ||
  1913             hasSameArgs(t, erasure(s)) || hasSameArgs(erasure(t), s);
  1916     /**
  1917      * Does t have the same arguments as s?  It is assumed that both
  1918      * types are (possibly polymorphic) method types.  Monomorphic
  1919      * method types "have the same arguments", if their argument lists
  1920      * are equal.  Polymorphic method types "have the same arguments",
  1921      * if they have the same arguments after renaming all type
  1922      * variables of one to corresponding type variables in the other,
  1923      * where correspondence is by position in the type parameter list.
  1924      */
  1925     public boolean hasSameArgs(Type t, Type s) {
  1926         return hasSameArgs.visit(t, s);
  1928     // where
  1929         private TypeRelation hasSameArgs = new TypeRelation() {
  1931             public Boolean visitType(Type t, Type s) {
  1932                 throw new AssertionError();
  1935             @Override
  1936             public Boolean visitMethodType(MethodType t, Type s) {
  1937                 return s.tag == METHOD
  1938                     && containsTypeEquivalent(t.argtypes, s.getParameterTypes());
  1941             @Override
  1942             public Boolean visitForAll(ForAll t, Type s) {
  1943                 if (s.tag != FORALL)
  1944                     return false;
  1946                 ForAll forAll = (ForAll)s;
  1947                 return hasSameBounds(t, forAll)
  1948                     && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
  1951             @Override
  1952             public Boolean visitErrorType(ErrorType t, Type s) {
  1953                 return false;
  1955         };
  1956     // </editor-fold>
  1958     // <editor-fold defaultstate="collapsed" desc="subst">
  1959     public List<Type> subst(List<Type> ts,
  1960                             List<Type> from,
  1961                             List<Type> to) {
  1962         return new Subst(from, to).subst(ts);
  1965     /**
  1966      * Substitute all occurrences of a type in `from' with the
  1967      * corresponding type in `to' in 't'. Match lists `from' and `to'
  1968      * from the right: If lists have different length, discard leading
  1969      * elements of the longer list.
  1970      */
  1971     public Type subst(Type t, List<Type> from, List<Type> to) {
  1972         return new Subst(from, to).subst(t);
  1975     private class Subst extends UnaryVisitor<Type> {
  1976         List<Type> from;
  1977         List<Type> to;
  1979         public Subst(List<Type> from, List<Type> to) {
  1980             int fromLength = from.length();
  1981             int toLength = to.length();
  1982             while (fromLength > toLength) {
  1983                 fromLength--;
  1984                 from = from.tail;
  1986             while (fromLength < toLength) {
  1987                 toLength--;
  1988                 to = to.tail;
  1990             this.from = from;
  1991             this.to = to;
  1994         Type subst(Type t) {
  1995             if (from.tail == null)
  1996                 return t;
  1997             else
  1998                 return visit(t);
  2001         List<Type> subst(List<Type> ts) {
  2002             if (from.tail == null)
  2003                 return ts;
  2004             boolean wild = false;
  2005             if (ts.nonEmpty() && from.nonEmpty()) {
  2006                 Type head1 = subst(ts.head);
  2007                 List<Type> tail1 = subst(ts.tail);
  2008                 if (head1 != ts.head || tail1 != ts.tail)
  2009                     return tail1.prepend(head1);
  2011             return ts;
  2014         public Type visitType(Type t, Void ignored) {
  2015             return t;
  2018         @Override
  2019         public Type visitMethodType(MethodType t, Void ignored) {
  2020             List<Type> argtypes = subst(t.argtypes);
  2021             Type restype = subst(t.restype);
  2022             List<Type> thrown = subst(t.thrown);
  2023             if (argtypes == t.argtypes &&
  2024                 restype == t.restype &&
  2025                 thrown == t.thrown)
  2026                 return t;
  2027             else
  2028                 return new MethodType(argtypes, restype, thrown, t.tsym);
  2031         @Override
  2032         public Type visitTypeVar(TypeVar t, Void ignored) {
  2033             for (List<Type> from = this.from, to = this.to;
  2034                  from.nonEmpty();
  2035                  from = from.tail, to = to.tail) {
  2036                 if (t == from.head) {
  2037                     return to.head.withTypeVar(t);
  2040             return t;
  2043         @Override
  2044         public Type visitClassType(ClassType t, Void ignored) {
  2045             if (!t.isCompound()) {
  2046                 List<Type> typarams = t.getTypeArguments();
  2047                 List<Type> typarams1 = subst(typarams);
  2048                 Type outer = t.getEnclosingType();
  2049                 Type outer1 = subst(outer);
  2050                 if (typarams1 == typarams && outer1 == outer)
  2051                     return t;
  2052                 else
  2053                     return new ClassType(outer1, typarams1, t.tsym);
  2054             } else {
  2055                 Type st = subst(supertype(t));
  2056                 List<Type> is = upperBounds(subst(interfaces(t)));
  2057                 if (st == supertype(t) && is == interfaces(t))
  2058                     return t;
  2059                 else
  2060                     return makeCompoundType(is.prepend(st));
  2064         @Override
  2065         public Type visitWildcardType(WildcardType t, Void ignored) {
  2066             Type bound = t.type;
  2067             if (t.kind != BoundKind.UNBOUND)
  2068                 bound = subst(bound);
  2069             if (bound == t.type) {
  2070                 return t;
  2071             } else {
  2072                 if (t.isExtendsBound() && bound.isExtendsBound())
  2073                     bound = upperBound(bound);
  2074                 return new WildcardType(bound, t.kind, syms.boundClass, t.bound);
  2078         @Override
  2079         public Type visitArrayType(ArrayType t, Void ignored) {
  2080             Type elemtype = subst(t.elemtype);
  2081             if (elemtype == t.elemtype)
  2082                 return t;
  2083             else
  2084                 return new ArrayType(upperBound(elemtype), t.tsym);
  2087         @Override
  2088         public Type visitForAll(ForAll t, Void ignored) {
  2089             List<Type> tvars1 = substBounds(t.tvars, from, to);
  2090             Type qtype1 = subst(t.qtype);
  2091             if (tvars1 == t.tvars && qtype1 == t.qtype) {
  2092                 return t;
  2093             } else if (tvars1 == t.tvars) {
  2094                 return new ForAll(tvars1, qtype1);
  2095             } else {
  2096                 return new ForAll(tvars1, Types.this.subst(qtype1, t.tvars, tvars1));
  2100         @Override
  2101         public Type visitErrorType(ErrorType t, Void ignored) {
  2102             return t;
  2106     public List<Type> substBounds(List<Type> tvars,
  2107                                   List<Type> from,
  2108                                   List<Type> to) {
  2109         if (tvars.isEmpty())
  2110             return tvars;
  2111         if (tvars.tail.isEmpty())
  2112             // fast common case
  2113             return List.<Type>of(substBound((TypeVar)tvars.head, from, to));
  2114         ListBuffer<Type> newBoundsBuf = lb();
  2115         boolean changed = false;
  2116         // calculate new bounds
  2117         for (Type t : tvars) {
  2118             TypeVar tv = (TypeVar) t;
  2119             Type bound = subst(tv.bound, from, to);
  2120             if (bound != tv.bound)
  2121                 changed = true;
  2122             newBoundsBuf.append(bound);
  2124         if (!changed)
  2125             return tvars;
  2126         ListBuffer<Type> newTvars = lb();
  2127         // create new type variables without bounds
  2128         for (Type t : tvars) {
  2129             newTvars.append(new TypeVar(t.tsym, null, syms.botType));
  2131         // the new bounds should use the new type variables in place
  2132         // of the old
  2133         List<Type> newBounds = newBoundsBuf.toList();
  2134         from = tvars;
  2135         to = newTvars.toList();
  2136         for (; !newBounds.isEmpty(); newBounds = newBounds.tail) {
  2137             newBounds.head = subst(newBounds.head, from, to);
  2139         newBounds = newBoundsBuf.toList();
  2140         // set the bounds of new type variables to the new bounds
  2141         for (Type t : newTvars.toList()) {
  2142             TypeVar tv = (TypeVar) t;
  2143             tv.bound = newBounds.head;
  2144             newBounds = newBounds.tail;
  2146         return newTvars.toList();
  2149     public TypeVar substBound(TypeVar t, List<Type> from, List<Type> to) {
  2150         Type bound1 = subst(t.bound, from, to);
  2151         if (bound1 == t.bound)
  2152             return t;
  2153         else
  2154             return new TypeVar(t.tsym, bound1, syms.botType);
  2156     // </editor-fold>
  2158     // <editor-fold defaultstate="collapsed" desc="hasSameBounds">
  2159     /**
  2160      * Does t have the same bounds for quantified variables as s?
  2161      */
  2162     boolean hasSameBounds(ForAll t, ForAll s) {
  2163         List<Type> l1 = t.tvars;
  2164         List<Type> l2 = s.tvars;
  2165         while (l1.nonEmpty() && l2.nonEmpty() &&
  2166                isSameType(l1.head.getUpperBound(),
  2167                           subst(l2.head.getUpperBound(),
  2168                                 s.tvars,
  2169                                 t.tvars))) {
  2170             l1 = l1.tail;
  2171             l2 = l2.tail;
  2173         return l1.isEmpty() && l2.isEmpty();
  2175     // </editor-fold>
  2177     // <editor-fold defaultstate="collapsed" desc="newInstances">
  2178     /** Create new vector of type variables from list of variables
  2179      *  changing all recursive bounds from old to new list.
  2180      */
  2181     public List<Type> newInstances(List<Type> tvars) {
  2182         List<Type> tvars1 = Type.map(tvars, newInstanceFun);
  2183         for (List<Type> l = tvars1; l.nonEmpty(); l = l.tail) {
  2184             TypeVar tv = (TypeVar) l.head;
  2185             tv.bound = subst(tv.bound, tvars, tvars1);
  2187         return tvars1;
  2189     static private Mapping newInstanceFun = new Mapping("newInstanceFun") {
  2190             public Type apply(Type t) { return new TypeVar(t.tsym, t.getUpperBound(), t.getLowerBound()); }
  2191         };
  2192     // </editor-fold>
  2194     // <editor-fold defaultstate="collapsed" desc="createErrorType">
  2195     public Type createErrorType(Type originalType) {
  2196         return new ErrorType(originalType, syms.errSymbol);
  2199     public Type createErrorType(ClassSymbol c, Type originalType) {
  2200         return new ErrorType(c, originalType);
  2203     public Type createErrorType(Name name, TypeSymbol container, Type originalType) {
  2204         return new ErrorType(name, container, originalType);
  2206     // </editor-fold>
  2208     // <editor-fold defaultstate="collapsed" desc="rank">
  2209     /**
  2210      * The rank of a class is the length of the longest path between
  2211      * the class and java.lang.Object in the class inheritance
  2212      * graph. Undefined for all but reference types.
  2213      */
  2214     public int rank(Type t) {
  2215         switch(t.tag) {
  2216         case CLASS: {
  2217             ClassType cls = (ClassType)t;
  2218             if (cls.rank_field < 0) {
  2219                 Name fullname = cls.tsym.getQualifiedName();
  2220                 if (fullname == names.java_lang_Object)
  2221                     cls.rank_field = 0;
  2222                 else {
  2223                     int r = rank(supertype(cls));
  2224                     for (List<Type> l = interfaces(cls);
  2225                          l.nonEmpty();
  2226                          l = l.tail) {
  2227                         if (rank(l.head) > r)
  2228                             r = rank(l.head);
  2230                     cls.rank_field = r + 1;
  2233             return cls.rank_field;
  2235         case TYPEVAR: {
  2236             TypeVar tvar = (TypeVar)t;
  2237             if (tvar.rank_field < 0) {
  2238                 int r = rank(supertype(tvar));
  2239                 for (List<Type> l = interfaces(tvar);
  2240                      l.nonEmpty();
  2241                      l = l.tail) {
  2242                     if (rank(l.head) > r) r = rank(l.head);
  2244                 tvar.rank_field = r + 1;
  2246             return tvar.rank_field;
  2248         case ERROR:
  2249             return 0;
  2250         default:
  2251             throw new AssertionError();
  2254     // </editor-fold>
  2256     // <editor-fold defaultstate="collapsed" desc="printType">
  2257     /**
  2258      * Visitor for generating a string representation of a given type
  2259      * accordingly to a given locale
  2260      */
  2261     public String toString(Type t, Locale locale) {
  2262         return typePrinter.visit(t, locale);
  2264     // where
  2265     private TypePrinter typePrinter = new TypePrinter();
  2267     public class TypePrinter extends DefaultTypeVisitor<String, Locale> {
  2269         public String visit(List<Type> ts, Locale locale) {
  2270             ListBuffer<String> sbuf = lb();
  2271             for (Type t : ts) {
  2272                 sbuf.append(visit(t, locale));
  2274             return sbuf.toList().toString();
  2277         @Override
  2278         public String visitCapturedType(CapturedType t, Locale locale) {
  2279             return messages.getLocalizedString("compiler.misc.type.captureof",
  2280                         (t.hashCode() & 0xFFFFFFFFL) % Type.CapturedType.PRIME,
  2281                         visit(t.wildcard, locale));
  2284         @Override
  2285         public String visitForAll(ForAll t, Locale locale) {
  2286             return "<" + visit(t.tvars, locale) + ">" + visit(t.qtype, locale);
  2289         @Override
  2290         public String visitUndetVar(UndetVar t, Locale locale) {
  2291             if (t.inst != null) {
  2292                 return visit(t.inst, locale);
  2293             } else {
  2294                 return visit(t.qtype, locale) + "?";
  2298         @Override
  2299         public String visitArrayType(ArrayType t, Locale locale) {
  2300             return visit(t.elemtype, locale) + "[]";
  2303         @Override
  2304         public String visitClassType(ClassType t, Locale locale) {
  2305             StringBuffer buf = new StringBuffer();
  2306             if (t.getEnclosingType().tag == CLASS && t.tsym.owner.kind == Kinds.TYP) {
  2307                 buf.append(visit(t.getEnclosingType(), locale));
  2308                 buf.append(".");
  2309                 buf.append(className(t, false, locale));
  2310             } else {
  2311                 buf.append(className(t, true, locale));
  2313             if (t.getTypeArguments().nonEmpty()) {
  2314                 buf.append('<');
  2315                 buf.append(visit(t.getTypeArguments(), locale));
  2316                 buf.append(">");
  2318             return buf.toString();
  2321         @Override
  2322         public String visitMethodType(MethodType t, Locale locale) {
  2323             return "(" + printMethodArgs(t.argtypes, false, locale) + ")" + visit(t.restype, locale);
  2326         @Override
  2327         public String visitPackageType(PackageType t, Locale locale) {
  2328             return t.tsym.getQualifiedName().toString();
  2331         @Override
  2332         public String visitWildcardType(WildcardType t, Locale locale) {
  2333             StringBuffer s = new StringBuffer();
  2334             s.append(t.kind);
  2335             if (t.kind != UNBOUND) {
  2336                 s.append(visit(t.type, locale));
  2338             return s.toString();
  2342         public String visitType(Type t, Locale locale) {
  2343             String s = (t.tsym == null || t.tsym.name == null)
  2344                     ? messages.getLocalizedString("compiler.misc.type.none")
  2345                     : t.tsym.name.toString();
  2346             return s;
  2349         protected String className(ClassType t, boolean longform, Locale locale) {
  2350             Symbol sym = t.tsym;
  2351             if (sym.name.length() == 0 && (sym.flags() & COMPOUND) != 0) {
  2352                 StringBuffer s = new StringBuffer(visit(supertype(t), locale));
  2353                 for (List<Type> is = interfaces(t); is.nonEmpty(); is = is.tail) {
  2354                     s.append("&");
  2355                     s.append(visit(is.head, locale));
  2357                 return s.toString();
  2358             } else if (sym.name.length() == 0) {
  2359                 String s;
  2360                 ClassType norm = (ClassType) t.tsym.type;
  2361                 if (norm == null) {
  2362                     s = getLocalizedString(locale, "compiler.misc.anonymous.class", (Object) null);
  2363                 } else if (interfaces(norm).nonEmpty()) {
  2364                     s = getLocalizedString(locale, "compiler.misc.anonymous.class",
  2365                             visit(interfaces(norm).head, locale));
  2366                 } else {
  2367                     s = getLocalizedString(locale, "compiler.misc.anonymous.class",
  2368                             visit(supertype(norm), locale));
  2370                 return s;
  2371             } else if (longform) {
  2372                 return sym.getQualifiedName().toString();
  2373             } else {
  2374                 return sym.name.toString();
  2378         protected String printMethodArgs(List<Type> args, boolean varArgs, Locale locale) {
  2379             if (!varArgs) {
  2380                 return visit(args, locale);
  2381             } else {
  2382                 StringBuffer buf = new StringBuffer();
  2383                 while (args.tail.nonEmpty()) {
  2384                     buf.append(visit(args.head, locale));
  2385                     args = args.tail;
  2386                     buf.append(',');
  2388                 if (args.head.tag == ARRAY) {
  2389                     buf.append(visit(((ArrayType) args.head).elemtype, locale));
  2390                     buf.append("...");
  2391                 } else {
  2392                     buf.append(visit(args.head, locale));
  2394                 return buf.toString();
  2398         protected String getLocalizedString(Locale locale, String key, Object... args) {
  2399             return messages.getLocalizedString(key, args);
  2401     };
  2402     // </editor-fold>
  2404     // <editor-fold defaultstate="collapsed" desc="printSymbol">
  2405     /**
  2406      * Visitor for generating a string representation of a given symbol
  2407      * accordingly to a given locale
  2408      */
  2409     public String toString(Symbol t, Locale locale) {
  2410         return symbolPrinter.visit(t, locale);
  2412     // where
  2413     private SymbolPrinter symbolPrinter = new SymbolPrinter();
  2415     public class SymbolPrinter extends DefaultSymbolVisitor<String, Locale> {
  2417         @Override
  2418         public String visitClassSymbol(ClassSymbol sym, Locale locale) {
  2419             return sym.name.isEmpty()
  2420                     ? getLocalizedString(locale, "compiler.misc.anonymous.class", sym.flatname)
  2421                     : sym.fullname.toString();
  2424         @Override
  2425         public String visitMethodSymbol(MethodSymbol s, Locale locale) {
  2426             if ((s.flags() & BLOCK) != 0) {
  2427                 return s.owner.name.toString();
  2428             } else {
  2429                 String ms = (s.name == names.init)
  2430                         ? s.owner.name.toString()
  2431                         : s.name.toString();
  2432                 if (s.type != null) {
  2433                     if (s.type.tag == FORALL) {
  2434                         ms = "<" + typePrinter.visit(s.type.getTypeArguments(), locale) + ">" + ms;
  2436                     ms += "(" + typePrinter.printMethodArgs(
  2437                             s.type.getParameterTypes(),
  2438                             (s.flags() & VARARGS) != 0,
  2439                             locale) + ")";
  2441                 return ms;
  2445         @Override
  2446         public String visitOperatorSymbol(OperatorSymbol s, Locale locale) {
  2447             return visitMethodSymbol(s, locale);
  2450         @Override
  2451         public String visitPackageSymbol(PackageSymbol s, Locale locale) {
  2452             return s.name.isEmpty()
  2453                     ? getLocalizedString(locale, "compiler.misc.unnamed.package")
  2454                     : s.fullname.toString();
  2457         @Override
  2458         public String visitSymbol(Symbol s, Locale locale) {
  2459             return s.name.toString();
  2462         public String visit(List<Symbol> ts, Locale locale) {
  2463             ListBuffer<String> sbuf = lb();
  2464             for (Symbol t : ts) {
  2465                 sbuf.append(visit(t, locale));
  2467             return sbuf.toList().toString();
  2470         protected String getLocalizedString(Locale locale, String key, Object... args) {
  2471             return messages.getLocalizedString(key, args);
  2473     };
  2474     // </editor-fold>
  2476     // <editor-fold defaultstate="collapsed" desc="toString">
  2477     /**
  2478      * This toString is slightly more descriptive than the one on Type.
  2480      * @deprecated Types.toString(Type t, Locale l) provides better support
  2481      * for localization
  2482      */
  2483     @Deprecated
  2484     public String toString(Type t) {
  2485         if (t.tag == FORALL) {
  2486             ForAll forAll = (ForAll)t;
  2487             return typaramsString(forAll.tvars) + forAll.qtype;
  2489         return "" + t;
  2491     // where
  2492         private String typaramsString(List<Type> tvars) {
  2493             StringBuffer s = new StringBuffer();
  2494             s.append('<');
  2495             boolean first = true;
  2496             for (Type t : tvars) {
  2497                 if (!first) s.append(", ");
  2498                 first = false;
  2499                 appendTyparamString(((TypeVar)t), s);
  2501             s.append('>');
  2502             return s.toString();
  2504         private void appendTyparamString(TypeVar t, StringBuffer buf) {
  2505             buf.append(t);
  2506             if (t.bound == null ||
  2507                 t.bound.tsym.getQualifiedName() == names.java_lang_Object)
  2508                 return;
  2509             buf.append(" extends "); // Java syntax; no need for i18n
  2510             Type bound = t.bound;
  2511             if (!bound.isCompound()) {
  2512                 buf.append(bound);
  2513             } else if ((erasure(t).tsym.flags() & INTERFACE) == 0) {
  2514                 buf.append(supertype(t));
  2515                 for (Type intf : interfaces(t)) {
  2516                     buf.append('&');
  2517                     buf.append(intf);
  2519             } else {
  2520                 // No superclass was given in bounds.
  2521                 // In this case, supertype is Object, erasure is first interface.
  2522                 boolean first = true;
  2523                 for (Type intf : interfaces(t)) {
  2524                     if (!first) buf.append('&');
  2525                     first = false;
  2526                     buf.append(intf);
  2530     // </editor-fold>
  2532     // <editor-fold defaultstate="collapsed" desc="Determining least upper bounds of types">
  2533     /**
  2534      * A cache for closures.
  2536      * <p>A closure is a list of all the supertypes and interfaces of
  2537      * a class or interface type, ordered by ClassSymbol.precedes
  2538      * (that is, subclasses come first, arbitrary but fixed
  2539      * otherwise).
  2540      */
  2541     private Map<Type,List<Type>> closureCache = new HashMap<Type,List<Type>>();
  2543     /**
  2544      * Returns the closure of a class or interface type.
  2545      */
  2546     public List<Type> closure(Type t) {
  2547         List<Type> cl = closureCache.get(t);
  2548         if (cl == null) {
  2549             Type st = supertype(t);
  2550             if (!t.isCompound()) {
  2551                 if (st.tag == CLASS) {
  2552                     cl = insert(closure(st), t);
  2553                 } else if (st.tag == TYPEVAR) {
  2554                     cl = closure(st).prepend(t);
  2555                 } else {
  2556                     cl = List.of(t);
  2558             } else {
  2559                 cl = closure(supertype(t));
  2561             for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail)
  2562                 cl = union(cl, closure(l.head));
  2563             closureCache.put(t, cl);
  2565         return cl;
  2568     /**
  2569      * Insert a type in a closure
  2570      */
  2571     public List<Type> insert(List<Type> cl, Type t) {
  2572         if (cl.isEmpty() || t.tsym.precedes(cl.head.tsym, this)) {
  2573             return cl.prepend(t);
  2574         } else if (cl.head.tsym.precedes(t.tsym, this)) {
  2575             return insert(cl.tail, t).prepend(cl.head);
  2576         } else {
  2577             return cl;
  2581     /**
  2582      * Form the union of two closures
  2583      */
  2584     public List<Type> union(List<Type> cl1, List<Type> cl2) {
  2585         if (cl1.isEmpty()) {
  2586             return cl2;
  2587         } else if (cl2.isEmpty()) {
  2588             return cl1;
  2589         } else if (cl1.head.tsym.precedes(cl2.head.tsym, this)) {
  2590             return union(cl1.tail, cl2).prepend(cl1.head);
  2591         } else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) {
  2592             return union(cl1, cl2.tail).prepend(cl2.head);
  2593         } else {
  2594             return union(cl1.tail, cl2.tail).prepend(cl1.head);
  2598     /**
  2599      * Intersect two closures
  2600      */
  2601     public List<Type> intersect(List<Type> cl1, List<Type> cl2) {
  2602         if (cl1 == cl2)
  2603             return cl1;
  2604         if (cl1.isEmpty() || cl2.isEmpty())
  2605             return List.nil();
  2606         if (cl1.head.tsym.precedes(cl2.head.tsym, this))
  2607             return intersect(cl1.tail, cl2);
  2608         if (cl2.head.tsym.precedes(cl1.head.tsym, this))
  2609             return intersect(cl1, cl2.tail);
  2610         if (isSameType(cl1.head, cl2.head))
  2611             return intersect(cl1.tail, cl2.tail).prepend(cl1.head);
  2612         if (cl1.head.tsym == cl2.head.tsym &&
  2613             cl1.head.tag == CLASS && cl2.head.tag == CLASS) {
  2614             if (cl1.head.isParameterized() && cl2.head.isParameterized()) {
  2615                 Type merge = merge(cl1.head,cl2.head);
  2616                 return intersect(cl1.tail, cl2.tail).prepend(merge);
  2618             if (cl1.head.isRaw() || cl2.head.isRaw())
  2619                 return intersect(cl1.tail, cl2.tail).prepend(erasure(cl1.head));
  2621         return intersect(cl1.tail, cl2.tail);
  2623     // where
  2624         class TypePair {
  2625             final Type t1;
  2626             final Type t2;
  2627             TypePair(Type t1, Type t2) {
  2628                 this.t1 = t1;
  2629                 this.t2 = t2;
  2631             @Override
  2632             public int hashCode() {
  2633                 return 127 * Types.this.hashCode(t1) + Types.this.hashCode(t2);
  2635             @Override
  2636             public boolean equals(Object obj) {
  2637                 if (!(obj instanceof TypePair))
  2638                     return false;
  2639                 TypePair typePair = (TypePair)obj;
  2640                 return isSameType(t1, typePair.t1)
  2641                     && isSameType(t2, typePair.t2);
  2644         Set<TypePair> mergeCache = new HashSet<TypePair>();
  2645         private Type merge(Type c1, Type c2) {
  2646             ClassType class1 = (ClassType) c1;
  2647             List<Type> act1 = class1.getTypeArguments();
  2648             ClassType class2 = (ClassType) c2;
  2649             List<Type> act2 = class2.getTypeArguments();
  2650             ListBuffer<Type> merged = new ListBuffer<Type>();
  2651             List<Type> typarams = class1.tsym.type.getTypeArguments();
  2653             while (act1.nonEmpty() && act2.nonEmpty() && typarams.nonEmpty()) {
  2654                 if (containsType(act1.head, act2.head)) {
  2655                     merged.append(act1.head);
  2656                 } else if (containsType(act2.head, act1.head)) {
  2657                     merged.append(act2.head);
  2658                 } else {
  2659                     TypePair pair = new TypePair(c1, c2);
  2660                     Type m;
  2661                     if (mergeCache.add(pair)) {
  2662                         m = new WildcardType(lub(upperBound(act1.head),
  2663                                                  upperBound(act2.head)),
  2664                                              BoundKind.EXTENDS,
  2665                                              syms.boundClass);
  2666                         mergeCache.remove(pair);
  2667                     } else {
  2668                         m = new WildcardType(syms.objectType,
  2669                                              BoundKind.UNBOUND,
  2670                                              syms.boundClass);
  2672                     merged.append(m.withTypeVar(typarams.head));
  2674                 act1 = act1.tail;
  2675                 act2 = act2.tail;
  2676                 typarams = typarams.tail;
  2678             assert(act1.isEmpty() && act2.isEmpty() && typarams.isEmpty());
  2679             return new ClassType(class1.getEnclosingType(), merged.toList(), class1.tsym);
  2682     /**
  2683      * Return the minimum type of a closure, a compound type if no
  2684      * unique minimum exists.
  2685      */
  2686     private Type compoundMin(List<Type> cl) {
  2687         if (cl.isEmpty()) return syms.objectType;
  2688         List<Type> compound = closureMin(cl);
  2689         if (compound.isEmpty())
  2690             return null;
  2691         else if (compound.tail.isEmpty())
  2692             return compound.head;
  2693         else
  2694             return makeCompoundType(compound);
  2697     /**
  2698      * Return the minimum types of a closure, suitable for computing
  2699      * compoundMin or glb.
  2700      */
  2701     private List<Type> closureMin(List<Type> cl) {
  2702         ListBuffer<Type> classes = lb();
  2703         ListBuffer<Type> interfaces = lb();
  2704         while (!cl.isEmpty()) {
  2705             Type current = cl.head;
  2706             if (current.isInterface())
  2707                 interfaces.append(current);
  2708             else
  2709                 classes.append(current);
  2710             ListBuffer<Type> candidates = lb();
  2711             for (Type t : cl.tail) {
  2712                 if (!isSubtypeNoCapture(current, t))
  2713                     candidates.append(t);
  2715             cl = candidates.toList();
  2717         return classes.appendList(interfaces).toList();
  2720     /**
  2721      * Return the least upper bound of pair of types.  if the lub does
  2722      * not exist return null.
  2723      */
  2724     public Type lub(Type t1, Type t2) {
  2725         return lub(List.of(t1, t2));
  2728     /**
  2729      * Return the least upper bound (lub) of set of types.  If the lub
  2730      * does not exist return the type of null (bottom).
  2731      */
  2732     public Type lub(List<Type> ts) {
  2733         final int ARRAY_BOUND = 1;
  2734         final int CLASS_BOUND = 2;
  2735         int boundkind = 0;
  2736         for (Type t : ts) {
  2737             switch (t.tag) {
  2738             case CLASS:
  2739                 boundkind |= CLASS_BOUND;
  2740                 break;
  2741             case ARRAY:
  2742                 boundkind |= ARRAY_BOUND;
  2743                 break;
  2744             case  TYPEVAR:
  2745                 do {
  2746                     t = t.getUpperBound();
  2747                 } while (t.tag == TYPEVAR);
  2748                 if (t.tag == ARRAY) {
  2749                     boundkind |= ARRAY_BOUND;
  2750                 } else {
  2751                     boundkind |= CLASS_BOUND;
  2753                 break;
  2754             default:
  2755                 if (t.isPrimitive())
  2756                     return syms.errType;
  2759         switch (boundkind) {
  2760         case 0:
  2761             return syms.botType;
  2763         case ARRAY_BOUND:
  2764             // calculate lub(A[], B[])
  2765             List<Type> elements = Type.map(ts, elemTypeFun);
  2766             for (Type t : elements) {
  2767                 if (t.isPrimitive()) {
  2768                     // if a primitive type is found, then return
  2769                     // arraySuperType unless all the types are the
  2770                     // same
  2771                     Type first = ts.head;
  2772                     for (Type s : ts.tail) {
  2773                         if (!isSameType(first, s)) {
  2774                              // lub(int[], B[]) is Cloneable & Serializable
  2775                             return arraySuperType();
  2778                     // all the array types are the same, return one
  2779                     // lub(int[], int[]) is int[]
  2780                     return first;
  2783             // lub(A[], B[]) is lub(A, B)[]
  2784             return new ArrayType(lub(elements), syms.arrayClass);
  2786         case CLASS_BOUND:
  2787             // calculate lub(A, B)
  2788             while (ts.head.tag != CLASS && ts.head.tag != TYPEVAR)
  2789                 ts = ts.tail;
  2790             assert !ts.isEmpty();
  2791             List<Type> cl = closure(ts.head);
  2792             for (Type t : ts.tail) {
  2793                 if (t.tag == CLASS || t.tag == TYPEVAR)
  2794                     cl = intersect(cl, closure(t));
  2796             return compoundMin(cl);
  2798         default:
  2799             // calculate lub(A, B[])
  2800             List<Type> classes = List.of(arraySuperType());
  2801             for (Type t : ts) {
  2802                 if (t.tag != ARRAY) // Filter out any arrays
  2803                     classes = classes.prepend(t);
  2805             // lub(A, B[]) is lub(A, arraySuperType)
  2806             return lub(classes);
  2809     // where
  2810         private Type arraySuperType = null;
  2811         private Type arraySuperType() {
  2812             // initialized lazily to avoid problems during compiler startup
  2813             if (arraySuperType == null) {
  2814                 synchronized (this) {
  2815                     if (arraySuperType == null) {
  2816                         // JLS 10.8: all arrays implement Cloneable and Serializable.
  2817                         arraySuperType = makeCompoundType(List.of(syms.serializableType,
  2818                                                                   syms.cloneableType),
  2819                                                           syms.objectType);
  2823             return arraySuperType;
  2825     // </editor-fold>
  2827     // <editor-fold defaultstate="collapsed" desc="Greatest lower bound">
  2828     public Type glb(Type t, Type s) {
  2829         if (s == null)
  2830             return t;
  2831         else if (isSubtypeNoCapture(t, s))
  2832             return t;
  2833         else if (isSubtypeNoCapture(s, t))
  2834             return s;
  2836         List<Type> closure = union(closure(t), closure(s));
  2837         List<Type> bounds = closureMin(closure);
  2839         if (bounds.isEmpty()) {             // length == 0
  2840             return syms.objectType;
  2841         } else if (bounds.tail.isEmpty()) { // length == 1
  2842             return bounds.head;
  2843         } else {                            // length > 1
  2844             int classCount = 0;
  2845             for (Type bound : bounds)
  2846                 if (!bound.isInterface())
  2847                     classCount++;
  2848             if (classCount > 1)
  2849                 return createErrorType(t);
  2851         return makeCompoundType(bounds);
  2853     // </editor-fold>
  2855     // <editor-fold defaultstate="collapsed" desc="hashCode">
  2856     /**
  2857      * Compute a hash code on a type.
  2858      */
  2859     public static int hashCode(Type t) {
  2860         return hashCode.visit(t);
  2862     // where
  2863         private static final UnaryVisitor<Integer> hashCode = new UnaryVisitor<Integer>() {
  2865             public Integer visitType(Type t, Void ignored) {
  2866                 return t.tag;
  2869             @Override
  2870             public Integer visitClassType(ClassType t, Void ignored) {
  2871                 int result = visit(t.getEnclosingType());
  2872                 result *= 127;
  2873                 result += t.tsym.flatName().hashCode();
  2874                 for (Type s : t.getTypeArguments()) {
  2875                     result *= 127;
  2876                     result += visit(s);
  2878                 return result;
  2881             @Override
  2882             public Integer visitWildcardType(WildcardType t, Void ignored) {
  2883                 int result = t.kind.hashCode();
  2884                 if (t.type != null) {
  2885                     result *= 127;
  2886                     result += visit(t.type);
  2888                 return result;
  2891             @Override
  2892             public Integer visitArrayType(ArrayType t, Void ignored) {
  2893                 return visit(t.elemtype) + 12;
  2896             @Override
  2897             public Integer visitTypeVar(TypeVar t, Void ignored) {
  2898                 return System.identityHashCode(t.tsym);
  2901             @Override
  2902             public Integer visitUndetVar(UndetVar t, Void ignored) {
  2903                 return System.identityHashCode(t);
  2906             @Override
  2907             public Integer visitErrorType(ErrorType t, Void ignored) {
  2908                 return 0;
  2910         };
  2911     // </editor-fold>
  2913     // <editor-fold defaultstate="collapsed" desc="Return-Type-Substitutable">
  2914     /**
  2915      * Does t have a result that is a subtype of the result type of s,
  2916      * suitable for covariant returns?  It is assumed that both types
  2917      * are (possibly polymorphic) method types.  Monomorphic method
  2918      * types are handled in the obvious way.  Polymorphic method types
  2919      * require renaming all type variables of one to corresponding
  2920      * type variables in the other, where correspondence is by
  2921      * position in the type parameter list. */
  2922     public boolean resultSubtype(Type t, Type s, Warner warner) {
  2923         List<Type> tvars = t.getTypeArguments();
  2924         List<Type> svars = s.getTypeArguments();
  2925         Type tres = t.getReturnType();
  2926         Type sres = subst(s.getReturnType(), svars, tvars);
  2927         return covariantReturnType(tres, sres, warner);
  2930     /**
  2931      * Return-Type-Substitutable.
  2932      * @see <a href="http://java.sun.com/docs/books/jls/">The Java
  2933      * Language Specification, Third Ed. (8.4.5)</a>
  2934      */
  2935     public boolean returnTypeSubstitutable(Type r1, Type r2) {
  2936         return returnTypeSubstitutable(r1, r2, Warner.noWarnings);
  2938     //where
  2939     public boolean returnTypeSubstitutable(Type r1, Type r2, Warner warner) {
  2940         if (hasSameArgs(r1, r2))
  2941             return resultSubtype(r1, r2, warner);
  2942         else
  2943             return covariantReturnType(r1.getReturnType(),
  2944                                        r2.getReturnType(),
  2945                                        warner);
  2948     /**
  2949      * Is t an appropriate return type in an overrider for a
  2950      * method that returns s?
  2951      */
  2952     public boolean covariantReturnType(Type t, Type s, Warner warner) {
  2953         //are return types identical?
  2954         if (isSameType(t, s))
  2955             return true;
  2956         //if t and s are both reference types...
  2957         else if(source.allowCovariantReturns() &&
  2958             !t.isPrimitive() &&
  2959             !s.isPrimitive()) {
  2960             //check that t is some unchecked subtype of s
  2961             if (isSubtypeUnchecked(t, s, warner))
  2962                 return true;
  2963             //otherwise check that t = |s|
  2964             else if (isSameType(t, erasure(s))) {
  2965                 warner.warnUnchecked();
  2966                 return true;
  2969         //otherwise t is not return type substitutable for s
  2970         return false;
  2972     // </editor-fold>
  2974     // <editor-fold defaultstate="collapsed" desc="Box/unbox support">
  2975     /**
  2976      * Return the class that boxes the given primitive.
  2977      */
  2978     public ClassSymbol boxedClass(Type t) {
  2979         return reader.enterClass(syms.boxedName[t.tag]);
  2982     /**
  2983      * Return the primitive type corresponding to a boxed type.
  2984      */
  2985     public Type unboxedType(Type t) {
  2986         if (allowBoxing) {
  2987             for (int i=0; i<syms.boxedName.length; i++) {
  2988                 Name box = syms.boxedName[i];
  2989                 if (box != null &&
  2990                     asSuper(t, reader.enterClass(box)) != null)
  2991                     return syms.typeOfTag[i];
  2994         return Type.noType;
  2996     // </editor-fold>
  2998     // <editor-fold defaultstate="collapsed" desc="Capture conversion">
  2999     /*
  3000      * JLS 3rd Ed. 5.1.10 Capture Conversion:
  3002      * Let G name a generic type declaration with n formal type
  3003      * parameters A1 ... An with corresponding bounds U1 ... Un. There
  3004      * exists a capture conversion from G<T1 ... Tn> to G<S1 ... Sn>,
  3005      * where, for 1 <= i <= n:
  3007      * + If Ti is a wildcard type argument (4.5.1) of the form ? then
  3008      *   Si is a fresh type variable whose upper bound is
  3009      *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is the null
  3010      *   type.
  3012      * + If Ti is a wildcard type argument of the form ? extends Bi,
  3013      *   then Si is a fresh type variable whose upper bound is
  3014      *   glb(Bi, Ui[A1 := S1, ..., An := Sn]) and whose lower bound is
  3015      *   the null type, where glb(V1,... ,Vm) is V1 & ... & Vm. It is
  3016      *   a compile-time error if for any two classes (not interfaces)
  3017      *   Vi and Vj,Vi is not a subclass of Vj or vice versa.
  3019      * + If Ti is a wildcard type argument of the form ? super Bi,
  3020      *   then Si is a fresh type variable whose upper bound is
  3021      *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is Bi.
  3023      * + Otherwise, Si = Ti.
  3025      * Capture conversion on any type other than a parameterized type
  3026      * (4.5) acts as an identity conversion (5.1.1). Capture
  3027      * conversions never require a special action at run time and
  3028      * therefore never throw an exception at run time.
  3030      * Capture conversion is not applied recursively.
  3031      */
  3032     /**
  3033      * Capture conversion as specified by JLS 3rd Ed.
  3034      */
  3035     public Type capture(Type t) {
  3036         if (t.tag != CLASS)
  3037             return t;
  3038         ClassType cls = (ClassType)t;
  3039         if (cls.isRaw() || !cls.isParameterized())
  3040             return cls;
  3042         ClassType G = (ClassType)cls.asElement().asType();
  3043         List<Type> A = G.getTypeArguments();
  3044         List<Type> T = cls.getTypeArguments();
  3045         List<Type> S = freshTypeVariables(T);
  3047         List<Type> currentA = A;
  3048         List<Type> currentT = T;
  3049         List<Type> currentS = S;
  3050         boolean captured = false;
  3051         while (!currentA.isEmpty() &&
  3052                !currentT.isEmpty() &&
  3053                !currentS.isEmpty()) {
  3054             if (currentS.head != currentT.head) {
  3055                 captured = true;
  3056                 WildcardType Ti = (WildcardType)currentT.head;
  3057                 Type Ui = currentA.head.getUpperBound();
  3058                 CapturedType Si = (CapturedType)currentS.head;
  3059                 if (Ui == null)
  3060                     Ui = syms.objectType;
  3061                 switch (Ti.kind) {
  3062                 case UNBOUND:
  3063                     Si.bound = subst(Ui, A, S);
  3064                     Si.lower = syms.botType;
  3065                     break;
  3066                 case EXTENDS:
  3067                     Si.bound = glb(Ti.getExtendsBound(), subst(Ui, A, S));
  3068                     Si.lower = syms.botType;
  3069                     break;
  3070                 case SUPER:
  3071                     Si.bound = subst(Ui, A, S);
  3072                     Si.lower = Ti.getSuperBound();
  3073                     break;
  3075                 if (Si.bound == Si.lower)
  3076                     currentS.head = Si.bound;
  3078             currentA = currentA.tail;
  3079             currentT = currentT.tail;
  3080             currentS = currentS.tail;
  3082         if (!currentA.isEmpty() || !currentT.isEmpty() || !currentS.isEmpty())
  3083             return erasure(t); // some "rare" type involved
  3085         if (captured)
  3086             return new ClassType(cls.getEnclosingType(), S, cls.tsym);
  3087         else
  3088             return t;
  3090     // where
  3091         private List<Type> freshTypeVariables(List<Type> types) {
  3092             ListBuffer<Type> result = lb();
  3093             for (Type t : types) {
  3094                 if (t.tag == WILDCARD) {
  3095                     Type bound = ((WildcardType)t).getExtendsBound();
  3096                     if (bound == null)
  3097                         bound = syms.objectType;
  3098                     result.append(new CapturedType(capturedName,
  3099                                                    syms.noSymbol,
  3100                                                    bound,
  3101                                                    syms.botType,
  3102                                                    (WildcardType)t));
  3103                 } else {
  3104                     result.append(t);
  3107             return result.toList();
  3109     // </editor-fold>
  3111     // <editor-fold defaultstate="collapsed" desc="Internal utility methods">
  3112     private List<Type> upperBounds(List<Type> ss) {
  3113         if (ss.isEmpty()) return ss;
  3114         Type head = upperBound(ss.head);
  3115         List<Type> tail = upperBounds(ss.tail);
  3116         if (head != ss.head || tail != ss.tail)
  3117             return tail.prepend(head);
  3118         else
  3119             return ss;
  3122     private boolean sideCast(Type from, Type to, Warner warn) {
  3123         // We are casting from type $from$ to type $to$, which are
  3124         // non-final unrelated types.  This method
  3125         // tries to reject a cast by transferring type parameters
  3126         // from $to$ to $from$ by common superinterfaces.
  3127         boolean reverse = false;
  3128         Type target = to;
  3129         if ((to.tsym.flags() & INTERFACE) == 0) {
  3130             assert (from.tsym.flags() & INTERFACE) != 0;
  3131             reverse = true;
  3132             to = from;
  3133             from = target;
  3135         List<Type> commonSupers = superClosure(to, erasure(from));
  3136         boolean giveWarning = commonSupers.isEmpty();
  3137         // The arguments to the supers could be unified here to
  3138         // get a more accurate analysis
  3139         while (commonSupers.nonEmpty()) {
  3140             Type t1 = asSuper(from, commonSupers.head.tsym);
  3141             Type t2 = commonSupers.head; // same as asSuper(to, commonSupers.head.tsym);
  3142             if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
  3143                 return false;
  3144             giveWarning = giveWarning || (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2));
  3145             commonSupers = commonSupers.tail;
  3147         if (giveWarning && !isReifiable(reverse ? from : to))
  3148             warn.warnUnchecked();
  3149         if (!source.allowCovariantReturns())
  3150             // reject if there is a common method signature with
  3151             // incompatible return types.
  3152             chk.checkCompatibleAbstracts(warn.pos(), from, to);
  3153         return true;
  3156     private boolean sideCastFinal(Type from, Type to, Warner warn) {
  3157         // We are casting from type $from$ to type $to$, which are
  3158         // unrelated types one of which is final and the other of
  3159         // which is an interface.  This method
  3160         // tries to reject a cast by transferring type parameters
  3161         // from the final class to the interface.
  3162         boolean reverse = false;
  3163         Type target = to;
  3164         if ((to.tsym.flags() & INTERFACE) == 0) {
  3165             assert (from.tsym.flags() & INTERFACE) != 0;
  3166             reverse = true;
  3167             to = from;
  3168             from = target;
  3170         assert (from.tsym.flags() & FINAL) != 0;
  3171         Type t1 = asSuper(from, to.tsym);
  3172         if (t1 == null) return false;
  3173         Type t2 = to;
  3174         if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
  3175             return false;
  3176         if (!source.allowCovariantReturns())
  3177             // reject if there is a common method signature with
  3178             // incompatible return types.
  3179             chk.checkCompatibleAbstracts(warn.pos(), from, to);
  3180         if (!isReifiable(target) &&
  3181             (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2)))
  3182             warn.warnUnchecked();
  3183         return true;
  3186     private boolean giveWarning(Type from, Type to) {
  3187         // To and from are (possibly different) parameterizations
  3188         // of the same class or interface
  3189         return to.isParameterized() && !containsType(to.allparams(), from.allparams());
  3192     private List<Type> superClosure(Type t, Type s) {
  3193         List<Type> cl = List.nil();
  3194         for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
  3195             if (isSubtype(s, erasure(l.head))) {
  3196                 cl = insert(cl, l.head);
  3197             } else {
  3198                 cl = union(cl, superClosure(l.head, s));
  3201         return cl;
  3204     private boolean containsTypeEquivalent(Type t, Type s) {
  3205         return
  3206             isSameType(t, s) || // shortcut
  3207             containsType(t, s) && containsType(s, t);
  3210     // <editor-fold defaultstate="collapsed" desc="adapt">
  3211     /**
  3212      * Adapt a type by computing a substitution which maps a source
  3213      * type to a target type.
  3215      * @param source    the source type
  3216      * @param target    the target type
  3217      * @param from      the type variables of the computed substitution
  3218      * @param to        the types of the computed substitution.
  3219      */
  3220     public void adapt(Type source,
  3221                        Type target,
  3222                        ListBuffer<Type> from,
  3223                        ListBuffer<Type> to) throws AdaptFailure {
  3224         new Adapter(from, to).adapt(source, target);
  3227     class Adapter extends SimpleVisitor<Void, Type> {
  3229         ListBuffer<Type> from;
  3230         ListBuffer<Type> to;
  3231         Map<Symbol,Type> mapping;
  3233         Adapter(ListBuffer<Type> from, ListBuffer<Type> to) {
  3234             this.from = from;
  3235             this.to = to;
  3236             mapping = new HashMap<Symbol,Type>();
  3239         public void adapt(Type source, Type target) throws AdaptFailure {
  3240             visit(source, target);
  3241             List<Type> fromList = from.toList();
  3242             List<Type> toList = to.toList();
  3243             while (!fromList.isEmpty()) {
  3244                 Type val = mapping.get(fromList.head.tsym);
  3245                 if (toList.head != val)
  3246                     toList.head = val;
  3247                 fromList = fromList.tail;
  3248                 toList = toList.tail;
  3252         @Override
  3253         public Void visitClassType(ClassType source, Type target) throws AdaptFailure {
  3254             if (target.tag == CLASS)
  3255                 adaptRecursive(source.allparams(), target.allparams());
  3256             return null;
  3259         @Override
  3260         public Void visitArrayType(ArrayType source, Type target) throws AdaptFailure {
  3261             if (target.tag == ARRAY)
  3262                 adaptRecursive(elemtype(source), elemtype(target));
  3263             return null;
  3266         @Override
  3267         public Void visitWildcardType(WildcardType source, Type target) throws AdaptFailure {
  3268             if (source.isExtendsBound())
  3269                 adaptRecursive(upperBound(source), upperBound(target));
  3270             else if (source.isSuperBound())
  3271                 adaptRecursive(lowerBound(source), lowerBound(target));
  3272             return null;
  3275         @Override
  3276         public Void visitTypeVar(TypeVar source, Type target) throws AdaptFailure {
  3277             // Check to see if there is
  3278             // already a mapping for $source$, in which case
  3279             // the old mapping will be merged with the new
  3280             Type val = mapping.get(source.tsym);
  3281             if (val != null) {
  3282                 if (val.isSuperBound() && target.isSuperBound()) {
  3283                     val = isSubtype(lowerBound(val), lowerBound(target))
  3284                         ? target : val;
  3285                 } else if (val.isExtendsBound() && target.isExtendsBound()) {
  3286                     val = isSubtype(upperBound(val), upperBound(target))
  3287                         ? val : target;
  3288                 } else if (!isSameType(val, target)) {
  3289                     throw new AdaptFailure();
  3291             } else {
  3292                 val = target;
  3293                 from.append(source);
  3294                 to.append(target);
  3296             mapping.put(source.tsym, val);
  3297             return null;
  3300         @Override
  3301         public Void visitType(Type source, Type target) {
  3302             return null;
  3305         private Set<TypePair> cache = new HashSet<TypePair>();
  3307         private void adaptRecursive(Type source, Type target) {
  3308             TypePair pair = new TypePair(source, target);
  3309             if (cache.add(pair)) {
  3310                 try {
  3311                     visit(source, target);
  3312                 } finally {
  3313                     cache.remove(pair);
  3318         private void adaptRecursive(List<Type> source, List<Type> target) {
  3319             if (source.length() == target.length()) {
  3320                 while (source.nonEmpty()) {
  3321                     adaptRecursive(source.head, target.head);
  3322                     source = source.tail;
  3323                     target = target.tail;
  3329     public static class AdaptFailure extends RuntimeException {
  3330         static final long serialVersionUID = -7490231548272701566L;
  3333     private void adaptSelf(Type t,
  3334                            ListBuffer<Type> from,
  3335                            ListBuffer<Type> to) {
  3336         try {
  3337             //if (t.tsym.type != t)
  3338                 adapt(t.tsym.type, t, from, to);
  3339         } catch (AdaptFailure ex) {
  3340             // Adapt should never fail calculating a mapping from
  3341             // t.tsym.type to t as there can be no merge problem.
  3342             throw new AssertionError(ex);
  3345     // </editor-fold>
  3347     /**
  3348      * Rewrite all type variables (universal quantifiers) in the given
  3349      * type to wildcards (existential quantifiers).  This is used to
  3350      * determine if a cast is allowed.  For example, if high is true
  3351      * and {@code T <: Number}, then {@code List<T>} is rewritten to
  3352      * {@code List<?  extends Number>}.  Since {@code List<Integer> <:
  3353      * List<? extends Number>} a {@code List<T>} can be cast to {@code
  3354      * List<Integer>} with a warning.
  3355      * @param t a type
  3356      * @param high if true return an upper bound; otherwise a lower
  3357      * bound
  3358      * @param rewriteTypeVars only rewrite captured wildcards if false;
  3359      * otherwise rewrite all type variables
  3360      * @return the type rewritten with wildcards (existential
  3361      * quantifiers) only
  3362      */
  3363     private Type rewriteQuantifiers(Type t, boolean high, boolean rewriteTypeVars) {
  3364         return new Rewriter(high, rewriteTypeVars).rewrite(t);
  3367     class Rewriter extends UnaryVisitor<Type> {
  3369         boolean high;
  3370         boolean rewriteTypeVars;
  3372         Rewriter(boolean high, boolean rewriteTypeVars) {
  3373             this.high = high;
  3374             this.rewriteTypeVars = rewriteTypeVars;
  3377         Type rewrite(Type t) {
  3378             ListBuffer<Type> from = new ListBuffer<Type>();
  3379             ListBuffer<Type> to = new ListBuffer<Type>();
  3380             adaptSelf(t, from, to);
  3381             ListBuffer<Type> rewritten = new ListBuffer<Type>();
  3382             List<Type> formals = from.toList();
  3383             boolean changed = false;
  3384             for (Type arg : to.toList()) {
  3385                 Type bound = visit(arg);
  3386                 if (arg != bound) {
  3387                     changed = true;
  3388                     bound = high ? makeExtendsWildcard(bound, (TypeVar)formals.head)
  3389                               : makeSuperWildcard(bound, (TypeVar)formals.head);
  3391                 rewritten.append(bound);
  3392                 formals = formals.tail;
  3394             if (changed)
  3395                 return subst(t.tsym.type, from.toList(), rewritten.toList());
  3396             else
  3397                 return t;
  3400         public Type visitType(Type t, Void s) {
  3401             return high ? upperBound(t) : lowerBound(t);
  3404         @Override
  3405         public Type visitCapturedType(CapturedType t, Void s) {
  3406             return visitWildcardType(t.wildcard, null);
  3409         @Override
  3410         public Type visitTypeVar(TypeVar t, Void s) {
  3411             if (rewriteTypeVars)
  3412                 return high ? t.bound : syms.botType;
  3413             else
  3414                 return t;
  3417         @Override
  3418         public Type visitWildcardType(WildcardType t, Void s) {
  3419             Type bound = high ? t.getExtendsBound() :
  3420                                 t.getSuperBound();
  3421             if (bound == null)
  3422                 bound = high ? syms.objectType : syms.botType;
  3423             return bound;
  3427     /**
  3428      * Create a wildcard with the given upper (extends) bound; create
  3429      * an unbounded wildcard if bound is Object.
  3431      * @param bound the upper bound
  3432      * @param formal the formal type parameter that will be
  3433      * substituted by the wildcard
  3434      */
  3435     private WildcardType makeExtendsWildcard(Type bound, TypeVar formal) {
  3436         if (bound == syms.objectType) {
  3437             return new WildcardType(syms.objectType,
  3438                                     BoundKind.UNBOUND,
  3439                                     syms.boundClass,
  3440                                     formal);
  3441         } else {
  3442             return new WildcardType(bound,
  3443                                     BoundKind.EXTENDS,
  3444                                     syms.boundClass,
  3445                                     formal);
  3449     /**
  3450      * Create a wildcard with the given lower (super) bound; create an
  3451      * unbounded wildcard if bound is bottom (type of {@code null}).
  3453      * @param bound the lower bound
  3454      * @param formal the formal type parameter that will be
  3455      * substituted by the wildcard
  3456      */
  3457     private WildcardType makeSuperWildcard(Type bound, TypeVar formal) {
  3458         if (bound.tag == BOT) {
  3459             return new WildcardType(syms.objectType,
  3460                                     BoundKind.UNBOUND,
  3461                                     syms.boundClass,
  3462                                     formal);
  3463         } else {
  3464             return new WildcardType(bound,
  3465                                     BoundKind.SUPER,
  3466                                     syms.boundClass,
  3467                                     formal);
  3471     /**
  3472      * A wrapper for a type that allows use in sets.
  3473      */
  3474     class SingletonType {
  3475         final Type t;
  3476         SingletonType(Type t) {
  3477             this.t = t;
  3479         public int hashCode() {
  3480             return Types.this.hashCode(t);
  3482         public boolean equals(Object obj) {
  3483             return (obj instanceof SingletonType) &&
  3484                 isSameType(t, ((SingletonType)obj).t);
  3486         public String toString() {
  3487             return t.toString();
  3490     // </editor-fold>
  3492     // <editor-fold defaultstate="collapsed" desc="Visitors">
  3493     /**
  3494      * A default visitor for types.  All visitor methods except
  3495      * visitType are implemented by delegating to visitType.  Concrete
  3496      * subclasses must provide an implementation of visitType and can
  3497      * override other methods as needed.
  3499      * @param <R> the return type of the operation implemented by this
  3500      * visitor; use Void if no return type is needed.
  3501      * @param <S> the type of the second argument (the first being the
  3502      * type itself) of the operation implemented by this visitor; use
  3503      * Void if a second argument is not needed.
  3504      */
  3505     public static abstract class DefaultTypeVisitor<R,S> implements Type.Visitor<R,S> {
  3506         final public R visit(Type t, S s)               { return t.accept(this, s); }
  3507         public R visitClassType(ClassType t, S s)       { return visitType(t, s); }
  3508         public R visitWildcardType(WildcardType t, S s) { return visitType(t, s); }
  3509         public R visitArrayType(ArrayType t, S s)       { return visitType(t, s); }
  3510         public R visitMethodType(MethodType t, S s)     { return visitType(t, s); }
  3511         public R visitPackageType(PackageType t, S s)   { return visitType(t, s); }
  3512         public R visitTypeVar(TypeVar t, S s)           { return visitType(t, s); }
  3513         public R visitCapturedType(CapturedType t, S s) { return visitType(t, s); }
  3514         public R visitForAll(ForAll t, S s)             { return visitType(t, s); }
  3515         public R visitUndetVar(UndetVar t, S s)         { return visitType(t, s); }
  3516         public R visitErrorType(ErrorType t, S s)       { return visitType(t, s); }
  3519     /**
  3520      * A default visitor for symbols.  All visitor methods except
  3521      * visitSymbol are implemented by delegating to visitSymbol.  Concrete
  3522      * subclasses must provide an implementation of visitSymbol and can
  3523      * override other methods as needed.
  3525      * @param <R> the return type of the operation implemented by this
  3526      * visitor; use Void if no return type is needed.
  3527      * @param <S> the type of the second argument (the first being the
  3528      * symbol itself) of the operation implemented by this visitor; use
  3529      * Void if a second argument is not needed.
  3530      */
  3531     public static abstract class DefaultSymbolVisitor<R,S> implements Symbol.Visitor<R,S> {
  3532         final public R visit(Symbol s, S arg)                   { return s.accept(this, arg); }
  3533         public R visitClassSymbol(ClassSymbol s, S arg)         { return visitSymbol(s, arg); }
  3534         public R visitMethodSymbol(MethodSymbol s, S arg)       { return visitSymbol(s, arg); }
  3535         public R visitOperatorSymbol(OperatorSymbol s, S arg)   { return visitSymbol(s, arg); }
  3536         public R visitPackageSymbol(PackageSymbol s, S arg)     { return visitSymbol(s, arg); }
  3537         public R visitTypeSymbol(TypeSymbol s, S arg)           { return visitSymbol(s, arg); }
  3538         public R visitVarSymbol(VarSymbol s, S arg)             { return visitSymbol(s, arg); }
  3541     /**
  3542      * A <em>simple</em> visitor for types.  This visitor is simple as
  3543      * captured wildcards, for-all types (generic methods), and
  3544      * undetermined type variables (part of inference) are hidden.
  3545      * Captured wildcards are hidden by treating them as type
  3546      * variables and the rest are hidden by visiting their qtypes.
  3548      * @param <R> the return type of the operation implemented by this
  3549      * visitor; use Void if no return type is needed.
  3550      * @param <S> the type of the second argument (the first being the
  3551      * type itself) of the operation implemented by this visitor; use
  3552      * Void if a second argument is not needed.
  3553      */
  3554     public static abstract class SimpleVisitor<R,S> extends DefaultTypeVisitor<R,S> {
  3555         @Override
  3556         public R visitCapturedType(CapturedType t, S s) {
  3557             return visitTypeVar(t, s);
  3559         @Override
  3560         public R visitForAll(ForAll t, S s) {
  3561             return visit(t.qtype, s);
  3563         @Override
  3564         public R visitUndetVar(UndetVar t, S s) {
  3565             return visit(t.qtype, s);
  3569     /**
  3570      * A plain relation on types.  That is a 2-ary function on the
  3571      * form Type&nbsp;&times;&nbsp;Type&nbsp;&rarr;&nbsp;Boolean.
  3572      * <!-- In plain text: Type x Type -> Boolean -->
  3573      */
  3574     public static abstract class TypeRelation extends SimpleVisitor<Boolean,Type> {}
  3576     /**
  3577      * A convenience visitor for implementing operations that only
  3578      * require one argument (the type itself), that is, unary
  3579      * operations.
  3581      * @param <R> the return type of the operation implemented by this
  3582      * visitor; use Void if no return type is needed.
  3583      */
  3584     public static abstract class UnaryVisitor<R> extends SimpleVisitor<R,Void> {
  3585         final public R visit(Type t) { return t.accept(this, null); }
  3588     /**
  3589      * A visitor for implementing a mapping from types to types.  The
  3590      * default behavior of this class is to implement the identity
  3591      * mapping (mapping a type to itself).  This can be overridden in
  3592      * subclasses.
  3594      * @param <S> the type of the second argument (the first being the
  3595      * type itself) of this mapping; use Void if a second argument is
  3596      * not needed.
  3597      */
  3598     public static class MapVisitor<S> extends DefaultTypeVisitor<Type,S> {
  3599         final public Type visit(Type t) { return t.accept(this, null); }
  3600         public Type visitType(Type t, S s) { return t; }
  3602     // </editor-fold>

mercurial