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