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