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