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