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