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

Fri, 26 Jun 2009 18:51:39 -0700

author
jjg
date
Fri, 26 Jun 2009 18:51:39 -0700
changeset 308
03944ee4fac4
parent 299
22872b24d38c
child 341
85fecace920b
permissions
-rw-r--r--

6843077: JSR 308: Annotations on types
Reviewed-by: jjg, mcimadamore, darcy
Contributed-by: mernst@cs.washington.edu, mali@csail.mit.edu, mpapi@csail.mit.edu

     1 /*
     2  * Copyright 2003-2009 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.api.Messages;
    32 import com.sun.tools.javac.util.*;
    33 import com.sun.tools.javac.util.List;
    35 import com.sun.tools.javac.jvm.ClassReader;
    36 import com.sun.tools.javac.comp.Check;
    38 import static com.sun.tools.javac.code.Type.*;
    39 import static com.sun.tools.javac.code.TypeTags.*;
    40 import static com.sun.tools.javac.code.Symbol.*;
    41 import static com.sun.tools.javac.code.Flags.*;
    42 import static com.sun.tools.javac.code.BoundKind.*;
    43 import static com.sun.tools.javac.util.ListBuffer.lb;
    45 /**
    46  * Utility class containing various operations on types.
    47  *
    48  * <p>Unless other names are more illustrative, the following naming
    49  * conventions should be observed in this file:
    50  *
    51  * <dl>
    52  * <dt>t</dt>
    53  * <dd>If the first argument to an operation is a type, it should be named t.</dd>
    54  * <dt>s</dt>
    55  * <dd>Similarly, if the second argument to an operation is a type, it should be named s.</dd>
    56  * <dt>ts</dt>
    57  * <dd>If an operations takes a list of types, the first should be named ts.</dd>
    58  * <dt>ss</dt>
    59  * <dd>A second list of types should be named ss.</dd>
    60  * </dl>
    61  *
    62  * <p><b>This is NOT part of any API supported by Sun Microsystems.
    63  * If you write code that depends on this, you do so at your own risk.
    64  * This code and its internal interfaces are subject to change or
    65  * deletion without notice.</b>
    66  */
    67 public class Types {
    68     protected static final Context.Key<Types> typesKey =
    69         new Context.Key<Types>();
    71     final Symtab syms;
    72     final JavacMessages messages;
    73     final Names names;
    74     final boolean allowBoxing;
    75     final ClassReader reader;
    76     final Source source;
    77     final Check chk;
    78     List<Warner> warnStack = List.nil();
    79     final Name capturedName;
    81     // <editor-fold defaultstate="collapsed" desc="Instantiating">
    82     public static Types instance(Context context) {
    83         Types instance = context.get(typesKey);
    84         if (instance == null)
    85             instance = new Types(context);
    86         return instance;
    87     }
    89     protected Types(Context context) {
    90         context.put(typesKey, this);
    91         syms = Symtab.instance(context);
    92         names = Names.instance(context);
    93         allowBoxing = Source.instance(context).allowBoxing();
    94         reader = ClassReader.instance(context);
    95         source = Source.instance(context);
    96         chk = Check.instance(context);
    97         capturedName = names.fromString("<captured wildcard>");
    98         messages = JavacMessages.instance(context);
    99     }
   100     // </editor-fold>
   102     // <editor-fold defaultstate="collapsed" desc="upperBound">
   103     /**
   104      * The "rvalue conversion".<br>
   105      * The upper bound of most types is the type
   106      * itself.  Wildcards, on the other hand have upper
   107      * and lower bounds.
   108      * @param t a type
   109      * @return the upper bound of the given type
   110      */
   111     public Type upperBound(Type t) {
   112         return upperBound.visit(t);
   113     }
   114     // where
   115         private final MapVisitor<Void> upperBound = new MapVisitor<Void>() {
   117             @Override
   118             public Type visitWildcardType(WildcardType t, Void ignored) {
   119                 if (t.isSuperBound())
   120                     return t.bound == null ? syms.objectType : t.bound.bound;
   121                 else
   122                     return visit(t.type);
   123             }
   125             @Override
   126             public Type visitCapturedType(CapturedType t, Void ignored) {
   127                 return visit(t.bound);
   128             }
   129         };
   130     // </editor-fold>
   132     // <editor-fold defaultstate="collapsed" desc="lowerBound">
   133     /**
   134      * The "lvalue conversion".<br>
   135      * The lower bound of most types is the type
   136      * itself.  Wildcards, on the other hand have upper
   137      * and lower bounds.
   138      * @param t a type
   139      * @return the lower bound of the given type
   140      */
   141     public Type lowerBound(Type t) {
   142         return lowerBound.visit(t);
   143     }
   144     // where
   145         private final MapVisitor<Void> lowerBound = new MapVisitor<Void>() {
   147             @Override
   148             public Type visitWildcardType(WildcardType t, Void ignored) {
   149                 return t.isExtendsBound() ? syms.botType : visit(t.type);
   150             }
   152             @Override
   153             public Type visitCapturedType(CapturedType t, Void ignored) {
   154                 return visit(t.getLowerBound());
   155             }
   156         };
   157     // </editor-fold>
   159     // <editor-fold defaultstate="collapsed" desc="isUnbounded">
   160     /**
   161      * Checks that all the arguments to a class are unbounded
   162      * wildcards or something else that doesn't make any restrictions
   163      * on the arguments. If a class isUnbounded, a raw super- or
   164      * subclass can be cast to it without a warning.
   165      * @param t a type
   166      * @return true iff the given type is unbounded or raw
   167      */
   168     public boolean isUnbounded(Type t) {
   169         return isUnbounded.visit(t);
   170     }
   171     // where
   172         private final UnaryVisitor<Boolean> isUnbounded = new UnaryVisitor<Boolean>() {
   174             public Boolean visitType(Type t, Void ignored) {
   175                 return true;
   176             }
   178             @Override
   179             public Boolean visitClassType(ClassType t, Void ignored) {
   180                 List<Type> parms = t.tsym.type.allparams();
   181                 List<Type> args = t.allparams();
   182                 while (parms.nonEmpty()) {
   183                     WildcardType unb = new WildcardType(syms.objectType,
   184                                                         BoundKind.UNBOUND,
   185                                                         syms.boundClass,
   186                                                         (TypeVar)parms.head);
   187                     if (!containsType(args.head, unb))
   188                         return false;
   189                     parms = parms.tail;
   190                     args = args.tail;
   191                 }
   192                 return true;
   193             }
   194         };
   195     // </editor-fold>
   197     // <editor-fold defaultstate="collapsed" desc="asSub">
   198     /**
   199      * Return the least specific subtype of t that starts with symbol
   200      * sym.  If none exists, return null.  The least specific subtype
   201      * is determined as follows:
   202      *
   203      * <p>If there is exactly one parameterized instance of sym that is a
   204      * subtype of t, that parameterized instance is returned.<br>
   205      * Otherwise, if the plain type or raw type `sym' is a subtype of
   206      * type t, the type `sym' itself is returned.  Otherwise, null is
   207      * returned.
   208      */
   209     public Type asSub(Type t, Symbol sym) {
   210         return asSub.visit(t, sym);
   211     }
   212     // where
   213         private final SimpleVisitor<Type,Symbol> asSub = new SimpleVisitor<Type,Symbol>() {
   215             public Type visitType(Type t, Symbol sym) {
   216                 return null;
   217             }
   219             @Override
   220             public Type visitClassType(ClassType t, Symbol sym) {
   221                 if (t.tsym == sym)
   222                     return t;
   223                 Type base = asSuper(sym.type, t.tsym);
   224                 if (base == null)
   225                     return null;
   226                 ListBuffer<Type> from = new ListBuffer<Type>();
   227                 ListBuffer<Type> to = new ListBuffer<Type>();
   228                 try {
   229                     adapt(base, t, from, to);
   230                 } catch (AdaptFailure ex) {
   231                     return null;
   232                 }
   233                 Type res = subst(sym.type, from.toList(), to.toList());
   234                 if (!isSubtype(res, t))
   235                     return null;
   236                 ListBuffer<Type> openVars = new ListBuffer<Type>();
   237                 for (List<Type> l = sym.type.allparams();
   238                      l.nonEmpty(); l = l.tail)
   239                     if (res.contains(l.head) && !t.contains(l.head))
   240                         openVars.append(l.head);
   241                 if (openVars.nonEmpty()) {
   242                     if (t.isRaw()) {
   243                         // The subtype of a raw type is raw
   244                         res = erasure(res);
   245                     } else {
   246                         // Unbound type arguments default to ?
   247                         List<Type> opens = openVars.toList();
   248                         ListBuffer<Type> qs = new ListBuffer<Type>();
   249                         for (List<Type> iter = opens; iter.nonEmpty(); iter = iter.tail) {
   250                             qs.append(new WildcardType(syms.objectType, BoundKind.UNBOUND, syms.boundClass, (TypeVar) iter.head));
   251                         }
   252                         res = subst(res, opens, qs.toList());
   253                     }
   254                 }
   255                 return res;
   256             }
   258             @Override
   259             public Type visitErrorType(ErrorType t, Symbol sym) {
   260                 return t;
   261             }
   262         };
   263     // </editor-fold>
   265     // <editor-fold defaultstate="collapsed" desc="isConvertible">
   266     /**
   267      * Is t a subtype of or convertiable via boxing/unboxing
   268      * convertions to s?
   269      */
   270     public boolean isConvertible(Type t, Type s, Warner warn) {
   271         boolean tPrimitive = t.isPrimitive();
   272         boolean sPrimitive = s.isPrimitive();
   273         if (tPrimitive == sPrimitive)
   274             return isSubtypeUnchecked(t, s, warn);
   275         if (!allowBoxing) return false;
   276         return tPrimitive
   277             ? isSubtype(boxedClass(t).type, s)
   278             : isSubtype(unboxedType(t), s);
   279     }
   281     /**
   282      * Is t a subtype of or convertiable via boxing/unboxing
   283      * convertions to s?
   284      */
   285     public boolean isConvertible(Type t, Type s) {
   286         return isConvertible(t, s, Warner.noWarnings);
   287     }
   288     // </editor-fold>
   290     // <editor-fold defaultstate="collapsed" desc="isSubtype">
   291     /**
   292      * Is t an unchecked subtype of s?
   293      */
   294     public boolean isSubtypeUnchecked(Type t, Type s) {
   295         return isSubtypeUnchecked(t, s, Warner.noWarnings);
   296     }
   297     /**
   298      * Is t an unchecked subtype of s?
   299      */
   300     public boolean isSubtypeUnchecked(Type t, Type s, Warner warn) {
   301         if (t.tag == ARRAY && s.tag == ARRAY) {
   302             return (((ArrayType)t).elemtype.tag <= lastBaseTag)
   303                 ? isSameType(elemtype(t), elemtype(s))
   304                 : isSubtypeUnchecked(elemtype(t), elemtype(s), warn);
   305         } else if (isSubtype(t, s)) {
   306             return true;
   307         }
   308         else if (t.tag == TYPEVAR) {
   309             return isSubtypeUnchecked(t.getUpperBound(), s, warn);
   310         }
   311         else if (s.tag == UNDETVAR) {
   312             UndetVar uv = (UndetVar)s;
   313             if (uv.inst != null)
   314                 return isSubtypeUnchecked(t, uv.inst, warn);
   315         }
   316         else if (!s.isRaw()) {
   317             Type t2 = asSuper(t, s.tsym);
   318             if (t2 != null && t2.isRaw()) {
   319                 if (isReifiable(s))
   320                     warn.silentUnchecked();
   321                 else
   322                     warn.warnUnchecked();
   323                 return true;
   324             }
   325         }
   326         return false;
   327     }
   329     /**
   330      * Is t a subtype of s?<br>
   331      * (not defined for Method and ForAll types)
   332      */
   333     final public boolean isSubtype(Type t, Type s) {
   334         return isSubtype(t, s, true);
   335     }
   336     final public boolean isSubtypeNoCapture(Type t, Type s) {
   337         return isSubtype(t, s, false);
   338     }
   339     public boolean isSubtype(Type t, Type s, boolean capture) {
   340         if (t == s)
   341             return true;
   343         if (s.tag >= firstPartialTag)
   344             return isSuperType(s, t);
   346         if (s.isCompound()) {
   347             for (Type s2 : interfaces(s).prepend(supertype(s))) {
   348                 if (!isSubtype(t, s2, capture))
   349                     return false;
   350             }
   351             return true;
   352         }
   354         Type lower = lowerBound(s);
   355         if (s != lower)
   356             return isSubtype(capture ? capture(t) : t, lower, false);
   358         return isSubtype.visit(capture ? capture(t) : t, s);
   359     }
   360     // where
   361         private TypeRelation isSubtype = new TypeRelation()
   362         {
   363             public Boolean visitType(Type t, Type s) {
   364                 switch (t.tag) {
   365                 case BYTE: case CHAR:
   366                     return (t.tag == s.tag ||
   367                               t.tag + 2 <= s.tag && s.tag <= DOUBLE);
   368                 case SHORT: case INT: case LONG: case FLOAT: case DOUBLE:
   369                     return t.tag <= s.tag && s.tag <= DOUBLE;
   370                 case BOOLEAN: case VOID:
   371                     return t.tag == s.tag;
   372                 case TYPEVAR:
   373                     return isSubtypeNoCapture(t.getUpperBound(), s);
   374                 case BOT:
   375                     return
   376                         s.tag == BOT || s.tag == CLASS ||
   377                         s.tag == ARRAY || s.tag == TYPEVAR;
   378                 case NONE:
   379                     return false;
   380                 default:
   381                     throw new AssertionError("isSubtype " + t.tag);
   382                 }
   383             }
   385             private Set<TypePair> cache = new HashSet<TypePair>();
   387             private boolean containsTypeRecursive(Type t, Type s) {
   388                 TypePair pair = new TypePair(t, s);
   389                 if (cache.add(pair)) {
   390                     try {
   391                         return containsType(t.getTypeArguments(),
   392                                             s.getTypeArguments());
   393                     } finally {
   394                         cache.remove(pair);
   395                     }
   396                 } else {
   397                     return containsType(t.getTypeArguments(),
   398                                         rewriteSupers(s).getTypeArguments());
   399                 }
   400             }
   402             private Type rewriteSupers(Type t) {
   403                 if (!t.isParameterized())
   404                     return t;
   405                 ListBuffer<Type> from = lb();
   406                 ListBuffer<Type> to = lb();
   407                 adaptSelf(t, from, to);
   408                 if (from.isEmpty())
   409                     return t;
   410                 ListBuffer<Type> rewrite = lb();
   411                 boolean changed = false;
   412                 for (Type orig : to.toList()) {
   413                     Type s = rewriteSupers(orig);
   414                     if (s.isSuperBound() && !s.isExtendsBound()) {
   415                         s = new WildcardType(syms.objectType,
   416                                              BoundKind.UNBOUND,
   417                                              syms.boundClass);
   418                         changed = true;
   419                     } else if (s != orig) {
   420                         s = new WildcardType(upperBound(s),
   421                                              BoundKind.EXTENDS,
   422                                              syms.boundClass);
   423                         changed = true;
   424                     }
   425                     rewrite.append(s);
   426                 }
   427                 if (changed)
   428                     return subst(t.tsym.type, from.toList(), rewrite.toList());
   429                 else
   430                     return t;
   431             }
   433             @Override
   434             public Boolean visitClassType(ClassType t, Type s) {
   435                 Type sup = asSuper(t, s.tsym);
   436                 return sup != null
   437                     && sup.tsym == s.tsym
   438                     // You're not allowed to write
   439                     //     Vector<Object> vec = new Vector<String>();
   440                     // But with wildcards you can write
   441                     //     Vector<? extends Object> vec = new Vector<String>();
   442                     // which means that subtype checking must be done
   443                     // here instead of same-type checking (via containsType).
   444                     && (!s.isParameterized() || containsTypeRecursive(s, sup))
   445                     && isSubtypeNoCapture(sup.getEnclosingType(),
   446                                           s.getEnclosingType());
   447             }
   449             @Override
   450             public Boolean visitArrayType(ArrayType t, Type s) {
   451                 if (s.tag == ARRAY) {
   452                     if (t.elemtype.tag <= lastBaseTag)
   453                         return isSameType(t.elemtype, elemtype(s));
   454                     else
   455                         return isSubtypeNoCapture(t.elemtype, elemtype(s));
   456                 }
   458                 if (s.tag == CLASS) {
   459                     Name sname = s.tsym.getQualifiedName();
   460                     return sname == names.java_lang_Object
   461                         || sname == names.java_lang_Cloneable
   462                         || sname == names.java_io_Serializable;
   463                 }
   465                 return false;
   466             }
   468             @Override
   469             public Boolean visitUndetVar(UndetVar t, Type s) {
   470                 //todo: test against origin needed? or replace with substitution?
   471                 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN)
   472                     return true;
   474                 if (t.inst != null)
   475                     return isSubtypeNoCapture(t.inst, s); // TODO: ", warn"?
   477                 t.hibounds = t.hibounds.prepend(s);
   478                 return true;
   479             }
   481             @Override
   482             public Boolean visitErrorType(ErrorType t, Type s) {
   483                 return true;
   484             }
   485         };
   487     /**
   488      * Is t a subtype of every type in given list `ts'?<br>
   489      * (not defined for Method and ForAll types)<br>
   490      * Allows unchecked conversions.
   491      */
   492     public boolean isSubtypeUnchecked(Type t, List<Type> ts, Warner warn) {
   493         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
   494             if (!isSubtypeUnchecked(t, l.head, warn))
   495                 return false;
   496         return true;
   497     }
   499     /**
   500      * Are corresponding elements of ts subtypes of ss?  If lists are
   501      * of different length, return false.
   502      */
   503     public boolean isSubtypes(List<Type> ts, List<Type> ss) {
   504         while (ts.tail != null && ss.tail != null
   505                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   506                isSubtype(ts.head, ss.head)) {
   507             ts = ts.tail;
   508             ss = ss.tail;
   509         }
   510         return ts.tail == null && ss.tail == null;
   511         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   512     }
   514     /**
   515      * Are corresponding elements of ts subtypes of ss, allowing
   516      * unchecked conversions?  If lists are of different length,
   517      * return false.
   518      **/
   519     public boolean isSubtypesUnchecked(List<Type> ts, List<Type> ss, Warner warn) {
   520         while (ts.tail != null && ss.tail != null
   521                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   522                isSubtypeUnchecked(ts.head, ss.head, warn)) {
   523             ts = ts.tail;
   524             ss = ss.tail;
   525         }
   526         return ts.tail == null && ss.tail == null;
   527         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   528     }
   529     // </editor-fold>
   531     // <editor-fold defaultstate="collapsed" desc="isSuperType">
   532     /**
   533      * Is t a supertype of s?
   534      */
   535     public boolean isSuperType(Type t, Type s) {
   536         switch (t.tag) {
   537         case ERROR:
   538             return true;
   539         case UNDETVAR: {
   540             UndetVar undet = (UndetVar)t;
   541             if (t == s ||
   542                 undet.qtype == s ||
   543                 s.tag == ERROR ||
   544                 s.tag == BOT) return true;
   545             if (undet.inst != null)
   546                 return isSubtype(s, undet.inst);
   547             undet.lobounds = undet.lobounds.prepend(s);
   548             return true;
   549         }
   550         default:
   551             return isSubtype(s, t);
   552         }
   553     }
   554     // </editor-fold>
   556     // <editor-fold defaultstate="collapsed" desc="isSameType">
   557     /**
   558      * Are corresponding elements of the lists the same type?  If
   559      * lists are of different length, return false.
   560      */
   561     public boolean isSameTypes(List<Type> ts, List<Type> ss) {
   562         while (ts.tail != null && ss.tail != null
   563                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
   564                isSameType(ts.head, ss.head)) {
   565             ts = ts.tail;
   566             ss = ss.tail;
   567         }
   568         return ts.tail == null && ss.tail == null;
   569         /*inlined: ts.isEmpty() && ss.isEmpty();*/
   570     }
   572     /**
   573      * Is t the same type as s?
   574      */
   575     public boolean isSameType(Type t, Type s) {
   576         return isSameType.visit(t, s);
   577     }
   578     // where
   579         private TypeRelation isSameType = new TypeRelation() {
   581             public Boolean visitType(Type t, Type s) {
   582                 if (t == s)
   583                     return true;
   585                 if (s.tag >= firstPartialTag)
   586                     return visit(s, t);
   588                 switch (t.tag) {
   589                 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
   590                 case DOUBLE: case BOOLEAN: case VOID: case BOT: case NONE:
   591                     return t.tag == s.tag;
   592                 case TYPEVAR:
   593                     return s.isSuperBound()
   594                         && !s.isExtendsBound()
   595                         && visit(t, upperBound(s));
   596                 default:
   597                     throw new AssertionError("isSameType " + t.tag);
   598                 }
   599             }
   601             @Override
   602             public Boolean visitWildcardType(WildcardType t, Type s) {
   603                 if (s.tag >= firstPartialTag)
   604                     return visit(s, t);
   605                 else
   606                     return false;
   607             }
   609             @Override
   610             public Boolean visitClassType(ClassType t, Type s) {
   611                 if (t == s)
   612                     return true;
   614                 if (s.tag >= firstPartialTag)
   615                     return visit(s, t);
   617                 if (s.isSuperBound() && !s.isExtendsBound())
   618                     return visit(t, upperBound(s)) && visit(t, lowerBound(s));
   620                 if (t.isCompound() && s.isCompound()) {
   621                     if (!visit(supertype(t), supertype(s)))
   622                         return false;
   624                     HashSet<SingletonType> set = new HashSet<SingletonType>();
   625                     for (Type x : interfaces(t))
   626                         set.add(new SingletonType(x));
   627                     for (Type x : interfaces(s)) {
   628                         if (!set.remove(new SingletonType(x)))
   629                             return false;
   630                     }
   631                     return (set.size() == 0);
   632                 }
   633                 return t.tsym == s.tsym
   634                     && visit(t.getEnclosingType(), s.getEnclosingType())
   635                     && containsTypeEquivalent(t.getTypeArguments(), s.getTypeArguments());
   636             }
   638             @Override
   639             public Boolean visitArrayType(ArrayType t, Type s) {
   640                 if (t == s)
   641                     return true;
   643                 if (s.tag >= firstPartialTag)
   644                     return visit(s, t);
   646                 return s.tag == ARRAY
   647                     && containsTypeEquivalent(t.elemtype, elemtype(s));
   648             }
   650             @Override
   651             public Boolean visitMethodType(MethodType t, Type s) {
   652                 // isSameType for methods does not take thrown
   653                 // exceptions into account!
   654                 return hasSameArgs(t, s) && visit(t.getReturnType(), s.getReturnType());
   655             }
   657             @Override
   658             public Boolean visitPackageType(PackageType t, Type s) {
   659                 return t == s;
   660             }
   662             @Override
   663             public Boolean visitForAll(ForAll t, Type s) {
   664                 if (s.tag != FORALL)
   665                     return false;
   667                 ForAll forAll = (ForAll)s;
   668                 return hasSameBounds(t, forAll)
   669                     && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
   670             }
   672             @Override
   673             public Boolean visitUndetVar(UndetVar t, Type s) {
   674                 if (s.tag == WILDCARD)
   675                     // FIXME, this might be leftovers from before capture conversion
   676                     return false;
   678                 if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN)
   679                     return true;
   681                 if (t.inst != null)
   682                     return visit(t.inst, s);
   684                 t.inst = fromUnknownFun.apply(s);
   685                 for (List<Type> l = t.lobounds; l.nonEmpty(); l = l.tail) {
   686                     if (!isSubtype(l.head, t.inst))
   687                         return false;
   688                 }
   689                 for (List<Type> l = t.hibounds; l.nonEmpty(); l = l.tail) {
   690                     if (!isSubtype(t.inst, l.head))
   691                         return false;
   692                 }
   693                 return true;
   694             }
   696             @Override
   697             public Boolean visitErrorType(ErrorType t, Type s) {
   698                 return true;
   699             }
   700         };
   701     // </editor-fold>
   703     // <editor-fold defaultstate="collapsed" desc="fromUnknownFun">
   704     /**
   705      * A mapping that turns all unknown types in this type to fresh
   706      * unknown variables.
   707      */
   708     public Mapping fromUnknownFun = new Mapping("fromUnknownFun") {
   709             public Type apply(Type t) {
   710                 if (t.tag == UNKNOWN) return new UndetVar(t);
   711                 else return t.map(this);
   712             }
   713         };
   714     // </editor-fold>
   716     // <editor-fold defaultstate="collapsed" desc="Contains Type">
   717     public boolean containedBy(Type t, Type s) {
   718         switch (t.tag) {
   719         case UNDETVAR:
   720             if (s.tag == WILDCARD) {
   721                 UndetVar undetvar = (UndetVar)t;
   722                 WildcardType wt = (WildcardType)s;
   723                 switch(wt.kind) {
   724                     case UNBOUND: //similar to ? extends Object
   725                     case EXTENDS: {
   726                         Type bound = upperBound(s);
   727                         // We should check the new upper bound against any of the
   728                         // undetvar's lower bounds.
   729                         for (Type t2 : undetvar.lobounds) {
   730                             if (!isSubtype(t2, bound))
   731                                 return false;
   732                         }
   733                         undetvar.hibounds = undetvar.hibounds.prepend(bound);
   734                         break;
   735                     }
   736                     case SUPER: {
   737                         Type bound = lowerBound(s);
   738                         // We should check the new lower bound against any of the
   739                         // undetvar's lower bounds.
   740                         for (Type t2 : undetvar.hibounds) {
   741                             if (!isSubtype(bound, t2))
   742                                 return false;
   743                         }
   744                         undetvar.lobounds = undetvar.lobounds.prepend(bound);
   745                         break;
   746                     }
   747                 }
   748                 return true;
   749             } else {
   750                 return isSameType(t, s);
   751             }
   752         case ERROR:
   753             return true;
   754         default:
   755             return containsType(s, t);
   756         }
   757     }
   759     boolean containsType(List<Type> ts, List<Type> ss) {
   760         while (ts.nonEmpty() && ss.nonEmpty()
   761                && containsType(ts.head, ss.head)) {
   762             ts = ts.tail;
   763             ss = ss.tail;
   764         }
   765         return ts.isEmpty() && ss.isEmpty();
   766     }
   768     /**
   769      * Check if t contains s.
   770      *
   771      * <p>T contains S if:
   772      *
   773      * <p>{@code L(T) <: L(S) && U(S) <: U(T)}
   774      *
   775      * <p>This relation is only used by ClassType.isSubtype(), that
   776      * is,
   777      *
   778      * <p>{@code C<S> <: C<T> if T contains S.}
   779      *
   780      * <p>Because of F-bounds, this relation can lead to infinite
   781      * recursion.  Thus we must somehow break that recursion.  Notice
   782      * that containsType() is only called from ClassType.isSubtype().
   783      * Since the arguments have already been checked against their
   784      * bounds, we know:
   785      *
   786      * <p>{@code U(S) <: U(T) if T is "super" bound (U(T) *is* the bound)}
   787      *
   788      * <p>{@code L(T) <: L(S) if T is "extends" bound (L(T) is bottom)}
   789      *
   790      * @param t a type
   791      * @param s a type
   792      */
   793     public boolean containsType(Type t, Type s) {
   794         return containsType.visit(t, s);
   795     }
   796     // where
   797         private TypeRelation containsType = new TypeRelation() {
   799             private Type U(Type t) {
   800                 while (t.tag == WILDCARD) {
   801                     WildcardType w = (WildcardType)t;
   802                     if (w.isSuperBound())
   803                         return w.bound == null ? syms.objectType : w.bound.bound;
   804                     else
   805                         t = w.type;
   806                 }
   807                 return t;
   808             }
   810             private Type L(Type t) {
   811                 while (t.tag == WILDCARD) {
   812                     WildcardType w = (WildcardType)t;
   813                     if (w.isExtendsBound())
   814                         return syms.botType;
   815                     else
   816                         t = w.type;
   817                 }
   818                 return t;
   819             }
   821             public Boolean visitType(Type t, Type s) {
   822                 if (s.tag >= firstPartialTag)
   823                     return containedBy(s, t);
   824                 else
   825                     return isSameType(t, s);
   826             }
   828             void debugContainsType(WildcardType t, Type s) {
   829                 System.err.println();
   830                 System.err.format(" does %s contain %s?%n", t, s);
   831                 System.err.format(" %s U(%s) <: U(%s) %s = %s%n",
   832                                   upperBound(s), s, t, U(t),
   833                                   t.isSuperBound()
   834                                   || isSubtypeNoCapture(upperBound(s), U(t)));
   835                 System.err.format(" %s L(%s) <: L(%s) %s = %s%n",
   836                                   L(t), t, s, lowerBound(s),
   837                                   t.isExtendsBound()
   838                                   || isSubtypeNoCapture(L(t), lowerBound(s)));
   839                 System.err.println();
   840             }
   842             @Override
   843             public Boolean visitWildcardType(WildcardType t, Type s) {
   844                 if (s.tag >= firstPartialTag)
   845                     return containedBy(s, t);
   846                 else {
   847                     // debugContainsType(t, s);
   848                     return isSameWildcard(t, s)
   849                         || isCaptureOf(s, t)
   850                         || ((t.isExtendsBound() || isSubtypeNoCapture(L(t), lowerBound(s))) &&
   851                             (t.isSuperBound() || isSubtypeNoCapture(upperBound(s), U(t))));
   852                 }
   853             }
   855             @Override
   856             public Boolean visitUndetVar(UndetVar t, Type s) {
   857                 if (s.tag != WILDCARD)
   858                     return isSameType(t, s);
   859                 else
   860                     return false;
   861             }
   863             @Override
   864             public Boolean visitErrorType(ErrorType t, Type s) {
   865                 return true;
   866             }
   867         };
   869     public boolean isCaptureOf(Type s, WildcardType t) {
   870         if (s.tag != TYPEVAR || !((TypeVar)s).isCaptured())
   871             return false;
   872         return isSameWildcard(t, ((CapturedType)s).wildcard);
   873     }
   875     public boolean isSameWildcard(WildcardType t, Type s) {
   876         if (s.tag != WILDCARD)
   877             return false;
   878         WildcardType w = (WildcardType)s;
   879         return w.kind == t.kind && w.type == t.type;
   880     }
   882     public boolean containsTypeEquivalent(List<Type> ts, List<Type> ss) {
   883         while (ts.nonEmpty() && ss.nonEmpty()
   884                && containsTypeEquivalent(ts.head, ss.head)) {
   885             ts = ts.tail;
   886             ss = ss.tail;
   887         }
   888         return ts.isEmpty() && ss.isEmpty();
   889     }
   890     // </editor-fold>
   892     // <editor-fold defaultstate="collapsed" desc="isCastable">
   893     public boolean isCastable(Type t, Type s) {
   894         return isCastable(t, s, Warner.noWarnings);
   895     }
   897     /**
   898      * Is t is castable to s?<br>
   899      * s is assumed to be an erased type.<br>
   900      * (not defined for Method and ForAll types).
   901      */
   902     public boolean isCastable(Type t, Type s, Warner warn) {
   903         if (t == s)
   904             return true;
   906         if (t.isPrimitive() != s.isPrimitive())
   907             return allowBoxing && isConvertible(t, s, warn);
   909         if (warn != warnStack.head) {
   910             try {
   911                 warnStack = warnStack.prepend(warn);
   912                 return isCastable.visit(t,s);
   913             } finally {
   914                 warnStack = warnStack.tail;
   915             }
   916         } else {
   917             return isCastable.visit(t,s);
   918         }
   919     }
   920     // where
   921         private TypeRelation isCastable = new TypeRelation() {
   923             public Boolean visitType(Type t, Type s) {
   924                 if (s.tag == ERROR)
   925                     return true;
   927                 switch (t.tag) {
   928                 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
   929                 case DOUBLE:
   930                     return s.tag <= DOUBLE;
   931                 case BOOLEAN:
   932                     return s.tag == BOOLEAN;
   933                 case VOID:
   934                     return false;
   935                 case BOT:
   936                     return isSubtype(t, s);
   937                 default:
   938                     throw new AssertionError();
   939                 }
   940             }
   942             @Override
   943             public Boolean visitWildcardType(WildcardType t, Type s) {
   944                 return isCastable(upperBound(t), s, warnStack.head);
   945             }
   947             @Override
   948             public Boolean visitClassType(ClassType t, Type s) {
   949                 if (s.tag == ERROR || s.tag == BOT)
   950                     return true;
   952                 if (s.tag == TYPEVAR) {
   953                     if (isCastable(s.getUpperBound(), t, Warner.noWarnings)) {
   954                         warnStack.head.warnUnchecked();
   955                         return true;
   956                     } else {
   957                         return false;
   958                     }
   959                 }
   961                 if (t.isCompound()) {
   962                     Warner oldWarner = warnStack.head;
   963                     warnStack.head = Warner.noWarnings;
   964                     if (!visit(supertype(t), s))
   965                         return false;
   966                     for (Type intf : interfaces(t)) {
   967                         if (!visit(intf, s))
   968                             return false;
   969                     }
   970                     if (warnStack.head.unchecked == true)
   971                         oldWarner.warnUnchecked();
   972                     return true;
   973                 }
   975                 if (s.isCompound()) {
   976                     // call recursively to reuse the above code
   977                     return visitClassType((ClassType)s, t);
   978                 }
   980                 if (s.tag == CLASS || s.tag == ARRAY) {
   981                     boolean upcast;
   982                     if ((upcast = isSubtype(erasure(t), erasure(s)))
   983                         || isSubtype(erasure(s), erasure(t))) {
   984                         if (!upcast && s.tag == ARRAY) {
   985                             if (!isReifiable(s))
   986                                 warnStack.head.warnUnchecked();
   987                             return true;
   988                         } else if (s.isRaw()) {
   989                             return true;
   990                         } else if (t.isRaw()) {
   991                             if (!isUnbounded(s))
   992                                 warnStack.head.warnUnchecked();
   993                             return true;
   994                         }
   995                         // Assume |a| <: |b|
   996                         final Type a = upcast ? t : s;
   997                         final Type b = upcast ? s : t;
   998                         final boolean HIGH = true;
   999                         final boolean LOW = false;
  1000                         final boolean DONT_REWRITE_TYPEVARS = false;
  1001                         Type aHigh = rewriteQuantifiers(a, HIGH, DONT_REWRITE_TYPEVARS);
  1002                         Type aLow  = rewriteQuantifiers(a, LOW,  DONT_REWRITE_TYPEVARS);
  1003                         Type bHigh = rewriteQuantifiers(b, HIGH, DONT_REWRITE_TYPEVARS);
  1004                         Type bLow  = rewriteQuantifiers(b, LOW,  DONT_REWRITE_TYPEVARS);
  1005                         Type lowSub = asSub(bLow, aLow.tsym);
  1006                         Type highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
  1007                         if (highSub == null) {
  1008                             final boolean REWRITE_TYPEVARS = true;
  1009                             aHigh = rewriteQuantifiers(a, HIGH, REWRITE_TYPEVARS);
  1010                             aLow  = rewriteQuantifiers(a, LOW,  REWRITE_TYPEVARS);
  1011                             bHigh = rewriteQuantifiers(b, HIGH, REWRITE_TYPEVARS);
  1012                             bLow  = rewriteQuantifiers(b, LOW,  REWRITE_TYPEVARS);
  1013                             lowSub = asSub(bLow, aLow.tsym);
  1014                             highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
  1016                         if (highSub != null) {
  1017                             assert a.tsym == highSub.tsym && a.tsym == lowSub.tsym
  1018                                 : a.tsym + " != " + highSub.tsym + " != " + lowSub.tsym;
  1019                             if (!disjointTypes(aHigh.allparams(), highSub.allparams())
  1020                                 && !disjointTypes(aHigh.allparams(), lowSub.allparams())
  1021                                 && !disjointTypes(aLow.allparams(), highSub.allparams())
  1022                                 && !disjointTypes(aLow.allparams(), lowSub.allparams())) {
  1023                                 if (upcast ? giveWarning(a, b) :
  1024                                     giveWarning(b, a))
  1025                                     warnStack.head.warnUnchecked();
  1026                                 return true;
  1029                         if (isReifiable(s))
  1030                             return isSubtypeUnchecked(a, b);
  1031                         else
  1032                             return isSubtypeUnchecked(a, b, warnStack.head);
  1035                     // Sidecast
  1036                     if (s.tag == CLASS) {
  1037                         if ((s.tsym.flags() & INTERFACE) != 0) {
  1038                             return ((t.tsym.flags() & FINAL) == 0)
  1039                                 ? sideCast(t, s, warnStack.head)
  1040                                 : sideCastFinal(t, s, warnStack.head);
  1041                         } else if ((t.tsym.flags() & INTERFACE) != 0) {
  1042                             return ((s.tsym.flags() & FINAL) == 0)
  1043                                 ? sideCast(t, s, warnStack.head)
  1044                                 : sideCastFinal(t, s, warnStack.head);
  1045                         } else {
  1046                             // unrelated class types
  1047                             return false;
  1051                 return false;
  1054             @Override
  1055             public Boolean visitArrayType(ArrayType t, Type s) {
  1056                 switch (s.tag) {
  1057                 case ERROR:
  1058                 case BOT:
  1059                     return true;
  1060                 case TYPEVAR:
  1061                     if (isCastable(s, t, Warner.noWarnings)) {
  1062                         warnStack.head.warnUnchecked();
  1063                         return true;
  1064                     } else {
  1065                         return false;
  1067                 case CLASS:
  1068                     return isSubtype(t, s);
  1069                 case ARRAY:
  1070                     if (elemtype(t).tag <= lastBaseTag) {
  1071                         return elemtype(t).tag == elemtype(s).tag;
  1072                     } else {
  1073                         return visit(elemtype(t), elemtype(s));
  1075                 default:
  1076                     return false;
  1080             @Override
  1081             public Boolean visitTypeVar(TypeVar t, Type s) {
  1082                 switch (s.tag) {
  1083                 case ERROR:
  1084                 case BOT:
  1085                     return true;
  1086                 case TYPEVAR:
  1087                     if (isSubtype(t, s)) {
  1088                         return true;
  1089                     } else if (isCastable(t.bound, s, Warner.noWarnings)) {
  1090                         warnStack.head.warnUnchecked();
  1091                         return true;
  1092                     } else {
  1093                         return false;
  1095                 default:
  1096                     return isCastable(t.bound, s, warnStack.head);
  1100             @Override
  1101             public Boolean visitErrorType(ErrorType t, Type s) {
  1102                 return true;
  1104         };
  1105     // </editor-fold>
  1107     // <editor-fold defaultstate="collapsed" desc="disjointTypes">
  1108     public boolean disjointTypes(List<Type> ts, List<Type> ss) {
  1109         while (ts.tail != null && ss.tail != null) {
  1110             if (disjointType(ts.head, ss.head)) return true;
  1111             ts = ts.tail;
  1112             ss = ss.tail;
  1114         return false;
  1117     /**
  1118      * Two types or wildcards are considered disjoint if it can be
  1119      * proven that no type can be contained in both. It is
  1120      * conservative in that it is allowed to say that two types are
  1121      * not disjoint, even though they actually are.
  1123      * The type C<X> is castable to C<Y> exactly if X and Y are not
  1124      * disjoint.
  1125      */
  1126     public boolean disjointType(Type t, Type s) {
  1127         return disjointType.visit(t, s);
  1129     // where
  1130         private TypeRelation disjointType = new TypeRelation() {
  1132             private Set<TypePair> cache = new HashSet<TypePair>();
  1134             public Boolean visitType(Type t, Type s) {
  1135                 if (s.tag == WILDCARD)
  1136                     return visit(s, t);
  1137                 else
  1138                     return notSoftSubtypeRecursive(t, s) || notSoftSubtypeRecursive(s, t);
  1141             private boolean isCastableRecursive(Type t, Type s) {
  1142                 TypePair pair = new TypePair(t, s);
  1143                 if (cache.add(pair)) {
  1144                     try {
  1145                         return Types.this.isCastable(t, s);
  1146                     } finally {
  1147                         cache.remove(pair);
  1149                 } else {
  1150                     return true;
  1154             private boolean notSoftSubtypeRecursive(Type t, Type s) {
  1155                 TypePair pair = new TypePair(t, s);
  1156                 if (cache.add(pair)) {
  1157                     try {
  1158                         return Types.this.notSoftSubtype(t, s);
  1159                     } finally {
  1160                         cache.remove(pair);
  1162                 } else {
  1163                     return false;
  1167             @Override
  1168             public Boolean visitWildcardType(WildcardType t, Type s) {
  1169                 if (t.isUnbound())
  1170                     return false;
  1172                 if (s.tag != WILDCARD) {
  1173                     if (t.isExtendsBound())
  1174                         return notSoftSubtypeRecursive(s, t.type);
  1175                     else // isSuperBound()
  1176                         return notSoftSubtypeRecursive(t.type, s);
  1179                 if (s.isUnbound())
  1180                     return false;
  1182                 if (t.isExtendsBound()) {
  1183                     if (s.isExtendsBound())
  1184                         return !isCastableRecursive(t.type, upperBound(s));
  1185                     else if (s.isSuperBound())
  1186                         return notSoftSubtypeRecursive(lowerBound(s), t.type);
  1187                 } else if (t.isSuperBound()) {
  1188                     if (s.isExtendsBound())
  1189                         return notSoftSubtypeRecursive(t.type, upperBound(s));
  1191                 return false;
  1193         };
  1194     // </editor-fold>
  1196     // <editor-fold defaultstate="collapsed" desc="lowerBoundArgtypes">
  1197     /**
  1198      * Returns the lower bounds of the formals of a method.
  1199      */
  1200     public List<Type> lowerBoundArgtypes(Type t) {
  1201         return map(t.getParameterTypes(), lowerBoundMapping);
  1203     private final Mapping lowerBoundMapping = new Mapping("lowerBound") {
  1204             public Type apply(Type t) {
  1205                 return lowerBound(t);
  1207         };
  1208     // </editor-fold>
  1210     // <editor-fold defaultstate="collapsed" desc="notSoftSubtype">
  1211     /**
  1212      * This relation answers the question: is impossible that
  1213      * something of type `t' can be a subtype of `s'? This is
  1214      * different from the question "is `t' not a subtype of `s'?"
  1215      * when type variables are involved: Integer is not a subtype of T
  1216      * where <T extends Number> but it is not true that Integer cannot
  1217      * possibly be a subtype of T.
  1218      */
  1219     public boolean notSoftSubtype(Type t, Type s) {
  1220         if (t == s) return false;
  1221         if (t.tag == TYPEVAR) {
  1222             TypeVar tv = (TypeVar) t;
  1223             if (s.tag == TYPEVAR)
  1224                 s = s.getUpperBound();
  1225             return !isCastable(tv.bound,
  1226                                s,
  1227                                Warner.noWarnings);
  1229         if (s.tag != WILDCARD)
  1230             s = upperBound(s);
  1231         if (s.tag == TYPEVAR)
  1232             s = s.getUpperBound();
  1234         return !isSubtype(t, s);
  1236     // </editor-fold>
  1238     // <editor-fold defaultstate="collapsed" desc="isReifiable">
  1239     public boolean isReifiable(Type t) {
  1240         return isReifiable.visit(t);
  1242     // where
  1243         private UnaryVisitor<Boolean> isReifiable = new UnaryVisitor<Boolean>() {
  1245             public Boolean visitType(Type t, Void ignored) {
  1246                 return true;
  1249             @Override
  1250             public Boolean visitClassType(ClassType t, Void ignored) {
  1251                 if (!t.isParameterized())
  1252                     return true;
  1254                 for (Type param : t.allparams()) {
  1255                     if (!param.isUnbound())
  1256                         return false;
  1258                 return true;
  1261             @Override
  1262             public Boolean visitArrayType(ArrayType t, Void ignored) {
  1263                 return visit(t.elemtype);
  1266             @Override
  1267             public Boolean visitTypeVar(TypeVar t, Void ignored) {
  1268                 return false;
  1270         };
  1271     // </editor-fold>
  1273     // <editor-fold defaultstate="collapsed" desc="Array Utils">
  1274     public boolean isArray(Type t) {
  1275         while (t.tag == WILDCARD)
  1276             t = upperBound(t);
  1277         return t.tag == ARRAY;
  1280     /**
  1281      * The element type of an array.
  1282      */
  1283     public Type elemtype(Type t) {
  1284         switch (t.tag) {
  1285         case WILDCARD:
  1286             return elemtype(upperBound(t));
  1287         case ARRAY:
  1288             return ((ArrayType)t).elemtype;
  1289         case FORALL:
  1290             return elemtype(((ForAll)t).qtype);
  1291         case ERROR:
  1292             return t;
  1293         default:
  1294             return null;
  1298     /**
  1299      * Mapping to take element type of an arraytype
  1300      */
  1301     private Mapping elemTypeFun = new Mapping ("elemTypeFun") {
  1302         public Type apply(Type t) { return elemtype(t); }
  1303     };
  1305     /**
  1306      * The number of dimensions of an array type.
  1307      */
  1308     public int dimensions(Type t) {
  1309         int result = 0;
  1310         while (t.tag == ARRAY) {
  1311             result++;
  1312             t = elemtype(t);
  1314         return result;
  1316     // </editor-fold>
  1318     // <editor-fold defaultstate="collapsed" desc="asSuper">
  1319     /**
  1320      * Return the (most specific) base type of t that starts with the
  1321      * given symbol.  If none exists, return null.
  1323      * @param t a type
  1324      * @param sym a symbol
  1325      */
  1326     public Type asSuper(Type t, Symbol sym) {
  1327         return asSuper.visit(t, sym);
  1329     // where
  1330         private SimpleVisitor<Type,Symbol> asSuper = new SimpleVisitor<Type,Symbol>() {
  1332             public Type visitType(Type t, Symbol sym) {
  1333                 return null;
  1336             @Override
  1337             public Type visitClassType(ClassType t, Symbol sym) {
  1338                 if (t.tsym == sym)
  1339                     return t;
  1341                 Type st = supertype(t);
  1342                 if (st.tag == CLASS || st.tag == TYPEVAR || st.tag == ERROR) {
  1343                     Type x = asSuper(st, sym);
  1344                     if (x != null)
  1345                         return x;
  1347                 if ((sym.flags() & INTERFACE) != 0) {
  1348                     for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
  1349                         Type x = asSuper(l.head, sym);
  1350                         if (x != null)
  1351                             return x;
  1354                 return null;
  1357             @Override
  1358             public Type visitArrayType(ArrayType t, Symbol sym) {
  1359                 return isSubtype(t, sym.type) ? sym.type : null;
  1362             @Override
  1363             public Type visitTypeVar(TypeVar t, Symbol sym) {
  1364                 if (t.tsym == sym)
  1365                     return t;
  1366                 else
  1367                     return asSuper(t.bound, sym);
  1370             @Override
  1371             public Type visitErrorType(ErrorType t, Symbol sym) {
  1372                 return t;
  1374         };
  1376     /**
  1377      * Return the base type of t or any of its outer types that starts
  1378      * with the given symbol.  If none exists, return null.
  1380      * @param t a type
  1381      * @param sym a symbol
  1382      */
  1383     public Type asOuterSuper(Type t, Symbol sym) {
  1384         switch (t.tag) {
  1385         case CLASS:
  1386             do {
  1387                 Type s = asSuper(t, sym);
  1388                 if (s != null) return s;
  1389                 t = t.getEnclosingType();
  1390             } while (t.tag == CLASS);
  1391             return null;
  1392         case ARRAY:
  1393             return isSubtype(t, sym.type) ? sym.type : null;
  1394         case TYPEVAR:
  1395             return asSuper(t, sym);
  1396         case ERROR:
  1397             return t;
  1398         default:
  1399             return null;
  1403     /**
  1404      * Return the base type of t or any of its enclosing types that
  1405      * starts with the given symbol.  If none exists, return null.
  1407      * @param t a type
  1408      * @param sym a symbol
  1409      */
  1410     public Type asEnclosingSuper(Type t, Symbol sym) {
  1411         switch (t.tag) {
  1412         case CLASS:
  1413             do {
  1414                 Type s = asSuper(t, sym);
  1415                 if (s != null) return s;
  1416                 Type outer = t.getEnclosingType();
  1417                 t = (outer.tag == CLASS) ? outer :
  1418                     (t.tsym.owner.enclClass() != null) ? t.tsym.owner.enclClass().type :
  1419                     Type.noType;
  1420             } while (t.tag == CLASS);
  1421             return null;
  1422         case ARRAY:
  1423             return isSubtype(t, sym.type) ? sym.type : null;
  1424         case TYPEVAR:
  1425             return asSuper(t, sym);
  1426         case ERROR:
  1427             return t;
  1428         default:
  1429             return null;
  1432     // </editor-fold>
  1434     // <editor-fold defaultstate="collapsed" desc="memberType">
  1435     /**
  1436      * The type of given symbol, seen as a member of t.
  1438      * @param t a type
  1439      * @param sym a symbol
  1440      */
  1441     public Type memberType(Type t, Symbol sym) {
  1442         return (sym.flags() & STATIC) != 0
  1443             ? sym.type
  1444             : memberType.visit(t, sym);
  1446     // where
  1447         private SimpleVisitor<Type,Symbol> memberType = new SimpleVisitor<Type,Symbol>() {
  1449             public Type visitType(Type t, Symbol sym) {
  1450                 return sym.type;
  1453             @Override
  1454             public Type visitWildcardType(WildcardType t, Symbol sym) {
  1455                 return memberType(upperBound(t), sym);
  1458             @Override
  1459             public Type visitClassType(ClassType t, Symbol sym) {
  1460                 Symbol owner = sym.owner;
  1461                 long flags = sym.flags();
  1462                 if (((flags & STATIC) == 0) && owner.type.isParameterized()) {
  1463                     Type base = asOuterSuper(t, owner);
  1464                     //if t is an intersection type T = CT & I1 & I2 ... & In
  1465                     //its supertypes CT, I1, ... In might contain wildcards
  1466                     //so we need to go through capture conversion
  1467                     base = t.isCompound() ? capture(base) : base;
  1468                     if (base != null) {
  1469                         List<Type> ownerParams = owner.type.allparams();
  1470                         List<Type> baseParams = base.allparams();
  1471                         if (ownerParams.nonEmpty()) {
  1472                             if (baseParams.isEmpty()) {
  1473                                 // then base is a raw type
  1474                                 return erasure(sym.type);
  1475                             } else {
  1476                                 return subst(sym.type, ownerParams, baseParams);
  1481                 return sym.type;
  1484             @Override
  1485             public Type visitTypeVar(TypeVar t, Symbol sym) {
  1486                 return memberType(t.bound, sym);
  1489             @Override
  1490             public Type visitErrorType(ErrorType t, Symbol sym) {
  1491                 return t;
  1493         };
  1494     // </editor-fold>
  1496     // <editor-fold defaultstate="collapsed" desc="isAssignable">
  1497     public boolean isAssignable(Type t, Type s) {
  1498         return isAssignable(t, s, Warner.noWarnings);
  1501     /**
  1502      * Is t assignable to s?<br>
  1503      * Equivalent to subtype except for constant values and raw
  1504      * types.<br>
  1505      * (not defined for Method and ForAll types)
  1506      */
  1507     public boolean isAssignable(Type t, Type s, Warner warn) {
  1508         if (t.tag == ERROR)
  1509             return true;
  1510         if (t.tag <= INT && t.constValue() != null) {
  1511             int value = ((Number)t.constValue()).intValue();
  1512             switch (s.tag) {
  1513             case BYTE:
  1514                 if (Byte.MIN_VALUE <= value && value <= Byte.MAX_VALUE)
  1515                     return true;
  1516                 break;
  1517             case CHAR:
  1518                 if (Character.MIN_VALUE <= value && value <= Character.MAX_VALUE)
  1519                     return true;
  1520                 break;
  1521             case SHORT:
  1522                 if (Short.MIN_VALUE <= value && value <= Short.MAX_VALUE)
  1523                     return true;
  1524                 break;
  1525             case INT:
  1526                 return true;
  1527             case CLASS:
  1528                 switch (unboxedType(s).tag) {
  1529                 case BYTE:
  1530                 case CHAR:
  1531                 case SHORT:
  1532                     return isAssignable(t, unboxedType(s), warn);
  1534                 break;
  1537         return isConvertible(t, s, warn);
  1539     // </editor-fold>
  1541     // <editor-fold defaultstate="collapsed" desc="erasure">
  1542     /**
  1543      * The erasure of t {@code |t|} -- the type that results when all
  1544      * type parameters in t are deleted.
  1545      */
  1546     public Type erasure(Type t) {
  1547         return erasure(t, false);
  1549     //where
  1550     private Type erasure(Type t, boolean recurse) {
  1551         if (t.tag <= lastBaseTag)
  1552             return t; /* fast special case */
  1553         else
  1554             return erasure.visit(t, recurse);
  1556     // where
  1557         private SimpleVisitor<Type, Boolean> erasure = new SimpleVisitor<Type, Boolean>() {
  1558             public Type visitType(Type t, Boolean recurse) {
  1559                 if (t.tag <= lastBaseTag)
  1560                     return t; /*fast special case*/
  1561                 else
  1562                     return t.map(recurse ? erasureRecFun : erasureFun);
  1565             @Override
  1566             public Type visitWildcardType(WildcardType t, Boolean recurse) {
  1567                 return erasure(upperBound(t), recurse);
  1570             @Override
  1571             public Type visitClassType(ClassType t, Boolean recurse) {
  1572                 Type erased = t.tsym.erasure(Types.this);
  1573                 if (recurse) {
  1574                     erased = new ErasedClassType(erased.getEnclosingType(),erased.tsym);
  1576                 return erased;
  1579             @Override
  1580             public Type visitTypeVar(TypeVar t, Boolean recurse) {
  1581                 return erasure(t.bound, recurse);
  1584             @Override
  1585             public Type visitErrorType(ErrorType t, Boolean recurse) {
  1586                 return t;
  1588         };
  1590     private Mapping erasureFun = new Mapping ("erasure") {
  1591             public Type apply(Type t) { return erasure(t); }
  1592         };
  1594     private Mapping erasureRecFun = new Mapping ("erasureRecursive") {
  1595         public Type apply(Type t) { return erasureRecursive(t); }
  1596     };
  1598     public List<Type> erasure(List<Type> ts) {
  1599         return Type.map(ts, erasureFun);
  1602     public Type erasureRecursive(Type t) {
  1603         return erasure(t, true);
  1606     public List<Type> erasureRecursive(List<Type> ts) {
  1607         return Type.map(ts, erasureRecFun);
  1609     // </editor-fold>
  1611     // <editor-fold defaultstate="collapsed" desc="makeCompoundType">
  1612     /**
  1613      * Make a compound type from non-empty list of types
  1615      * @param bounds            the types from which the compound type is formed
  1616      * @param supertype         is objectType if all bounds are interfaces,
  1617      *                          null otherwise.
  1618      */
  1619     public Type makeCompoundType(List<Type> bounds,
  1620                                  Type supertype) {
  1621         ClassSymbol bc =
  1622             new ClassSymbol(ABSTRACT|PUBLIC|SYNTHETIC|COMPOUND|ACYCLIC,
  1623                             Type.moreInfo
  1624                                 ? names.fromString(bounds.toString())
  1625                                 : names.empty,
  1626                             syms.noSymbol);
  1627         if (bounds.head.tag == TYPEVAR)
  1628             // error condition, recover
  1629                 bc.erasure_field = syms.objectType;
  1630             else
  1631                 bc.erasure_field = erasure(bounds.head);
  1632             bc.members_field = new Scope(bc);
  1633         ClassType bt = (ClassType)bc.type;
  1634         bt.allparams_field = List.nil();
  1635         if (supertype != null) {
  1636             bt.supertype_field = supertype;
  1637             bt.interfaces_field = bounds;
  1638         } else {
  1639             bt.supertype_field = bounds.head;
  1640             bt.interfaces_field = bounds.tail;
  1642         assert bt.supertype_field.tsym.completer != null
  1643             || !bt.supertype_field.isInterface()
  1644             : bt.supertype_field;
  1645         return bt;
  1648     /**
  1649      * Same as {@link #makeCompoundType(List,Type)}, except that the
  1650      * second parameter is computed directly. Note that this might
  1651      * cause a symbol completion.  Hence, this version of
  1652      * makeCompoundType may not be called during a classfile read.
  1653      */
  1654     public Type makeCompoundType(List<Type> bounds) {
  1655         Type supertype = (bounds.head.tsym.flags() & INTERFACE) != 0 ?
  1656             supertype(bounds.head) : null;
  1657         return makeCompoundType(bounds, supertype);
  1660     /**
  1661      * A convenience wrapper for {@link #makeCompoundType(List)}; the
  1662      * arguments are converted to a list and passed to the other
  1663      * method.  Note that this might cause a symbol completion.
  1664      * Hence, this version of makeCompoundType may not be called
  1665      * during a classfile read.
  1666      */
  1667     public Type makeCompoundType(Type bound1, Type bound2) {
  1668         return makeCompoundType(List.of(bound1, bound2));
  1670     // </editor-fold>
  1672     // <editor-fold defaultstate="collapsed" desc="supertype">
  1673     public Type supertype(Type t) {
  1674         return supertype.visit(t);
  1676     // where
  1677         private UnaryVisitor<Type> supertype = new UnaryVisitor<Type>() {
  1679             public Type visitType(Type t, Void ignored) {
  1680                 // A note on wildcards: there is no good way to
  1681                 // determine a supertype for a super bounded wildcard.
  1682                 return null;
  1685             @Override
  1686             public Type visitClassType(ClassType t, Void ignored) {
  1687                 if (t.supertype_field == null) {
  1688                     Type supertype = ((ClassSymbol)t.tsym).getSuperclass();
  1689                     // An interface has no superclass; its supertype is Object.
  1690                     if (t.isInterface())
  1691                         supertype = ((ClassType)t.tsym.type).supertype_field;
  1692                     if (t.supertype_field == null) {
  1693                         List<Type> actuals = classBound(t).allparams();
  1694                         List<Type> formals = t.tsym.type.allparams();
  1695                         if (t.hasErasedSupertypes()) {
  1696                             t.supertype_field = erasureRecursive(supertype);
  1697                         } else if (formals.nonEmpty()) {
  1698                             t.supertype_field = subst(supertype, formals, actuals);
  1700                         else {
  1701                             t.supertype_field = supertype;
  1705                 return t.supertype_field;
  1708             /**
  1709              * The supertype is always a class type. If the type
  1710              * variable's bounds start with a class type, this is also
  1711              * the supertype.  Otherwise, the supertype is
  1712              * java.lang.Object.
  1713              */
  1714             @Override
  1715             public Type visitTypeVar(TypeVar t, Void ignored) {
  1716                 if (t.bound.tag == TYPEVAR ||
  1717                     (!t.bound.isCompound() && !t.bound.isInterface())) {
  1718                     return t.bound;
  1719                 } else {
  1720                     return supertype(t.bound);
  1724             @Override
  1725             public Type visitArrayType(ArrayType t, Void ignored) {
  1726                 if (t.elemtype.isPrimitive() || isSameType(t.elemtype, syms.objectType))
  1727                     return arraySuperType();
  1728                 else
  1729                     return new ArrayType(supertype(t.elemtype), t.tsym);
  1732             @Override
  1733             public Type visitErrorType(ErrorType t, Void ignored) {
  1734                 return t;
  1736         };
  1737     // </editor-fold>
  1739     // <editor-fold defaultstate="collapsed" desc="interfaces">
  1740     /**
  1741      * Return the interfaces implemented by this class.
  1742      */
  1743     public List<Type> interfaces(Type t) {
  1744         return interfaces.visit(t);
  1746     // where
  1747         private UnaryVisitor<List<Type>> interfaces = new UnaryVisitor<List<Type>>() {
  1749             public List<Type> visitType(Type t, Void ignored) {
  1750                 return List.nil();
  1753             @Override
  1754             public List<Type> visitClassType(ClassType t, Void ignored) {
  1755                 if (t.interfaces_field == null) {
  1756                     List<Type> interfaces = ((ClassSymbol)t.tsym).getInterfaces();
  1757                     if (t.interfaces_field == null) {
  1758                         // If t.interfaces_field is null, then t must
  1759                         // be a parameterized type (not to be confused
  1760                         // with a generic type declaration).
  1761                         // Terminology:
  1762                         //    Parameterized type: List<String>
  1763                         //    Generic type declaration: class List<E> { ... }
  1764                         // So t corresponds to List<String> and
  1765                         // t.tsym.type corresponds to List<E>.
  1766                         // The reason t must be parameterized type is
  1767                         // that completion will happen as a side
  1768                         // effect of calling
  1769                         // ClassSymbol.getInterfaces.  Since
  1770                         // t.interfaces_field is null after
  1771                         // completion, we can assume that t is not the
  1772                         // type of a class/interface declaration.
  1773                         assert t != t.tsym.type : t.toString();
  1774                         List<Type> actuals = t.allparams();
  1775                         List<Type> formals = t.tsym.type.allparams();
  1776                         if (t.hasErasedSupertypes()) {
  1777                             t.interfaces_field = erasureRecursive(interfaces);
  1778                         } else if (formals.nonEmpty()) {
  1779                             t.interfaces_field =
  1780                                 upperBounds(subst(interfaces, formals, actuals));
  1782                         else {
  1783                             t.interfaces_field = interfaces;
  1787                 return t.interfaces_field;
  1790             @Override
  1791             public List<Type> visitTypeVar(TypeVar t, Void ignored) {
  1792                 if (t.bound.isCompound())
  1793                     return interfaces(t.bound);
  1795                 if (t.bound.isInterface())
  1796                     return List.of(t.bound);
  1798                 return List.nil();
  1800         };
  1801     // </editor-fold>
  1803     // <editor-fold defaultstate="collapsed" desc="isDerivedRaw">
  1804     Map<Type,Boolean> isDerivedRawCache = new HashMap<Type,Boolean>();
  1806     public boolean isDerivedRaw(Type t) {
  1807         Boolean result = isDerivedRawCache.get(t);
  1808         if (result == null) {
  1809             result = isDerivedRawInternal(t);
  1810             isDerivedRawCache.put(t, result);
  1812         return result;
  1815     public boolean isDerivedRawInternal(Type t) {
  1816         if (t.isErroneous())
  1817             return false;
  1818         return
  1819             t.isRaw() ||
  1820             supertype(t) != null && isDerivedRaw(supertype(t)) ||
  1821             isDerivedRaw(interfaces(t));
  1824     public boolean isDerivedRaw(List<Type> ts) {
  1825         List<Type> l = ts;
  1826         while (l.nonEmpty() && !isDerivedRaw(l.head)) l = l.tail;
  1827         return l.nonEmpty();
  1829     // </editor-fold>
  1831     // <editor-fold defaultstate="collapsed" desc="setBounds">
  1832     /**
  1833      * Set the bounds field of the given type variable to reflect a
  1834      * (possibly multiple) list of bounds.
  1835      * @param t                 a type variable
  1836      * @param bounds            the bounds, must be nonempty
  1837      * @param supertype         is objectType if all bounds are interfaces,
  1838      *                          null otherwise.
  1839      */
  1840     public void setBounds(TypeVar t, List<Type> bounds, Type supertype) {
  1841         if (bounds.tail.isEmpty())
  1842             t.bound = bounds.head;
  1843         else
  1844             t.bound = makeCompoundType(bounds, supertype);
  1845         t.rank_field = -1;
  1848     /**
  1849      * Same as {@link #setBounds(Type.TypeVar,List,Type)}, except that
  1850      * third parameter is computed directly.  Note that this test
  1851      * might cause a symbol completion.  Hence, this version of
  1852      * setBounds may not be called during a classfile read.
  1853      */
  1854     public void setBounds(TypeVar t, List<Type> bounds) {
  1855         Type supertype = (bounds.head.tsym.flags() & INTERFACE) != 0 ?
  1856             supertype(bounds.head) : null;
  1857         setBounds(t, bounds, supertype);
  1858         t.rank_field = -1;
  1860     // </editor-fold>
  1862     // <editor-fold defaultstate="collapsed" desc="getBounds">
  1863     /**
  1864      * Return list of bounds of the given type variable.
  1865      */
  1866     public List<Type> getBounds(TypeVar t) {
  1867         if (t.bound.isErroneous() || !t.bound.isCompound())
  1868             return List.of(t.bound);
  1869         else if ((erasure(t).tsym.flags() & INTERFACE) == 0)
  1870             return interfaces(t).prepend(supertype(t));
  1871         else
  1872             // No superclass was given in bounds.
  1873             // In this case, supertype is Object, erasure is first interface.
  1874             return interfaces(t);
  1876     // </editor-fold>
  1878     // <editor-fold defaultstate="collapsed" desc="classBound">
  1879     /**
  1880      * If the given type is a (possibly selected) type variable,
  1881      * return the bounding class of this type, otherwise return the
  1882      * type itself.
  1883      */
  1884     public Type classBound(Type t) {
  1885         return classBound.visit(t);
  1887     // where
  1888         private UnaryVisitor<Type> classBound = new UnaryVisitor<Type>() {
  1890             public Type visitType(Type t, Void ignored) {
  1891                 return t;
  1894             @Override
  1895             public Type visitClassType(ClassType t, Void ignored) {
  1896                 Type outer1 = classBound(t.getEnclosingType());
  1897                 if (outer1 != t.getEnclosingType())
  1898                     return new ClassType(outer1, t.getTypeArguments(), t.tsym);
  1899                 else
  1900                     return t;
  1903             @Override
  1904             public Type visitTypeVar(TypeVar t, Void ignored) {
  1905                 return classBound(supertype(t));
  1908             @Override
  1909             public Type visitErrorType(ErrorType t, Void ignored) {
  1910                 return t;
  1912         };
  1913     // </editor-fold>
  1915     // <editor-fold defaultstate="collapsed" desc="sub signature / override equivalence">
  1916     /**
  1917      * Returns true iff the first signature is a <em>sub
  1918      * signature</em> of the other.  This is <b>not</b> an equivalence
  1919      * relation.
  1921      * @see "The Java Language Specification, Third Ed. (8.4.2)."
  1922      * @see #overrideEquivalent(Type t, Type s)
  1923      * @param t first signature (possibly raw).
  1924      * @param s second signature (could be subjected to erasure).
  1925      * @return true if t is a sub signature of s.
  1926      */
  1927     public boolean isSubSignature(Type t, Type s) {
  1928         return hasSameArgs(t, s) || hasSameArgs(t, erasure(s));
  1931     /**
  1932      * Returns true iff these signatures are related by <em>override
  1933      * equivalence</em>.  This is the natural extension of
  1934      * isSubSignature to an equivalence relation.
  1936      * @see "The Java Language Specification, Third Ed. (8.4.2)."
  1937      * @see #isSubSignature(Type t, Type s)
  1938      * @param t a signature (possible raw, could be subjected to
  1939      * erasure).
  1940      * @param s a signature (possible raw, could be subjected to
  1941      * erasure).
  1942      * @return true if either argument is a sub signature of the other.
  1943      */
  1944     public boolean overrideEquivalent(Type t, Type s) {
  1945         return hasSameArgs(t, s) ||
  1946             hasSameArgs(t, erasure(s)) || hasSameArgs(erasure(t), s);
  1949     /**
  1950      * Does t have the same arguments as s?  It is assumed that both
  1951      * types are (possibly polymorphic) method types.  Monomorphic
  1952      * method types "have the same arguments", if their argument lists
  1953      * are equal.  Polymorphic method types "have the same arguments",
  1954      * if they have the same arguments after renaming all type
  1955      * variables of one to corresponding type variables in the other,
  1956      * where correspondence is by position in the type parameter list.
  1957      */
  1958     public boolean hasSameArgs(Type t, Type s) {
  1959         return hasSameArgs.visit(t, s);
  1961     // where
  1962         private TypeRelation hasSameArgs = new TypeRelation() {
  1964             public Boolean visitType(Type t, Type s) {
  1965                 throw new AssertionError();
  1968             @Override
  1969             public Boolean visitMethodType(MethodType t, Type s) {
  1970                 return s.tag == METHOD
  1971                     && containsTypeEquivalent(t.argtypes, s.getParameterTypes());
  1974             @Override
  1975             public Boolean visitForAll(ForAll t, Type s) {
  1976                 if (s.tag != FORALL)
  1977                     return false;
  1979                 ForAll forAll = (ForAll)s;
  1980                 return hasSameBounds(t, forAll)
  1981                     && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
  1984             @Override
  1985             public Boolean visitErrorType(ErrorType t, Type s) {
  1986                 return false;
  1988         };
  1989     // </editor-fold>
  1991     // <editor-fold defaultstate="collapsed" desc="subst">
  1992     public List<Type> subst(List<Type> ts,
  1993                             List<Type> from,
  1994                             List<Type> to) {
  1995         return new Subst(from, to).subst(ts);
  1998     /**
  1999      * Substitute all occurrences of a type in `from' with the
  2000      * corresponding type in `to' in 't'. Match lists `from' and `to'
  2001      * from the right: If lists have different length, discard leading
  2002      * elements of the longer list.
  2003      */
  2004     public Type subst(Type t, List<Type> from, List<Type> to) {
  2005         return new Subst(from, to).subst(t);
  2008     private class Subst extends UnaryVisitor<Type> {
  2009         List<Type> from;
  2010         List<Type> to;
  2012         public Subst(List<Type> from, List<Type> to) {
  2013             int fromLength = from.length();
  2014             int toLength = to.length();
  2015             while (fromLength > toLength) {
  2016                 fromLength--;
  2017                 from = from.tail;
  2019             while (fromLength < toLength) {
  2020                 toLength--;
  2021                 to = to.tail;
  2023             this.from = from;
  2024             this.to = to;
  2027         Type subst(Type t) {
  2028             if (from.tail == null)
  2029                 return t;
  2030             else
  2031                 return visit(t);
  2034         List<Type> subst(List<Type> ts) {
  2035             if (from.tail == null)
  2036                 return ts;
  2037             boolean wild = false;
  2038             if (ts.nonEmpty() && from.nonEmpty()) {
  2039                 Type head1 = subst(ts.head);
  2040                 List<Type> tail1 = subst(ts.tail);
  2041                 if (head1 != ts.head || tail1 != ts.tail)
  2042                     return tail1.prepend(head1);
  2044             return ts;
  2047         public Type visitType(Type t, Void ignored) {
  2048             return t;
  2051         @Override
  2052         public Type visitMethodType(MethodType t, Void ignored) {
  2053             List<Type> argtypes = subst(t.argtypes);
  2054             Type restype = subst(t.restype);
  2055             List<Type> thrown = subst(t.thrown);
  2056             if (argtypes == t.argtypes &&
  2057                 restype == t.restype &&
  2058                 thrown == t.thrown)
  2059                 return t;
  2060             else
  2061                 return new MethodType(argtypes, restype, thrown, t.tsym);
  2064         @Override
  2065         public Type visitTypeVar(TypeVar t, Void ignored) {
  2066             for (List<Type> from = this.from, to = this.to;
  2067                  from.nonEmpty();
  2068                  from = from.tail, to = to.tail) {
  2069                 if (t == from.head) {
  2070                     return to.head.withTypeVar(t);
  2073             return t;
  2076         @Override
  2077         public Type visitClassType(ClassType t, Void ignored) {
  2078             if (!t.isCompound()) {
  2079                 List<Type> typarams = t.getTypeArguments();
  2080                 List<Type> typarams1 = subst(typarams);
  2081                 Type outer = t.getEnclosingType();
  2082                 Type outer1 = subst(outer);
  2083                 if (typarams1 == typarams && outer1 == outer)
  2084                     return t;
  2085                 else
  2086                     return new ClassType(outer1, typarams1, t.tsym);
  2087             } else {
  2088                 Type st = subst(supertype(t));
  2089                 List<Type> is = upperBounds(subst(interfaces(t)));
  2090                 if (st == supertype(t) && is == interfaces(t))
  2091                     return t;
  2092                 else
  2093                     return makeCompoundType(is.prepend(st));
  2097         @Override
  2098         public Type visitWildcardType(WildcardType t, Void ignored) {
  2099             Type bound = t.type;
  2100             if (t.kind != BoundKind.UNBOUND)
  2101                 bound = subst(bound);
  2102             if (bound == t.type) {
  2103                 return t;
  2104             } else {
  2105                 if (t.isExtendsBound() && bound.isExtendsBound())
  2106                     bound = upperBound(bound);
  2107                 return new WildcardType(bound, t.kind, syms.boundClass, t.bound);
  2111         @Override
  2112         public Type visitArrayType(ArrayType t, Void ignored) {
  2113             Type elemtype = subst(t.elemtype);
  2114             if (elemtype == t.elemtype)
  2115                 return t;
  2116             else
  2117                 return new ArrayType(upperBound(elemtype), t.tsym);
  2120         @Override
  2121         public Type visitForAll(ForAll t, Void ignored) {
  2122             List<Type> tvars1 = substBounds(t.tvars, from, to);
  2123             Type qtype1 = subst(t.qtype);
  2124             if (tvars1 == t.tvars && qtype1 == t.qtype) {
  2125                 return t;
  2126             } else if (tvars1 == t.tvars) {
  2127                 return new ForAll(tvars1, qtype1);
  2128             } else {
  2129                 return new ForAll(tvars1, Types.this.subst(qtype1, t.tvars, tvars1));
  2133         @Override
  2134         public Type visitErrorType(ErrorType t, Void ignored) {
  2135             return t;
  2139     public List<Type> substBounds(List<Type> tvars,
  2140                                   List<Type> from,
  2141                                   List<Type> to) {
  2142         if (tvars.isEmpty())
  2143             return tvars;
  2144         ListBuffer<Type> newBoundsBuf = lb();
  2145         boolean changed = false;
  2146         // calculate new bounds
  2147         for (Type t : tvars) {
  2148             TypeVar tv = (TypeVar) t;
  2149             Type bound = subst(tv.bound, from, to);
  2150             if (bound != tv.bound)
  2151                 changed = true;
  2152             newBoundsBuf.append(bound);
  2154         if (!changed)
  2155             return tvars;
  2156         ListBuffer<Type> newTvars = lb();
  2157         // create new type variables without bounds
  2158         for (Type t : tvars) {
  2159             newTvars.append(new TypeVar(t.tsym, null, syms.botType));
  2161         // the new bounds should use the new type variables in place
  2162         // of the old
  2163         List<Type> newBounds = newBoundsBuf.toList();
  2164         from = tvars;
  2165         to = newTvars.toList();
  2166         for (; !newBounds.isEmpty(); newBounds = newBounds.tail) {
  2167             newBounds.head = subst(newBounds.head, from, to);
  2169         newBounds = newBoundsBuf.toList();
  2170         // set the bounds of new type variables to the new bounds
  2171         for (Type t : newTvars.toList()) {
  2172             TypeVar tv = (TypeVar) t;
  2173             tv.bound = newBounds.head;
  2174             newBounds = newBounds.tail;
  2176         return newTvars.toList();
  2179     public TypeVar substBound(TypeVar t, List<Type> from, List<Type> to) {
  2180         Type bound1 = subst(t.bound, from, to);
  2181         if (bound1 == t.bound)
  2182             return t;
  2183         else {
  2184             // create new type variable without bounds
  2185             TypeVar tv = new TypeVar(t.tsym, null, syms.botType);
  2186             // the new bound should use the new type variable in place
  2187             // of the old
  2188             tv.bound = subst(bound1, List.<Type>of(t), List.<Type>of(tv));
  2189             return tv;
  2192     // </editor-fold>
  2194     // <editor-fold defaultstate="collapsed" desc="hasSameBounds">
  2195     /**
  2196      * Does t have the same bounds for quantified variables as s?
  2197      */
  2198     boolean hasSameBounds(ForAll t, ForAll s) {
  2199         List<Type> l1 = t.tvars;
  2200         List<Type> l2 = s.tvars;
  2201         while (l1.nonEmpty() && l2.nonEmpty() &&
  2202                isSameType(l1.head.getUpperBound(),
  2203                           subst(l2.head.getUpperBound(),
  2204                                 s.tvars,
  2205                                 t.tvars))) {
  2206             l1 = l1.tail;
  2207             l2 = l2.tail;
  2209         return l1.isEmpty() && l2.isEmpty();
  2211     // </editor-fold>
  2213     // <editor-fold defaultstate="collapsed" desc="newInstances">
  2214     /** Create new vector of type variables from list of variables
  2215      *  changing all recursive bounds from old to new list.
  2216      */
  2217     public List<Type> newInstances(List<Type> tvars) {
  2218         List<Type> tvars1 = Type.map(tvars, newInstanceFun);
  2219         for (List<Type> l = tvars1; l.nonEmpty(); l = l.tail) {
  2220             TypeVar tv = (TypeVar) l.head;
  2221             tv.bound = subst(tv.bound, tvars, tvars1);
  2223         return tvars1;
  2225     static private Mapping newInstanceFun = new Mapping("newInstanceFun") {
  2226             public Type apply(Type t) { return new TypeVar(t.tsym, t.getUpperBound(), t.getLowerBound()); }
  2227         };
  2228     // </editor-fold>
  2230     // <editor-fold defaultstate="collapsed" desc="createErrorType">
  2231     public Type createErrorType(Type originalType) {
  2232         return new ErrorType(originalType, syms.errSymbol);
  2235     public Type createErrorType(ClassSymbol c, Type originalType) {
  2236         return new ErrorType(c, originalType);
  2239     public Type createErrorType(Name name, TypeSymbol container, Type originalType) {
  2240         return new ErrorType(name, container, originalType);
  2242     // </editor-fold>
  2244     // <editor-fold defaultstate="collapsed" desc="rank">
  2245     /**
  2246      * The rank of a class is the length of the longest path between
  2247      * the class and java.lang.Object in the class inheritance
  2248      * graph. Undefined for all but reference types.
  2249      */
  2250     public int rank(Type t) {
  2251         switch(t.tag) {
  2252         case CLASS: {
  2253             ClassType cls = (ClassType)t;
  2254             if (cls.rank_field < 0) {
  2255                 Name fullname = cls.tsym.getQualifiedName();
  2256                 if (fullname == names.java_lang_Object)
  2257                     cls.rank_field = 0;
  2258                 else {
  2259                     int r = rank(supertype(cls));
  2260                     for (List<Type> l = interfaces(cls);
  2261                          l.nonEmpty();
  2262                          l = l.tail) {
  2263                         if (rank(l.head) > r)
  2264                             r = rank(l.head);
  2266                     cls.rank_field = r + 1;
  2269             return cls.rank_field;
  2271         case TYPEVAR: {
  2272             TypeVar tvar = (TypeVar)t;
  2273             if (tvar.rank_field < 0) {
  2274                 int r = rank(supertype(tvar));
  2275                 for (List<Type> l = interfaces(tvar);
  2276                      l.nonEmpty();
  2277                      l = l.tail) {
  2278                     if (rank(l.head) > r) r = rank(l.head);
  2280                 tvar.rank_field = r + 1;
  2282             return tvar.rank_field;
  2284         case ERROR:
  2285             return 0;
  2286         default:
  2287             throw new AssertionError();
  2290     // </editor-fold>
  2292     /**
  2293      * Helper method for generating a string representation of a given type
  2294      * accordingly to a given locale
  2295      */
  2296     public String toString(Type t, Locale locale) {
  2297         return Printer.createStandardPrinter(messages).visit(t, locale);
  2300     /**
  2301      * Helper method for generating a string representation of a given type
  2302      * accordingly to a given locale
  2303      */
  2304     public String toString(Symbol t, Locale locale) {
  2305         return Printer.createStandardPrinter(messages).visit(t, locale);
  2308     // <editor-fold defaultstate="collapsed" desc="toString">
  2309     /**
  2310      * This toString is slightly more descriptive than the one on Type.
  2312      * @deprecated Types.toString(Type t, Locale l) provides better support
  2313      * for localization
  2314      */
  2315     @Deprecated
  2316     public String toString(Type t) {
  2317         if (t.tag == FORALL) {
  2318             ForAll forAll = (ForAll)t;
  2319             return typaramsString(forAll.tvars) + forAll.qtype;
  2321         return "" + t;
  2323     // where
  2324         private String typaramsString(List<Type> tvars) {
  2325             StringBuffer s = new StringBuffer();
  2326             s.append('<');
  2327             boolean first = true;
  2328             for (Type t : tvars) {
  2329                 if (!first) s.append(", ");
  2330                 first = false;
  2331                 appendTyparamString(((TypeVar)t), s);
  2333             s.append('>');
  2334             return s.toString();
  2336         private void appendTyparamString(TypeVar t, StringBuffer buf) {
  2337             buf.append(t);
  2338             if (t.bound == null ||
  2339                 t.bound.tsym.getQualifiedName() == names.java_lang_Object)
  2340                 return;
  2341             buf.append(" extends "); // Java syntax; no need for i18n
  2342             Type bound = t.bound;
  2343             if (!bound.isCompound()) {
  2344                 buf.append(bound);
  2345             } else if ((erasure(t).tsym.flags() & INTERFACE) == 0) {
  2346                 buf.append(supertype(t));
  2347                 for (Type intf : interfaces(t)) {
  2348                     buf.append('&');
  2349                     buf.append(intf);
  2351             } else {
  2352                 // No superclass was given in bounds.
  2353                 // In this case, supertype is Object, erasure is first interface.
  2354                 boolean first = true;
  2355                 for (Type intf : interfaces(t)) {
  2356                     if (!first) buf.append('&');
  2357                     first = false;
  2358                     buf.append(intf);
  2362     // </editor-fold>
  2364     // <editor-fold defaultstate="collapsed" desc="Determining least upper bounds of types">
  2365     /**
  2366      * A cache for closures.
  2368      * <p>A closure is a list of all the supertypes and interfaces of
  2369      * a class or interface type, ordered by ClassSymbol.precedes
  2370      * (that is, subclasses come first, arbitrary but fixed
  2371      * otherwise).
  2372      */
  2373     private Map<Type,List<Type>> closureCache = new HashMap<Type,List<Type>>();
  2375     /**
  2376      * Returns the closure of a class or interface type.
  2377      */
  2378     public List<Type> closure(Type t) {
  2379         List<Type> cl = closureCache.get(t);
  2380         if (cl == null) {
  2381             Type st = supertype(t);
  2382             if (!t.isCompound()) {
  2383                 if (st.tag == CLASS) {
  2384                     cl = insert(closure(st), t);
  2385                 } else if (st.tag == TYPEVAR) {
  2386                     cl = closure(st).prepend(t);
  2387                 } else {
  2388                     cl = List.of(t);
  2390             } else {
  2391                 cl = closure(supertype(t));
  2393             for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail)
  2394                 cl = union(cl, closure(l.head));
  2395             closureCache.put(t, cl);
  2397         return cl;
  2400     /**
  2401      * Insert a type in a closure
  2402      */
  2403     public List<Type> insert(List<Type> cl, Type t) {
  2404         if (cl.isEmpty() || t.tsym.precedes(cl.head.tsym, this)) {
  2405             return cl.prepend(t);
  2406         } else if (cl.head.tsym.precedes(t.tsym, this)) {
  2407             return insert(cl.tail, t).prepend(cl.head);
  2408         } else {
  2409             return cl;
  2413     /**
  2414      * Form the union of two closures
  2415      */
  2416     public List<Type> union(List<Type> cl1, List<Type> cl2) {
  2417         if (cl1.isEmpty()) {
  2418             return cl2;
  2419         } else if (cl2.isEmpty()) {
  2420             return cl1;
  2421         } else if (cl1.head.tsym.precedes(cl2.head.tsym, this)) {
  2422             return union(cl1.tail, cl2).prepend(cl1.head);
  2423         } else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) {
  2424             return union(cl1, cl2.tail).prepend(cl2.head);
  2425         } else {
  2426             return union(cl1.tail, cl2.tail).prepend(cl1.head);
  2430     /**
  2431      * Intersect two closures
  2432      */
  2433     public List<Type> intersect(List<Type> cl1, List<Type> cl2) {
  2434         if (cl1 == cl2)
  2435             return cl1;
  2436         if (cl1.isEmpty() || cl2.isEmpty())
  2437             return List.nil();
  2438         if (cl1.head.tsym.precedes(cl2.head.tsym, this))
  2439             return intersect(cl1.tail, cl2);
  2440         if (cl2.head.tsym.precedes(cl1.head.tsym, this))
  2441             return intersect(cl1, cl2.tail);
  2442         if (isSameType(cl1.head, cl2.head))
  2443             return intersect(cl1.tail, cl2.tail).prepend(cl1.head);
  2444         if (cl1.head.tsym == cl2.head.tsym &&
  2445             cl1.head.tag == CLASS && cl2.head.tag == CLASS) {
  2446             if (cl1.head.isParameterized() && cl2.head.isParameterized()) {
  2447                 Type merge = merge(cl1.head,cl2.head);
  2448                 return intersect(cl1.tail, cl2.tail).prepend(merge);
  2450             if (cl1.head.isRaw() || cl2.head.isRaw())
  2451                 return intersect(cl1.tail, cl2.tail).prepend(erasure(cl1.head));
  2453         return intersect(cl1.tail, cl2.tail);
  2455     // where
  2456         class TypePair {
  2457             final Type t1;
  2458             final Type t2;
  2459             TypePair(Type t1, Type t2) {
  2460                 this.t1 = t1;
  2461                 this.t2 = t2;
  2463             @Override
  2464             public int hashCode() {
  2465                 return 127 * Types.this.hashCode(t1) + Types.this.hashCode(t2);
  2467             @Override
  2468             public boolean equals(Object obj) {
  2469                 if (!(obj instanceof TypePair))
  2470                     return false;
  2471                 TypePair typePair = (TypePair)obj;
  2472                 return isSameType(t1, typePair.t1)
  2473                     && isSameType(t2, typePair.t2);
  2476         Set<TypePair> mergeCache = new HashSet<TypePair>();
  2477         private Type merge(Type c1, Type c2) {
  2478             ClassType class1 = (ClassType) c1;
  2479             List<Type> act1 = class1.getTypeArguments();
  2480             ClassType class2 = (ClassType) c2;
  2481             List<Type> act2 = class2.getTypeArguments();
  2482             ListBuffer<Type> merged = new ListBuffer<Type>();
  2483             List<Type> typarams = class1.tsym.type.getTypeArguments();
  2485             while (act1.nonEmpty() && act2.nonEmpty() && typarams.nonEmpty()) {
  2486                 if (containsType(act1.head, act2.head)) {
  2487                     merged.append(act1.head);
  2488                 } else if (containsType(act2.head, act1.head)) {
  2489                     merged.append(act2.head);
  2490                 } else {
  2491                     TypePair pair = new TypePair(c1, c2);
  2492                     Type m;
  2493                     if (mergeCache.add(pair)) {
  2494                         m = new WildcardType(lub(upperBound(act1.head),
  2495                                                  upperBound(act2.head)),
  2496                                              BoundKind.EXTENDS,
  2497                                              syms.boundClass);
  2498                         mergeCache.remove(pair);
  2499                     } else {
  2500                         m = new WildcardType(syms.objectType,
  2501                                              BoundKind.UNBOUND,
  2502                                              syms.boundClass);
  2504                     merged.append(m.withTypeVar(typarams.head));
  2506                 act1 = act1.tail;
  2507                 act2 = act2.tail;
  2508                 typarams = typarams.tail;
  2510             assert(act1.isEmpty() && act2.isEmpty() && typarams.isEmpty());
  2511             return new ClassType(class1.getEnclosingType(), merged.toList(), class1.tsym);
  2514     /**
  2515      * Return the minimum type of a closure, a compound type if no
  2516      * unique minimum exists.
  2517      */
  2518     private Type compoundMin(List<Type> cl) {
  2519         if (cl.isEmpty()) return syms.objectType;
  2520         List<Type> compound = closureMin(cl);
  2521         if (compound.isEmpty())
  2522             return null;
  2523         else if (compound.tail.isEmpty())
  2524             return compound.head;
  2525         else
  2526             return makeCompoundType(compound);
  2529     /**
  2530      * Return the minimum types of a closure, suitable for computing
  2531      * compoundMin or glb.
  2532      */
  2533     private List<Type> closureMin(List<Type> cl) {
  2534         ListBuffer<Type> classes = lb();
  2535         ListBuffer<Type> interfaces = lb();
  2536         while (!cl.isEmpty()) {
  2537             Type current = cl.head;
  2538             if (current.isInterface())
  2539                 interfaces.append(current);
  2540             else
  2541                 classes.append(current);
  2542             ListBuffer<Type> candidates = lb();
  2543             for (Type t : cl.tail) {
  2544                 if (!isSubtypeNoCapture(current, t))
  2545                     candidates.append(t);
  2547             cl = candidates.toList();
  2549         return classes.appendList(interfaces).toList();
  2552     /**
  2553      * Return the least upper bound of pair of types.  if the lub does
  2554      * not exist return null.
  2555      */
  2556     public Type lub(Type t1, Type t2) {
  2557         return lub(List.of(t1, t2));
  2560     /**
  2561      * Return the least upper bound (lub) of set of types.  If the lub
  2562      * does not exist return the type of null (bottom).
  2563      */
  2564     public Type lub(List<Type> ts) {
  2565         final int ARRAY_BOUND = 1;
  2566         final int CLASS_BOUND = 2;
  2567         int boundkind = 0;
  2568         for (Type t : ts) {
  2569             switch (t.tag) {
  2570             case CLASS:
  2571                 boundkind |= CLASS_BOUND;
  2572                 break;
  2573             case ARRAY:
  2574                 boundkind |= ARRAY_BOUND;
  2575                 break;
  2576             case  TYPEVAR:
  2577                 do {
  2578                     t = t.getUpperBound();
  2579                 } while (t.tag == TYPEVAR);
  2580                 if (t.tag == ARRAY) {
  2581                     boundkind |= ARRAY_BOUND;
  2582                 } else {
  2583                     boundkind |= CLASS_BOUND;
  2585                 break;
  2586             default:
  2587                 if (t.isPrimitive())
  2588                     return syms.errType;
  2591         switch (boundkind) {
  2592         case 0:
  2593             return syms.botType;
  2595         case ARRAY_BOUND:
  2596             // calculate lub(A[], B[])
  2597             List<Type> elements = Type.map(ts, elemTypeFun);
  2598             for (Type t : elements) {
  2599                 if (t.isPrimitive()) {
  2600                     // if a primitive type is found, then return
  2601                     // arraySuperType unless all the types are the
  2602                     // same
  2603                     Type first = ts.head;
  2604                     for (Type s : ts.tail) {
  2605                         if (!isSameType(first, s)) {
  2606                              // lub(int[], B[]) is Cloneable & Serializable
  2607                             return arraySuperType();
  2610                     // all the array types are the same, return one
  2611                     // lub(int[], int[]) is int[]
  2612                     return first;
  2615             // lub(A[], B[]) is lub(A, B)[]
  2616             return new ArrayType(lub(elements), syms.arrayClass);
  2618         case CLASS_BOUND:
  2619             // calculate lub(A, B)
  2620             while (ts.head.tag != CLASS && ts.head.tag != TYPEVAR)
  2621                 ts = ts.tail;
  2622             assert !ts.isEmpty();
  2623             List<Type> cl = closure(ts.head);
  2624             for (Type t : ts.tail) {
  2625                 if (t.tag == CLASS || t.tag == TYPEVAR)
  2626                     cl = intersect(cl, closure(t));
  2628             return compoundMin(cl);
  2630         default:
  2631             // calculate lub(A, B[])
  2632             List<Type> classes = List.of(arraySuperType());
  2633             for (Type t : ts) {
  2634                 if (t.tag != ARRAY) // Filter out any arrays
  2635                     classes = classes.prepend(t);
  2637             // lub(A, B[]) is lub(A, arraySuperType)
  2638             return lub(classes);
  2641     // where
  2642         private Type arraySuperType = null;
  2643         private Type arraySuperType() {
  2644             // initialized lazily to avoid problems during compiler startup
  2645             if (arraySuperType == null) {
  2646                 synchronized (this) {
  2647                     if (arraySuperType == null) {
  2648                         // JLS 10.8: all arrays implement Cloneable and Serializable.
  2649                         arraySuperType = makeCompoundType(List.of(syms.serializableType,
  2650                                                                   syms.cloneableType),
  2651                                                           syms.objectType);
  2655             return arraySuperType;
  2657     // </editor-fold>
  2659     // <editor-fold defaultstate="collapsed" desc="Greatest lower bound">
  2660     public Type glb(List<Type> ts) {
  2661         Type t1 = ts.head;
  2662         for (Type t2 : ts.tail) {
  2663             if (t1.isErroneous())
  2664                 return t1;
  2665             t1 = glb(t1, t2);
  2667         return t1;
  2669     //where
  2670     public Type glb(Type t, Type s) {
  2671         if (s == null)
  2672             return t;
  2673         else if (isSubtypeNoCapture(t, s))
  2674             return t;
  2675         else if (isSubtypeNoCapture(s, t))
  2676             return s;
  2678         List<Type> closure = union(closure(t), closure(s));
  2679         List<Type> bounds = closureMin(closure);
  2681         if (bounds.isEmpty()) {             // length == 0
  2682             return syms.objectType;
  2683         } else if (bounds.tail.isEmpty()) { // length == 1
  2684             return bounds.head;
  2685         } else {                            // length > 1
  2686             int classCount = 0;
  2687             for (Type bound : bounds)
  2688                 if (!bound.isInterface())
  2689                     classCount++;
  2690             if (classCount > 1)
  2691                 return createErrorType(t);
  2693         return makeCompoundType(bounds);
  2695     // </editor-fold>
  2697     // <editor-fold defaultstate="collapsed" desc="hashCode">
  2698     /**
  2699      * Compute a hash code on a type.
  2700      */
  2701     public static int hashCode(Type t) {
  2702         return hashCode.visit(t);
  2704     // where
  2705         private static final UnaryVisitor<Integer> hashCode = new UnaryVisitor<Integer>() {
  2707             public Integer visitType(Type t, Void ignored) {
  2708                 return t.tag;
  2711             @Override
  2712             public Integer visitClassType(ClassType t, Void ignored) {
  2713                 int result = visit(t.getEnclosingType());
  2714                 result *= 127;
  2715                 result += t.tsym.flatName().hashCode();
  2716                 for (Type s : t.getTypeArguments()) {
  2717                     result *= 127;
  2718                     result += visit(s);
  2720                 return result;
  2723             @Override
  2724             public Integer visitWildcardType(WildcardType t, Void ignored) {
  2725                 int result = t.kind.hashCode();
  2726                 if (t.type != null) {
  2727                     result *= 127;
  2728                     result += visit(t.type);
  2730                 return result;
  2733             @Override
  2734             public Integer visitArrayType(ArrayType t, Void ignored) {
  2735                 return visit(t.elemtype) + 12;
  2738             @Override
  2739             public Integer visitTypeVar(TypeVar t, Void ignored) {
  2740                 return System.identityHashCode(t.tsym);
  2743             @Override
  2744             public Integer visitUndetVar(UndetVar t, Void ignored) {
  2745                 return System.identityHashCode(t);
  2748             @Override
  2749             public Integer visitErrorType(ErrorType t, Void ignored) {
  2750                 return 0;
  2752         };
  2753     // </editor-fold>
  2755     // <editor-fold defaultstate="collapsed" desc="Return-Type-Substitutable">
  2756     /**
  2757      * Does t have a result that is a subtype of the result type of s,
  2758      * suitable for covariant returns?  It is assumed that both types
  2759      * are (possibly polymorphic) method types.  Monomorphic method
  2760      * types are handled in the obvious way.  Polymorphic method types
  2761      * require renaming all type variables of one to corresponding
  2762      * type variables in the other, where correspondence is by
  2763      * position in the type parameter list. */
  2764     public boolean resultSubtype(Type t, Type s, Warner warner) {
  2765         List<Type> tvars = t.getTypeArguments();
  2766         List<Type> svars = s.getTypeArguments();
  2767         Type tres = t.getReturnType();
  2768         Type sres = subst(s.getReturnType(), svars, tvars);
  2769         return covariantReturnType(tres, sres, warner);
  2772     /**
  2773      * Return-Type-Substitutable.
  2774      * @see <a href="http://java.sun.com/docs/books/jls/">The Java
  2775      * Language Specification, Third Ed. (8.4.5)</a>
  2776      */
  2777     public boolean returnTypeSubstitutable(Type r1, Type r2) {
  2778         if (hasSameArgs(r1, r2))
  2779             return resultSubtype(r1, r2, Warner.noWarnings);
  2780         else
  2781             return covariantReturnType(r1.getReturnType(),
  2782                                        erasure(r2.getReturnType()),
  2783                                        Warner.noWarnings);
  2786     public boolean returnTypeSubstitutable(Type r1,
  2787                                            Type r2, Type r2res,
  2788                                            Warner warner) {
  2789         if (isSameType(r1.getReturnType(), r2res))
  2790             return true;
  2791         if (r1.getReturnType().isPrimitive() || r2res.isPrimitive())
  2792             return false;
  2794         if (hasSameArgs(r1, r2))
  2795             return covariantReturnType(r1.getReturnType(), r2res, warner);
  2796         if (!source.allowCovariantReturns())
  2797             return false;
  2798         if (isSubtypeUnchecked(r1.getReturnType(), r2res, warner))
  2799             return true;
  2800         if (!isSubtype(r1.getReturnType(), erasure(r2res)))
  2801             return false;
  2802         warner.warnUnchecked();
  2803         return true;
  2806     /**
  2807      * Is t an appropriate return type in an overrider for a
  2808      * method that returns s?
  2809      */
  2810     public boolean covariantReturnType(Type t, Type s, Warner warner) {
  2811         return
  2812             isSameType(t, s) ||
  2813             source.allowCovariantReturns() &&
  2814             !t.isPrimitive() &&
  2815             !s.isPrimitive() &&
  2816             isAssignable(t, s, warner);
  2818     // </editor-fold>
  2820     // <editor-fold defaultstate="collapsed" desc="Box/unbox support">
  2821     /**
  2822      * Return the class that boxes the given primitive.
  2823      */
  2824     public ClassSymbol boxedClass(Type t) {
  2825         return reader.enterClass(syms.boxedName[t.tag]);
  2828     /**
  2829      * Return the primitive type corresponding to a boxed type.
  2830      */
  2831     public Type unboxedType(Type t) {
  2832         if (allowBoxing) {
  2833             for (int i=0; i<syms.boxedName.length; i++) {
  2834                 Name box = syms.boxedName[i];
  2835                 if (box != null &&
  2836                     asSuper(t, reader.enterClass(box)) != null)
  2837                     return syms.typeOfTag[i];
  2840         return Type.noType;
  2842     // </editor-fold>
  2844     // <editor-fold defaultstate="collapsed" desc="Capture conversion">
  2845     /*
  2846      * JLS 3rd Ed. 5.1.10 Capture Conversion:
  2848      * Let G name a generic type declaration with n formal type
  2849      * parameters A1 ... An with corresponding bounds U1 ... Un. There
  2850      * exists a capture conversion from G<T1 ... Tn> to G<S1 ... Sn>,
  2851      * where, for 1 <= i <= n:
  2853      * + If Ti is a wildcard type argument (4.5.1) of the form ? then
  2854      *   Si is a fresh type variable whose upper bound is
  2855      *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is the null
  2856      *   type.
  2858      * + If Ti is a wildcard type argument of the form ? extends Bi,
  2859      *   then Si is a fresh type variable whose upper bound is
  2860      *   glb(Bi, Ui[A1 := S1, ..., An := Sn]) and whose lower bound is
  2861      *   the null type, where glb(V1,... ,Vm) is V1 & ... & Vm. It is
  2862      *   a compile-time error if for any two classes (not interfaces)
  2863      *   Vi and Vj,Vi is not a subclass of Vj or vice versa.
  2865      * + If Ti is a wildcard type argument of the form ? super Bi,
  2866      *   then Si is a fresh type variable whose upper bound is
  2867      *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is Bi.
  2869      * + Otherwise, Si = Ti.
  2871      * Capture conversion on any type other than a parameterized type
  2872      * (4.5) acts as an identity conversion (5.1.1). Capture
  2873      * conversions never require a special action at run time and
  2874      * therefore never throw an exception at run time.
  2876      * Capture conversion is not applied recursively.
  2877      */
  2878     /**
  2879      * Capture conversion as specified by JLS 3rd Ed.
  2880      */
  2882     public List<Type> capture(List<Type> ts) {
  2883         List<Type> buf = List.nil();
  2884         for (Type t : ts) {
  2885             buf = buf.prepend(capture(t));
  2887         return buf.reverse();
  2889     public Type capture(Type t) {
  2890         if (t.tag != CLASS)
  2891             return t;
  2892         ClassType cls = (ClassType)t;
  2893         if (cls.isRaw() || !cls.isParameterized())
  2894             return cls;
  2896         ClassType G = (ClassType)cls.asElement().asType();
  2897         List<Type> A = G.getTypeArguments();
  2898         List<Type> T = cls.getTypeArguments();
  2899         List<Type> S = freshTypeVariables(T);
  2901         List<Type> currentA = A;
  2902         List<Type> currentT = T;
  2903         List<Type> currentS = S;
  2904         boolean captured = false;
  2905         while (!currentA.isEmpty() &&
  2906                !currentT.isEmpty() &&
  2907                !currentS.isEmpty()) {
  2908             if (currentS.head != currentT.head) {
  2909                 captured = true;
  2910                 WildcardType Ti = (WildcardType)currentT.head;
  2911                 Type Ui = currentA.head.getUpperBound();
  2912                 CapturedType Si = (CapturedType)currentS.head;
  2913                 if (Ui == null)
  2914                     Ui = syms.objectType;
  2915                 switch (Ti.kind) {
  2916                 case UNBOUND:
  2917                     Si.bound = subst(Ui, A, S);
  2918                     Si.lower = syms.botType;
  2919                     break;
  2920                 case EXTENDS:
  2921                     Si.bound = glb(Ti.getExtendsBound(), subst(Ui, A, S));
  2922                     Si.lower = syms.botType;
  2923                     break;
  2924                 case SUPER:
  2925                     Si.bound = subst(Ui, A, S);
  2926                     Si.lower = Ti.getSuperBound();
  2927                     break;
  2929                 if (Si.bound == Si.lower)
  2930                     currentS.head = Si.bound;
  2932             currentA = currentA.tail;
  2933             currentT = currentT.tail;
  2934             currentS = currentS.tail;
  2936         if (!currentA.isEmpty() || !currentT.isEmpty() || !currentS.isEmpty())
  2937             return erasure(t); // some "rare" type involved
  2939         if (captured)
  2940             return new ClassType(cls.getEnclosingType(), S, cls.tsym);
  2941         else
  2942             return t;
  2944     // where
  2945         public List<Type> freshTypeVariables(List<Type> types) {
  2946             ListBuffer<Type> result = lb();
  2947             for (Type t : types) {
  2948                 if (t.tag == WILDCARD) {
  2949                     Type bound = ((WildcardType)t).getExtendsBound();
  2950                     if (bound == null)
  2951                         bound = syms.objectType;
  2952                     result.append(new CapturedType(capturedName,
  2953                                                    syms.noSymbol,
  2954                                                    bound,
  2955                                                    syms.botType,
  2956                                                    (WildcardType)t));
  2957                 } else {
  2958                     result.append(t);
  2961             return result.toList();
  2963     // </editor-fold>
  2965     // <editor-fold defaultstate="collapsed" desc="Internal utility methods">
  2966     private List<Type> upperBounds(List<Type> ss) {
  2967         if (ss.isEmpty()) return ss;
  2968         Type head = upperBound(ss.head);
  2969         List<Type> tail = upperBounds(ss.tail);
  2970         if (head != ss.head || tail != ss.tail)
  2971             return tail.prepend(head);
  2972         else
  2973             return ss;
  2976     private boolean sideCast(Type from, Type to, Warner warn) {
  2977         // We are casting from type $from$ to type $to$, which are
  2978         // non-final unrelated types.  This method
  2979         // tries to reject a cast by transferring type parameters
  2980         // from $to$ to $from$ by common superinterfaces.
  2981         boolean reverse = false;
  2982         Type target = to;
  2983         if ((to.tsym.flags() & INTERFACE) == 0) {
  2984             assert (from.tsym.flags() & INTERFACE) != 0;
  2985             reverse = true;
  2986             to = from;
  2987             from = target;
  2989         List<Type> commonSupers = superClosure(to, erasure(from));
  2990         boolean giveWarning = commonSupers.isEmpty();
  2991         // The arguments to the supers could be unified here to
  2992         // get a more accurate analysis
  2993         while (commonSupers.nonEmpty()) {
  2994             Type t1 = asSuper(from, commonSupers.head.tsym);
  2995             Type t2 = commonSupers.head; // same as asSuper(to, commonSupers.head.tsym);
  2996             if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
  2997                 return false;
  2998             giveWarning = giveWarning || (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2));
  2999             commonSupers = commonSupers.tail;
  3001         if (giveWarning && !isReifiable(reverse ? from : to))
  3002             warn.warnUnchecked();
  3003         if (!source.allowCovariantReturns())
  3004             // reject if there is a common method signature with
  3005             // incompatible return types.
  3006             chk.checkCompatibleAbstracts(warn.pos(), from, to);
  3007         return true;
  3010     private boolean sideCastFinal(Type from, Type to, Warner warn) {
  3011         // We are casting from type $from$ to type $to$, which are
  3012         // unrelated types one of which is final and the other of
  3013         // which is an interface.  This method
  3014         // tries to reject a cast by transferring type parameters
  3015         // from the final class to the interface.
  3016         boolean reverse = false;
  3017         Type target = to;
  3018         if ((to.tsym.flags() & INTERFACE) == 0) {
  3019             assert (from.tsym.flags() & INTERFACE) != 0;
  3020             reverse = true;
  3021             to = from;
  3022             from = target;
  3024         assert (from.tsym.flags() & FINAL) != 0;
  3025         Type t1 = asSuper(from, to.tsym);
  3026         if (t1 == null) return false;
  3027         Type t2 = to;
  3028         if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
  3029             return false;
  3030         if (!source.allowCovariantReturns())
  3031             // reject if there is a common method signature with
  3032             // incompatible return types.
  3033             chk.checkCompatibleAbstracts(warn.pos(), from, to);
  3034         if (!isReifiable(target) &&
  3035             (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2)))
  3036             warn.warnUnchecked();
  3037         return true;
  3040     private boolean giveWarning(Type from, Type to) {
  3041         Type subFrom = asSub(from, to.tsym);
  3042         return to.isParameterized() &&
  3043                 (!(isUnbounded(to) ||
  3044                 isSubtype(from, to) ||
  3045                 ((subFrom != null) && isSameType(subFrom, to))));
  3048     private List<Type> superClosure(Type t, Type s) {
  3049         List<Type> cl = List.nil();
  3050         for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
  3051             if (isSubtype(s, erasure(l.head))) {
  3052                 cl = insert(cl, l.head);
  3053             } else {
  3054                 cl = union(cl, superClosure(l.head, s));
  3057         return cl;
  3060     private boolean containsTypeEquivalent(Type t, Type s) {
  3061         return
  3062             isSameType(t, s) || // shortcut
  3063             containsType(t, s) && containsType(s, t);
  3066     // <editor-fold defaultstate="collapsed" desc="adapt">
  3067     /**
  3068      * Adapt a type by computing a substitution which maps a source
  3069      * type to a target type.
  3071      * @param source    the source type
  3072      * @param target    the target type
  3073      * @param from      the type variables of the computed substitution
  3074      * @param to        the types of the computed substitution.
  3075      */
  3076     public void adapt(Type source,
  3077                        Type target,
  3078                        ListBuffer<Type> from,
  3079                        ListBuffer<Type> to) throws AdaptFailure {
  3080         new Adapter(from, to).adapt(source, target);
  3083     class Adapter extends SimpleVisitor<Void, Type> {
  3085         ListBuffer<Type> from;
  3086         ListBuffer<Type> to;
  3087         Map<Symbol,Type> mapping;
  3089         Adapter(ListBuffer<Type> from, ListBuffer<Type> to) {
  3090             this.from = from;
  3091             this.to = to;
  3092             mapping = new HashMap<Symbol,Type>();
  3095         public void adapt(Type source, Type target) throws AdaptFailure {
  3096             visit(source, target);
  3097             List<Type> fromList = from.toList();
  3098             List<Type> toList = to.toList();
  3099             while (!fromList.isEmpty()) {
  3100                 Type val = mapping.get(fromList.head.tsym);
  3101                 if (toList.head != val)
  3102                     toList.head = val;
  3103                 fromList = fromList.tail;
  3104                 toList = toList.tail;
  3108         @Override
  3109         public Void visitClassType(ClassType source, Type target) throws AdaptFailure {
  3110             if (target.tag == CLASS)
  3111                 adaptRecursive(source.allparams(), target.allparams());
  3112             return null;
  3115         @Override
  3116         public Void visitArrayType(ArrayType source, Type target) throws AdaptFailure {
  3117             if (target.tag == ARRAY)
  3118                 adaptRecursive(elemtype(source), elemtype(target));
  3119             return null;
  3122         @Override
  3123         public Void visitWildcardType(WildcardType source, Type target) throws AdaptFailure {
  3124             if (source.isExtendsBound())
  3125                 adaptRecursive(upperBound(source), upperBound(target));
  3126             else if (source.isSuperBound())
  3127                 adaptRecursive(lowerBound(source), lowerBound(target));
  3128             return null;
  3131         @Override
  3132         public Void visitTypeVar(TypeVar source, Type target) throws AdaptFailure {
  3133             // Check to see if there is
  3134             // already a mapping for $source$, in which case
  3135             // the old mapping will be merged with the new
  3136             Type val = mapping.get(source.tsym);
  3137             if (val != null) {
  3138                 if (val.isSuperBound() && target.isSuperBound()) {
  3139                     val = isSubtype(lowerBound(val), lowerBound(target))
  3140                         ? target : val;
  3141                 } else if (val.isExtendsBound() && target.isExtendsBound()) {
  3142                     val = isSubtype(upperBound(val), upperBound(target))
  3143                         ? val : target;
  3144                 } else if (!isSameType(val, target)) {
  3145                     throw new AdaptFailure();
  3147             } else {
  3148                 val = target;
  3149                 from.append(source);
  3150                 to.append(target);
  3152             mapping.put(source.tsym, val);
  3153             return null;
  3156         @Override
  3157         public Void visitType(Type source, Type target) {
  3158             return null;
  3161         private Set<TypePair> cache = new HashSet<TypePair>();
  3163         private void adaptRecursive(Type source, Type target) {
  3164             TypePair pair = new TypePair(source, target);
  3165             if (cache.add(pair)) {
  3166                 try {
  3167                     visit(source, target);
  3168                 } finally {
  3169                     cache.remove(pair);
  3174         private void adaptRecursive(List<Type> source, List<Type> target) {
  3175             if (source.length() == target.length()) {
  3176                 while (source.nonEmpty()) {
  3177                     adaptRecursive(source.head, target.head);
  3178                     source = source.tail;
  3179                     target = target.tail;
  3185     public static class AdaptFailure extends RuntimeException {
  3186         static final long serialVersionUID = -7490231548272701566L;
  3189     private void adaptSelf(Type t,
  3190                            ListBuffer<Type> from,
  3191                            ListBuffer<Type> to) {
  3192         try {
  3193             //if (t.tsym.type != t)
  3194                 adapt(t.tsym.type, t, from, to);
  3195         } catch (AdaptFailure ex) {
  3196             // Adapt should never fail calculating a mapping from
  3197             // t.tsym.type to t as there can be no merge problem.
  3198             throw new AssertionError(ex);
  3201     // </editor-fold>
  3203     /**
  3204      * Rewrite all type variables (universal quantifiers) in the given
  3205      * type to wildcards (existential quantifiers).  This is used to
  3206      * determine if a cast is allowed.  For example, if high is true
  3207      * and {@code T <: Number}, then {@code List<T>} is rewritten to
  3208      * {@code List<?  extends Number>}.  Since {@code List<Integer> <:
  3209      * List<? extends Number>} a {@code List<T>} can be cast to {@code
  3210      * List<Integer>} with a warning.
  3211      * @param t a type
  3212      * @param high if true return an upper bound; otherwise a lower
  3213      * bound
  3214      * @param rewriteTypeVars only rewrite captured wildcards if false;
  3215      * otherwise rewrite all type variables
  3216      * @return the type rewritten with wildcards (existential
  3217      * quantifiers) only
  3218      */
  3219     private Type rewriteQuantifiers(Type t, boolean high, boolean rewriteTypeVars) {
  3220         return new Rewriter(high, rewriteTypeVars).rewrite(t);
  3223     class Rewriter extends UnaryVisitor<Type> {
  3225         boolean high;
  3226         boolean rewriteTypeVars;
  3228         Rewriter(boolean high, boolean rewriteTypeVars) {
  3229             this.high = high;
  3230             this.rewriteTypeVars = rewriteTypeVars;
  3233         Type rewrite(Type t) {
  3234             ListBuffer<Type> from = new ListBuffer<Type>();
  3235             ListBuffer<Type> to = new ListBuffer<Type>();
  3236             adaptSelf(t, from, to);
  3237             ListBuffer<Type> rewritten = new ListBuffer<Type>();
  3238             List<Type> formals = from.toList();
  3239             boolean changed = false;
  3240             for (Type arg : to.toList()) {
  3241                 Type bound = visit(arg);
  3242                 if (arg != bound) {
  3243                     changed = true;
  3244                     bound = high ? makeExtendsWildcard(bound, (TypeVar)formals.head)
  3245                               : makeSuperWildcard(bound, (TypeVar)formals.head);
  3247                 rewritten.append(bound);
  3248                 formals = formals.tail;
  3250             if (changed)
  3251                 return subst(t.tsym.type, from.toList(), rewritten.toList());
  3252             else
  3253                 return t;
  3256         public Type visitType(Type t, Void s) {
  3257             return high ? upperBound(t) : lowerBound(t);
  3260         @Override
  3261         public Type visitCapturedType(CapturedType t, Void s) {
  3262             return visitWildcardType(t.wildcard, null);
  3265         @Override
  3266         public Type visitTypeVar(TypeVar t, Void s) {
  3267             if (rewriteTypeVars)
  3268                 return high ? t.bound : syms.botType;
  3269             else
  3270                 return t;
  3273         @Override
  3274         public Type visitWildcardType(WildcardType t, Void s) {
  3275             Type bound = high ? t.getExtendsBound() :
  3276                                 t.getSuperBound();
  3277             if (bound == null)
  3278                 bound = high ? syms.objectType : syms.botType;
  3279             return bound;
  3283     /**
  3284      * Create a wildcard with the given upper (extends) bound; create
  3285      * an unbounded wildcard if bound is Object.
  3287      * @param bound the upper bound
  3288      * @param formal the formal type parameter that will be
  3289      * substituted by the wildcard
  3290      */
  3291     private WildcardType makeExtendsWildcard(Type bound, TypeVar formal) {
  3292         if (bound == syms.objectType) {
  3293             return new WildcardType(syms.objectType,
  3294                                     BoundKind.UNBOUND,
  3295                                     syms.boundClass,
  3296                                     formal);
  3297         } else {
  3298             return new WildcardType(bound,
  3299                                     BoundKind.EXTENDS,
  3300                                     syms.boundClass,
  3301                                     formal);
  3305     /**
  3306      * Create a wildcard with the given lower (super) bound; create an
  3307      * unbounded wildcard if bound is bottom (type of {@code null}).
  3309      * @param bound the lower bound
  3310      * @param formal the formal type parameter that will be
  3311      * substituted by the wildcard
  3312      */
  3313     private WildcardType makeSuperWildcard(Type bound, TypeVar formal) {
  3314         if (bound.tag == BOT) {
  3315             return new WildcardType(syms.objectType,
  3316                                     BoundKind.UNBOUND,
  3317                                     syms.boundClass,
  3318                                     formal);
  3319         } else {
  3320             return new WildcardType(bound,
  3321                                     BoundKind.SUPER,
  3322                                     syms.boundClass,
  3323                                     formal);
  3327     /**
  3328      * A wrapper for a type that allows use in sets.
  3329      */
  3330     class SingletonType {
  3331         final Type t;
  3332         SingletonType(Type t) {
  3333             this.t = t;
  3335         public int hashCode() {
  3336             return Types.this.hashCode(t);
  3338         public boolean equals(Object obj) {
  3339             return (obj instanceof SingletonType) &&
  3340                 isSameType(t, ((SingletonType)obj).t);
  3342         public String toString() {
  3343             return t.toString();
  3346     // </editor-fold>
  3348     // <editor-fold defaultstate="collapsed" desc="Visitors">
  3349     /**
  3350      * A default visitor for types.  All visitor methods except
  3351      * visitType are implemented by delegating to visitType.  Concrete
  3352      * subclasses must provide an implementation of visitType and can
  3353      * override other methods as needed.
  3355      * @param <R> the return type of the operation implemented by this
  3356      * visitor; use Void if no return type is needed.
  3357      * @param <S> the type of the second argument (the first being the
  3358      * type itself) of the operation implemented by this visitor; use
  3359      * Void if a second argument is not needed.
  3360      */
  3361     public static abstract class DefaultTypeVisitor<R,S> implements Type.Visitor<R,S> {
  3362         final public R visit(Type t, S s)               { return t.accept(this, s); }
  3363         public R visitClassType(ClassType t, S s)       { return visitType(t, s); }
  3364         public R visitWildcardType(WildcardType t, S s) { return visitType(t, s); }
  3365         public R visitArrayType(ArrayType t, S s)       { return visitType(t, s); }
  3366         public R visitMethodType(MethodType t, S s)     { return visitType(t, s); }
  3367         public R visitPackageType(PackageType t, S s)   { return visitType(t, s); }
  3368         public R visitTypeVar(TypeVar t, S s)           { return visitType(t, s); }
  3369         public R visitCapturedType(CapturedType t, S s) { return visitType(t, s); }
  3370         public R visitForAll(ForAll t, S s)             { return visitType(t, s); }
  3371         public R visitUndetVar(UndetVar t, S s)         { return visitType(t, s); }
  3372         public R visitErrorType(ErrorType t, S s)       { return visitType(t, s); }
  3375     /**
  3376      * A default visitor for symbols.  All visitor methods except
  3377      * visitSymbol are implemented by delegating to visitSymbol.  Concrete
  3378      * subclasses must provide an implementation of visitSymbol and can
  3379      * override other methods as needed.
  3381      * @param <R> the return type of the operation implemented by this
  3382      * visitor; use Void if no return type is needed.
  3383      * @param <S> the type of the second argument (the first being the
  3384      * symbol itself) of the operation implemented by this visitor; use
  3385      * Void if a second argument is not needed.
  3386      */
  3387     public static abstract class DefaultSymbolVisitor<R,S> implements Symbol.Visitor<R,S> {
  3388         final public R visit(Symbol s, S arg)                   { return s.accept(this, arg); }
  3389         public R visitClassSymbol(ClassSymbol s, S arg)         { return visitSymbol(s, arg); }
  3390         public R visitMethodSymbol(MethodSymbol s, S arg)       { return visitSymbol(s, arg); }
  3391         public R visitOperatorSymbol(OperatorSymbol s, S arg)   { return visitSymbol(s, arg); }
  3392         public R visitPackageSymbol(PackageSymbol s, S arg)     { return visitSymbol(s, arg); }
  3393         public R visitTypeSymbol(TypeSymbol s, S arg)           { return visitSymbol(s, arg); }
  3394         public R visitVarSymbol(VarSymbol s, S arg)             { return visitSymbol(s, arg); }
  3397     /**
  3398      * A <em>simple</em> visitor for types.  This visitor is simple as
  3399      * captured wildcards, for-all types (generic methods), and
  3400      * undetermined type variables (part of inference) are hidden.
  3401      * Captured wildcards are hidden by treating them as type
  3402      * variables and the rest are hidden by visiting their qtypes.
  3404      * @param <R> the return type of the operation implemented by this
  3405      * visitor; use Void if no return type is needed.
  3406      * @param <S> the type of the second argument (the first being the
  3407      * type itself) of the operation implemented by this visitor; use
  3408      * Void if a second argument is not needed.
  3409      */
  3410     public static abstract class SimpleVisitor<R,S> extends DefaultTypeVisitor<R,S> {
  3411         @Override
  3412         public R visitCapturedType(CapturedType t, S s) {
  3413             return visitTypeVar(t, s);
  3415         @Override
  3416         public R visitForAll(ForAll t, S s) {
  3417             return visit(t.qtype, s);
  3419         @Override
  3420         public R visitUndetVar(UndetVar t, S s) {
  3421             return visit(t.qtype, s);
  3425     /**
  3426      * A plain relation on types.  That is a 2-ary function on the
  3427      * form Type&nbsp;&times;&nbsp;Type&nbsp;&rarr;&nbsp;Boolean.
  3428      * <!-- In plain text: Type x Type -> Boolean -->
  3429      */
  3430     public static abstract class TypeRelation extends SimpleVisitor<Boolean,Type> {}
  3432     /**
  3433      * A convenience visitor for implementing operations that only
  3434      * require one argument (the type itself), that is, unary
  3435      * operations.
  3437      * @param <R> the return type of the operation implemented by this
  3438      * visitor; use Void if no return type is needed.
  3439      */
  3440     public static abstract class UnaryVisitor<R> extends SimpleVisitor<R,Void> {
  3441         final public R visit(Type t) { return t.accept(this, null); }
  3444     /**
  3445      * A visitor for implementing a mapping from types to types.  The
  3446      * default behavior of this class is to implement the identity
  3447      * mapping (mapping a type to itself).  This can be overridden in
  3448      * subclasses.
  3450      * @param <S> the type of the second argument (the first being the
  3451      * type itself) of this mapping; use Void if a second argument is
  3452      * not needed.
  3453      */
  3454     public static class MapVisitor<S> extends DefaultTypeVisitor<Type,S> {
  3455         final public Type visit(Type t) { return t.accept(this, null); }
  3456         public Type visitType(Type t, S s) { return t; }
  3458     // </editor-fold>

mercurial