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