1 /*
   2  * Copyright (c) 2003, 2024, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package com.sun.tools.javac.code;
  27 
  28 import java.lang.ref.SoftReference;
  29 import java.util.HashSet;
  30 import java.util.HashMap;
  31 import java.util.Locale;
  32 import java.util.Map;
  33 import java.util.Optional;
  34 import java.util.Set;
  35 import java.util.WeakHashMap;

  36 import java.util.function.BiPredicate;
  37 import java.util.function.Function;
  38 import java.util.function.Predicate;
  39 import java.util.stream.Collector;
  40 
  41 import javax.tools.JavaFileObject;
  42 
  43 import com.sun.tools.javac.code.Attribute.RetentionPolicy;
  44 import com.sun.tools.javac.code.Lint.LintCategory;
  45 import com.sun.tools.javac.code.Source.Feature;
  46 import com.sun.tools.javac.code.Type.UndetVar.InferenceBound;
  47 import com.sun.tools.javac.code.TypeMetadata.Annotations;
  48 import com.sun.tools.javac.comp.AttrContext;
  49 import com.sun.tools.javac.comp.Check;
  50 import com.sun.tools.javac.comp.Enter;
  51 import com.sun.tools.javac.comp.Env;
  52 import com.sun.tools.javac.comp.LambdaToMethod;
  53 import com.sun.tools.javac.jvm.ClassFile;
  54 import com.sun.tools.javac.util.*;
  55 
  56 import static com.sun.tools.javac.code.BoundKind.*;
  57 import static com.sun.tools.javac.code.Flags.*;
  58 import static com.sun.tools.javac.code.Kinds.Kind.*;
  59 import static com.sun.tools.javac.code.Scope.*;
  60 import static com.sun.tools.javac.code.Scope.LookupKind.NON_RECURSIVE;
  61 import static com.sun.tools.javac.code.Symbol.*;
  62 import static com.sun.tools.javac.code.Type.*;
  63 import static com.sun.tools.javac.code.TypeTag.*;
  64 import static com.sun.tools.javac.jvm.ClassFile.externalize;
  65 import static com.sun.tools.javac.main.Option.DOE;
  66 
  67 import com.sun.tools.javac.resources.CompilerProperties.Fragments;
  68 
  69 /**
  70  * Utility class containing various operations on types.
  71  *
  72  * <p>Unless other names are more illustrative, the following naming
  73  * conventions should be observed in this file:
  74  *
  75  * <dl>
  76  * <dt>t</dt>
  77  * <dd>If the first argument to an operation is a type, it should be named t.</dd>
  78  * <dt>s</dt>
  79  * <dd>Similarly, if the second argument to an operation is a type, it should be named s.</dd>
  80  * <dt>ts</dt>
  81  * <dd>If an operations takes a list of types, the first should be named ts.</dd>
  82  * <dt>ss</dt>
  83  * <dd>A second list of types should be named ss.</dd>
  84  * </dl>
  85  *
  86  * <p><b>This is NOT part of any supported API.
  87  * If you write code that depends on this, you do so at your own risk.
  88  * This code and its internal interfaces are subject to change or
  89  * deletion without notice.</b>
  90  */
  91 public class Types {
  92     protected static final Context.Key<Types> typesKey = new Context.Key<>();
  93 
  94     final Symtab syms;
  95     final JavacMessages messages;
  96     final Names names;
  97     final Check chk;
  98     final Enter enter;
  99     JCDiagnostic.Factory diags;
 100     List<Warner> warnStack = List.nil();
 101     final Name capturedName;
 102 
 103     public final Warner noWarnings;
 104     public final boolean dumpStacktraceOnError;
 105 
 106     // <editor-fold defaultstate="collapsed" desc="Instantiating">
 107     public static Types instance(Context context) {
 108         Types instance = context.get(typesKey);
 109         if (instance == null)
 110             instance = new Types(context);
 111         return instance;
 112     }
 113 
 114     @SuppressWarnings("this-escape")
 115     protected Types(Context context) {
 116         context.put(typesKey, this);
 117         syms = Symtab.instance(context);
 118         names = Names.instance(context);
 119         Source source = Source.instance(context);
 120         chk = Check.instance(context);
 121         enter = Enter.instance(context);
 122         capturedName = names.fromString("<captured wildcard>");
 123         messages = JavacMessages.instance(context);
 124         diags = JCDiagnostic.Factory.instance(context);
 125         noWarnings = new Warner(null);





 126         Options options = Options.instance(context);
 127         dumpStacktraceOnError = options.isSet("dev") || options.isSet(DOE);
 128     }
 129     // </editor-fold>
 130 
 131     // <editor-fold defaultstate="collapsed" desc="bounds">
 132     /**
 133      * Get a wildcard's upper bound, returning non-wildcards unchanged.
 134      * @param t a type argument, either a wildcard or a type
 135      */
 136     public Type wildUpperBound(Type t) {
 137         if (t.hasTag(WILDCARD)) {
 138             WildcardType w = (WildcardType) t;
 139             if (w.isSuperBound())
 140                 return w.bound == null ? syms.objectType : w.bound.getUpperBound();
 141             else
 142                 return wildUpperBound(w.type);
 143         }
 144         else return t;
 145     }
 146 
 147     /**
 148      * Get a capture variable's upper bound, returning other types unchanged.
 149      * @param t a type
 150      */
 151     public Type cvarUpperBound(Type t) {
 152         if (t.hasTag(TYPEVAR)) {
 153             TypeVar v = (TypeVar) t;
 154             return v.isCaptured() ? cvarUpperBound(v.getUpperBound()) : v;
 155         }
 156         else return t;
 157     }
 158 
 159     /**
 160      * Get a wildcard's lower bound, returning non-wildcards unchanged.
 161      * @param t a type argument, either a wildcard or a type
 162      */
 163     public Type wildLowerBound(Type t) {
 164         if (t.hasTag(WILDCARD)) {
 165             WildcardType w = (WildcardType) t;
 166             return w.isExtendsBound() ? syms.botType : wildLowerBound(w.type);
 167         }
 168         else return t;
 169     }
 170 
 171     /**
 172      * Get a capture variable's lower bound, returning other types unchanged.
 173      * @param t a type
 174      */
 175     public Type cvarLowerBound(Type t) {
 176         if (t.hasTag(TYPEVAR) && ((TypeVar) t).isCaptured()) {
 177             return cvarLowerBound(t.getLowerBound());
 178         }
 179         else return t;
 180     }
 181 
 182     /**
 183      * Recursively skip type-variables until a class/array type is found; capture conversion is then
 184      * (optionally) applied to the resulting type. This is useful for i.e. computing a site that is
 185      * suitable for a method lookup.
 186      */
 187     public Type skipTypeVars(Type site, boolean capture) {
 188         while (site.hasTag(TYPEVAR)) {
 189             site = site.getUpperBound();
 190         }
 191         return capture ? capture(site) : site;
 192     }
 193     // </editor-fold>
 194 
 195     // <editor-fold defaultstate="collapsed" desc="projections">
 196 
 197     /**
 198      * A projection kind. See {@link TypeProjection}
 199      */
 200     enum ProjectionKind {
 201         UPWARDS() {
 202             @Override
 203             ProjectionKind complement() {
 204                 return DOWNWARDS;
 205             }
 206         },
 207         DOWNWARDS() {
 208             @Override
 209             ProjectionKind complement() {
 210                 return UPWARDS;
 211             }
 212         };
 213 
 214         abstract ProjectionKind complement();
 215     }
 216 
 217     /**
 218      * This visitor performs upwards and downwards projections on types.
 219      *
 220      * A projection is defined as a function that takes a type T, a set of type variables V and that
 221      * produces another type S.
 222      *
 223      * An upwards projection maps a type T into a type S such that (i) T has no variables in V,
 224      * and (ii) S is an upper bound of T.
 225      *
 226      * A downwards projection maps a type T into a type S such that (i) T has no variables in V,
 227      * and (ii) S is a lower bound of T.
 228      *
 229      * Note that projections are only allowed to touch variables in V. Therefore, it is possible for
 230      * a projection to leave its input type unchanged if it does not contain any variables in V.
 231      *
 232      * Moreover, note that while an upwards projection is always defined (every type as an upper bound),
 233      * a downwards projection is not always defined.
 234      *
 235      * Examples:
 236      *
 237      * {@code upwards(List<#CAP1>, [#CAP1]) = List<? extends String>, where #CAP1 <: String }
 238      * {@code downwards(List<#CAP2>, [#CAP2]) = List<? super String>, where #CAP2 :> String }
 239      * {@code upwards(List<#CAP1>, [#CAP2]) = List<#CAP1> }
 240      * {@code downwards(List<#CAP1>, [#CAP1]) = not defined }
 241      */
 242     class TypeProjection extends TypeMapping<ProjectionKind> {
 243 
 244         List<Type> vars;
 245         Set<Type> seen = new HashSet<>();
 246 
 247         public TypeProjection(List<Type> vars) {
 248             this.vars = vars;
 249         }
 250 
 251         @Override
 252         public Type visitClassType(ClassType t, ProjectionKind pkind) {
 253             if (t.isCompound()) {
 254                 List<Type> components = directSupertypes(t);
 255                 List<Type> components1 = components.map(c -> c.map(this, pkind));
 256                 if (components == components1) return t;
 257                 else return makeIntersectionType(components1);
 258             } else {
 259                 Type outer = t.getEnclosingType();
 260                 Type outer1 = visit(outer, pkind);
 261                 List<Type> typarams = t.getTypeArguments();
 262                 List<Type> formals = t.tsym.type.getTypeArguments();
 263                 ListBuffer<Type> typarams1 = new ListBuffer<>();
 264                 boolean changed = false;
 265                 for (Type actual : typarams) {
 266                     Type t2 = mapTypeArgument(t, formals.head.getUpperBound(), actual, pkind);
 267                     if (t2.hasTag(BOT)) {
 268                         //not defined
 269                         return syms.botType;
 270                     }
 271                     typarams1.add(t2);
 272                     changed |= actual != t2;
 273                     formals = formals.tail;
 274                 }
 275                 if (outer1 == outer && !changed) return t;
 276                 else return new ClassType(outer1, typarams1.toList(), t.tsym, t.getMetadata()) {
 277                     @Override
 278                     protected boolean needsStripping() {
 279                         return true;
 280                     }
 281                 };
 282             }
 283         }
 284 
 285         @Override
 286         public Type visitArrayType(ArrayType t, ProjectionKind s) {
 287             Type elemtype = t.elemtype;
 288             Type elemtype1 = visit(elemtype, s);
 289             if (elemtype1 == elemtype) {
 290                 return t;
 291             } else if (elemtype1.hasTag(BOT)) {
 292                 //undefined
 293                 return syms.botType;
 294             } else {
 295                 return new ArrayType(elemtype1, t.tsym, t.metadata) {
 296                     @Override
 297                     protected boolean needsStripping() {
 298                         return true;
 299                     }
 300                 };
 301             }
 302         }
 303 
 304         @Override
 305         public Type visitTypeVar(TypeVar t, ProjectionKind pkind) {
 306             if (vars.contains(t)) {
 307                 if (seen.add(t)) {
 308                     try {
 309                         final Type bound;
 310                         switch (pkind) {
 311                             case UPWARDS:
 312                                 bound = t.getUpperBound();
 313                                 break;
 314                             case DOWNWARDS:
 315                                 bound = (t.getLowerBound() == null) ?
 316                                         syms.botType :
 317                                         t.getLowerBound();
 318                                 break;
 319                             default:
 320                                 Assert.error();
 321                                 return null;
 322                         }
 323                         return bound.map(this, pkind);
 324                     } finally {
 325                         seen.remove(t);
 326                     }
 327                 } else {
 328                     //cycle
 329                     return pkind == ProjectionKind.UPWARDS ?
 330                             syms.objectType : syms.botType;
 331                 }
 332             } else {
 333                 return t;
 334             }
 335         }
 336 
 337         private Type mapTypeArgument(Type site, Type declaredBound, Type t, ProjectionKind pkind) {
 338             return t.containsAny(vars) ?
 339                     t.map(new TypeArgumentProjection(site, declaredBound), pkind) :
 340                     t;
 341         }
 342 
 343         class TypeArgumentProjection extends TypeMapping<ProjectionKind> {
 344 
 345             Type site;
 346             Type declaredBound;
 347 
 348             TypeArgumentProjection(Type site, Type declaredBound) {
 349                 this.site = site;
 350                 this.declaredBound = declaredBound;
 351             }
 352 
 353             @Override
 354             public Type visitType(Type t, ProjectionKind pkind) {
 355                 //type argument is some type containing restricted vars
 356                 if (pkind == ProjectionKind.DOWNWARDS) {
 357                     //not defined
 358                     return syms.botType;
 359                 }
 360                 Type upper = t.map(TypeProjection.this, ProjectionKind.UPWARDS);
 361                 Type lower = t.map(TypeProjection.this, ProjectionKind.DOWNWARDS);
 362                 List<Type> formals = site.tsym.type.getTypeArguments();
 363                 BoundKind bk;
 364                 Type bound;
 365                 if (!isSameType(upper, syms.objectType) &&
 366                         (declaredBound.containsAny(formals) ||
 367                          !isSubtype(declaredBound, upper))) {
 368                     bound = upper;
 369                     bk = EXTENDS;
 370                 } else if (!lower.hasTag(BOT)) {
 371                     bound = lower;
 372                     bk = SUPER;
 373                 } else {
 374                     bound = syms.objectType;
 375                     bk = UNBOUND;
 376                 }
 377                 return makeWildcard(bound, bk);
 378             }
 379 
 380             @Override
 381             public Type visitWildcardType(WildcardType wt, ProjectionKind pkind) {
 382                 //type argument is some wildcard whose bound contains restricted vars
 383                 Type bound = syms.botType;
 384                 BoundKind bk = wt.kind;
 385                 switch (wt.kind) {
 386                     case EXTENDS:
 387                         bound = wt.type.map(TypeProjection.this, pkind);
 388                         if (bound.hasTag(BOT)) {
 389                             return syms.botType;
 390                         }
 391                         break;
 392                     case SUPER:
 393                         bound = wt.type.map(TypeProjection.this, pkind.complement());
 394                         if (bound.hasTag(BOT)) {
 395                             bound = syms.objectType;
 396                             bk = UNBOUND;
 397                         }
 398                         break;
 399                 }
 400                 return makeWildcard(bound, bk);
 401             }
 402 
 403             private Type makeWildcard(Type bound, BoundKind bk) {
 404                 return new WildcardType(bound, bk, syms.boundClass) {
 405                     @Override
 406                     protected boolean needsStripping() {
 407                         return true;
 408                     }
 409                 };
 410             }
 411         }
 412     }
 413 
 414     /**
 415      * Computes an upward projection of given type, and vars. See {@link TypeProjection}.
 416      *
 417      * @param t the type to be projected
 418      * @param vars the set of type variables to be mapped
 419      * @return the type obtained as result of the projection
 420      */
 421     public Type upward(Type t, List<Type> vars) {
 422         return t.map(new TypeProjection(vars), ProjectionKind.UPWARDS);
 423     }
 424 
 425     /**
 426      * Computes the set of captured variables mentioned in a given type. See {@link CaptureScanner}.
 427      * This routine is typically used to computed the input set of variables to be used during
 428      * an upwards projection (see {@link Types#upward(Type, List)}).
 429      *
 430      * @param t the type where occurrences of captured variables have to be found
 431      * @return the set of captured variables found in t
 432      */
 433     public List<Type> captures(Type t) {
 434         CaptureScanner cs = new CaptureScanner();
 435         Set<Type> captures = new HashSet<>();
 436         cs.visit(t, captures);
 437         return List.from(captures);
 438     }
 439 
 440     /**
 441      * This visitor scans a type recursively looking for occurrences of captured type variables.
 442      */
 443     class CaptureScanner extends SimpleVisitor<Void, Set<Type>> {
 444 
 445         @Override
 446         public Void visitType(Type t, Set<Type> types) {
 447             return null;
 448         }
 449 
 450         @Override
 451         public Void visitClassType(ClassType t, Set<Type> seen) {
 452             if (t.isCompound()) {
 453                 directSupertypes(t).forEach(s -> visit(s, seen));
 454             } else {
 455                 t.allparams().forEach(ta -> visit(ta, seen));
 456             }
 457             return null;
 458         }
 459 
 460         @Override
 461         public Void visitArrayType(ArrayType t, Set<Type> seen) {
 462             return visit(t.elemtype, seen);
 463         }
 464 
 465         @Override
 466         public Void visitWildcardType(WildcardType t, Set<Type> seen) {
 467             visit(t.type, seen);
 468             return null;
 469         }
 470 
 471         @Override
 472         public Void visitTypeVar(TypeVar t, Set<Type> seen) {
 473             if ((t.tsym.flags() & Flags.SYNTHETIC) != 0 && seen.add(t)) {
 474                 visit(t.getUpperBound(), seen);
 475             }
 476             return null;
 477         }
 478 
 479         @Override
 480         public Void visitCapturedType(CapturedType t, Set<Type> seen) {
 481             if (seen.add(t)) {
 482                 visit(t.getUpperBound(), seen);
 483                 visit(t.getLowerBound(), seen);
 484             }
 485             return null;
 486         }
 487     }
 488 
 489     // </editor-fold>
 490 
 491     // <editor-fold defaultstate="collapsed" desc="isUnbounded">
 492     /**
 493      * Checks that all the arguments to a class are unbounded
 494      * wildcards or something else that doesn't make any restrictions
 495      * on the arguments. If a class isUnbounded, a raw super- or
 496      * subclass can be cast to it without a warning.
 497      * @param t a type
 498      * @return true iff the given type is unbounded or raw
 499      */
 500     public boolean isUnbounded(Type t) {
 501         return isUnbounded.visit(t);
 502     }
 503     // where
 504         private final UnaryVisitor<Boolean> isUnbounded = new UnaryVisitor<Boolean>() {
 505 
 506             public Boolean visitType(Type t, Void ignored) {
 507                 return true;
 508             }
 509 
 510             @Override
 511             public Boolean visitClassType(ClassType t, Void ignored) {
 512                 List<Type> parms = t.tsym.type.allparams();
 513                 List<Type> args = t.allparams();
 514                 while (parms.nonEmpty()) {
 515                     WildcardType unb = new WildcardType(syms.objectType,
 516                                                         BoundKind.UNBOUND,
 517                                                         syms.boundClass,
 518                                                         (TypeVar)parms.head);
 519                     if (!containsType(args.head, unb))
 520                         return false;
 521                     parms = parms.tail;
 522                     args = args.tail;
 523                 }
 524                 return true;
 525             }
 526         };
 527     // </editor-fold>
 528 
 529     // <editor-fold defaultstate="collapsed" desc="asSub">
 530     /**
 531      * Return the least specific subtype of t that starts with symbol
 532      * sym.  If none exists, return null.  The least specific subtype
 533      * is determined as follows:
 534      *
 535      * <p>If there is exactly one parameterized instance of sym that is a
 536      * subtype of t, that parameterized instance is returned.<br>
 537      * Otherwise, if the plain type or raw type `sym' is a subtype of
 538      * type t, the type `sym' itself is returned.  Otherwise, null is
 539      * returned.
 540      */
 541     public Type asSub(Type t, Symbol sym) {
 542         return asSub.visit(t, sym);
 543     }
 544     // where
 545         private final SimpleVisitor<Type,Symbol> asSub = new SimpleVisitor<Type,Symbol>() {
 546 
 547             public Type visitType(Type t, Symbol sym) {
 548                 return null;
 549             }
 550 
 551             @Override
 552             public Type visitClassType(ClassType t, Symbol sym) {
 553                 if (t.tsym == sym)
 554                     return t;
 555                 Type base = asSuper(sym.type, t.tsym);
 556                 if (base == null)
 557                     return null;
 558                 ListBuffer<Type> from = new ListBuffer<>();
 559                 ListBuffer<Type> to = new ListBuffer<>();
 560                 try {
 561                     adapt(base, t, from, to);
 562                 } catch (AdaptFailure ex) {
 563                     return null;
 564                 }
 565                 Type res = subst(sym.type, from.toList(), to.toList());
 566                 if (!isSubtype(res, t))
 567                     return null;
 568                 ListBuffer<Type> openVars = new ListBuffer<>();
 569                 for (List<Type> l = sym.type.allparams();
 570                      l.nonEmpty(); l = l.tail)
 571                     if (res.contains(l.head) && !t.contains(l.head))
 572                         openVars.append(l.head);
 573                 if (openVars.nonEmpty()) {
 574                     if (t.isRaw()) {
 575                         // The subtype of a raw type is raw
 576                         res = erasure(res);
 577                     } else {
 578                         // Unbound type arguments default to ?
 579                         List<Type> opens = openVars.toList();
 580                         ListBuffer<Type> qs = new ListBuffer<>();
 581                         for (List<Type> iter = opens; iter.nonEmpty(); iter = iter.tail) {
 582                             qs.append(new WildcardType(syms.objectType, BoundKind.UNBOUND,
 583                                                        syms.boundClass, (TypeVar) iter.head));
 584                         }
 585                         res = subst(res, opens, qs.toList());
 586                     }
 587                 }
 588                 return res;
 589             }
 590 
 591             @Override
 592             public Type visitErrorType(ErrorType t, Symbol sym) {
 593                 return t;
 594             }
 595         };
 596     // </editor-fold>
 597 
 598     // <editor-fold defaultstate="collapsed" desc="isConvertible">
 599     /**
 600      * Is t a subtype of or convertible via boxing/unboxing
 601      * conversion to s?
 602      */
 603     public boolean isConvertible(Type t, Type s, Warner warn) {
 604         if (t.hasTag(ERROR)) {
 605             return true;
 606         }
 607         boolean tPrimitive = t.isPrimitive();
 608         boolean sPrimitive = s.isPrimitive();
 609         if (tPrimitive == sPrimitive) {
 610             return isSubtypeUnchecked(t, s, warn);
 611         }
 612         boolean tUndet = t.hasTag(UNDETVAR);
 613         boolean sUndet = s.hasTag(UNDETVAR);
 614 
 615         if (tUndet || sUndet) {
 616             return tUndet ?
 617                     isSubtype(t, boxedTypeOrType(s)) :
 618                     isSubtype(boxedTypeOrType(t), s);
 619         }
 620 
 621         return tPrimitive
 622             ? isSubtype(boxedClass(t).type, s)
 623             : isSubtype(unboxedType(t), s);
 624     }
 625 
 626     /**
 627      * Is t a subtype of or convertible via boxing/unboxing
 628      * conversions to s?
 629      */
 630     public boolean isConvertible(Type t, Type s) {
 631         return isConvertible(t, s, noWarnings);
 632     }
 633     // </editor-fold>
 634 
 635     // <editor-fold defaultstate="collapsed" desc="findSam">
 636 
 637     /**
 638      * Exception used to report a function descriptor lookup failure. The exception
 639      * wraps a diagnostic that can be used to generate more details error
 640      * messages.
 641      */
 642     public static class FunctionDescriptorLookupError extends CompilerInternalException {
 643         private static final long serialVersionUID = 0;
 644 
 645         transient JCDiagnostic diagnostic;
 646 
 647         FunctionDescriptorLookupError(boolean dumpStackTraceOnError) {
 648             super(dumpStackTraceOnError);
 649             this.diagnostic = null;
 650         }
 651 
 652         FunctionDescriptorLookupError setMessage(JCDiagnostic diag) {
 653             this.diagnostic = diag;
 654             return this;
 655         }
 656 
 657         public JCDiagnostic getDiagnostic() {
 658             return diagnostic;
 659         }
 660     }
 661 
 662     /**
 663      * A cache that keeps track of function descriptors associated with given
 664      * functional interfaces.
 665      */
 666     class DescriptorCache {
 667 
 668         private WeakHashMap<TypeSymbol, Entry> _map = new WeakHashMap<>();
 669 
 670         class FunctionDescriptor {
 671             Symbol descSym;
 672 
 673             FunctionDescriptor(Symbol descSym) {
 674                 this.descSym = descSym;
 675             }
 676 
 677             public Symbol getSymbol() {
 678                 return descSym;
 679             }
 680 
 681             public Type getType(Type site) {
 682                 site = removeWildcards(site);
 683                 if (site.isIntersection()) {
 684                     IntersectionClassType ict = (IntersectionClassType)site;
 685                     for (Type component : ict.getExplicitComponents()) {
 686                         if (!chk.checkValidGenericType(component)) {
 687                             //if the inferred functional interface type is not well-formed,
 688                             //or if it's not a subtype of the original target, issue an error
 689                             throw failure(diags.fragment(Fragments.NoSuitableFunctionalIntfInst(site)));
 690                         }
 691                     }
 692                 } else {
 693                     if (!chk.checkValidGenericType(site)) {
 694                         //if the inferred functional interface type is not well-formed,
 695                         //or if it's not a subtype of the original target, issue an error
 696                         throw failure(diags.fragment(Fragments.NoSuitableFunctionalIntfInst(site)));
 697                     }
 698                 }
 699                 return memberType(site, descSym);
 700             }
 701         }
 702 
 703         class Entry {
 704             final FunctionDescriptor cachedDescRes;
 705             final int prevMark;
 706 
 707             public Entry(FunctionDescriptor cachedDescRes,
 708                     int prevMark) {
 709                 this.cachedDescRes = cachedDescRes;
 710                 this.prevMark = prevMark;
 711             }
 712 
 713             boolean matches(int mark) {
 714                 return  this.prevMark == mark;
 715             }
 716         }
 717 
 718         FunctionDescriptor get(TypeSymbol origin) throws FunctionDescriptorLookupError {
 719             Entry e = _map.get(origin);
 720             CompoundScope members = membersClosure(origin.type, false);
 721             if (e == null ||
 722                     !e.matches(members.getMark())) {
 723                 FunctionDescriptor descRes = findDescriptorInternal(origin, members);
 724                 _map.put(origin, new Entry(descRes, members.getMark()));
 725                 return descRes;
 726             }
 727             else {
 728                 return e.cachedDescRes;
 729             }
 730         }
 731 
 732         /**
 733          * Compute the function descriptor associated with a given functional interface
 734          */
 735         public FunctionDescriptor findDescriptorInternal(TypeSymbol origin,
 736                 CompoundScope membersCache) throws FunctionDescriptorLookupError {
 737             if (!origin.isInterface() || (origin.flags() & ANNOTATION) != 0 || origin.isSealed()) {
 738                 //t must be an interface
 739                 throw failure("not.a.functional.intf", origin);
 740             }
 741 
 742             final ListBuffer<Symbol> abstracts = new ListBuffer<>();
 743             for (Symbol sym : membersCache.getSymbols(new DescriptorFilter(origin))) {
 744                 Type mtype = memberType(origin.type, sym);
 745                 if (abstracts.isEmpty()) {
 746                     abstracts.append(sym);
 747                 } else if ((sym.name == abstracts.first().name &&
 748                         overrideEquivalent(mtype, memberType(origin.type, abstracts.first())))) {
 749                     if (!abstracts.stream().filter(msym -> msym.owner.isSubClass(sym.enclClass(), Types.this))
 750                             .map(msym -> memberType(origin.type, msym))
 751                             .anyMatch(abstractMType -> isSubSignature(abstractMType, mtype))) {
 752                         abstracts.append(sym);
 753                     }
 754                 } else {
 755                     //the target method(s) should be the only abstract members of t
 756                     throw failure("not.a.functional.intf.1",  origin,
 757                             diags.fragment(Fragments.IncompatibleAbstracts(Kinds.kindName(origin), origin)));
 758                 }
 759             }
 760             if (abstracts.isEmpty()) {
 761                 //t must define a suitable non-generic method
 762                 throw failure("not.a.functional.intf.1", origin,
 763                             diags.fragment(Fragments.NoAbstracts(Kinds.kindName(origin), origin)));
 764             } else if (abstracts.size() == 1) {
 765                 return new FunctionDescriptor(abstracts.first());
 766             } else { // size > 1
 767                 FunctionDescriptor descRes = mergeDescriptors(origin, abstracts.toList());
 768                 if (descRes == null) {
 769                     //we can get here if the functional interface is ill-formed
 770                     ListBuffer<JCDiagnostic> descriptors = new ListBuffer<>();
 771                     for (Symbol desc : abstracts) {
 772                         String key = desc.type.getThrownTypes().nonEmpty() ?
 773                                 "descriptor.throws" : "descriptor";
 774                         descriptors.append(diags.fragment(key, desc.name,
 775                                 desc.type.getParameterTypes(),
 776                                 desc.type.getReturnType(),
 777                                 desc.type.getThrownTypes()));
 778                     }
 779                     JCDiagnostic msg =
 780                             diags.fragment(Fragments.IncompatibleDescsInFunctionalIntf(Kinds.kindName(origin),
 781                                                                                        origin));
 782                     JCDiagnostic.MultilineDiagnostic incompatibleDescriptors =
 783                             new JCDiagnostic.MultilineDiagnostic(msg, descriptors.toList());
 784                     throw failure(incompatibleDescriptors);
 785                 }
 786                 return descRes;
 787             }
 788         }
 789 
 790         /**
 791          * Compute a synthetic type for the target descriptor given a list
 792          * of override-equivalent methods in the functional interface type.
 793          * The resulting method type is a method type that is override-equivalent
 794          * and return-type substitutable with each method in the original list.
 795          */
 796         private FunctionDescriptor mergeDescriptors(TypeSymbol origin, List<Symbol> methodSyms) {
 797             return mergeAbstracts(methodSyms, origin.type, false)
 798                     .map(bestSoFar -> new FunctionDescriptor(bestSoFar.baseSymbol()) {
 799                         @Override
 800                         public Type getType(Type origin) {
 801                             Type mt = memberType(origin, getSymbol());
 802                             return createMethodTypeWithThrown(mt, bestSoFar.type.getThrownTypes());
 803                         }
 804                     }).orElse(null);
 805         }
 806 
 807         FunctionDescriptorLookupError failure(String msg, Object... args) {
 808             return failure(diags.fragment(msg, args));
 809         }
 810 
 811         FunctionDescriptorLookupError failure(JCDiagnostic diag) {
 812             return new FunctionDescriptorLookupError(Types.this.dumpStacktraceOnError).setMessage(diag);
 813         }
 814     }
 815 
 816     private DescriptorCache descCache = new DescriptorCache();
 817 
 818     /**
 819      * Find the method descriptor associated to this class symbol - if the
 820      * symbol 'origin' is not a functional interface, an exception is thrown.
 821      */
 822     public Symbol findDescriptorSymbol(TypeSymbol origin) throws FunctionDescriptorLookupError {
 823         return descCache.get(origin).getSymbol();
 824     }
 825 
 826     /**
 827      * Find the type of the method descriptor associated to this class symbol -
 828      * if the symbol 'origin' is not a functional interface, an exception is thrown.
 829      */
 830     public Type findDescriptorType(Type origin) throws FunctionDescriptorLookupError {
 831         return descCache.get(origin.tsym).getType(origin);
 832     }
 833 
 834     /**
 835      * Is given type a functional interface?
 836      */
 837     public boolean isFunctionalInterface(TypeSymbol tsym) {
 838         try {
 839             findDescriptorSymbol(tsym);
 840             return true;
 841         } catch (FunctionDescriptorLookupError ex) {
 842             return false;
 843         }
 844     }
 845 
 846     public boolean isFunctionalInterface(Type site) {
 847         try {
 848             findDescriptorType(site);
 849             return true;
 850         } catch (FunctionDescriptorLookupError ex) {
 851             return false;
 852         }
 853     }
 854 
 855     public Type removeWildcards(Type site) {
 856         if (site.getTypeArguments().stream().anyMatch(t -> t.hasTag(WILDCARD))) {
 857             //compute non-wildcard parameterization - JLS 9.9
 858             List<Type> actuals = site.getTypeArguments();
 859             List<Type> formals = site.tsym.type.getTypeArguments();
 860             ListBuffer<Type> targs = new ListBuffer<>();
 861             for (Type formal : formals) {
 862                 Type actual = actuals.head;
 863                 Type bound = formal.getUpperBound();
 864                 if (actuals.head.hasTag(WILDCARD)) {
 865                     WildcardType wt = (WildcardType)actual;
 866                     //check that bound does not contain other formals
 867                     if (bound.containsAny(formals)) {
 868                         targs.add(wt.type);
 869                     } else {
 870                         //compute new type-argument based on declared bound and wildcard bound
 871                         switch (wt.kind) {
 872                             case UNBOUND:
 873                                 targs.add(bound);
 874                                 break;
 875                             case EXTENDS:
 876                                 targs.add(glb(bound, wt.type));
 877                                 break;
 878                             case SUPER:
 879                                 targs.add(wt.type);
 880                                 break;
 881                             default:
 882                                 Assert.error("Cannot get here!");
 883                         }
 884                     }
 885                 } else {
 886                     //not a wildcard - the new type argument remains unchanged
 887                     targs.add(actual);
 888                 }
 889                 actuals = actuals.tail;
 890             }
 891             return subst(site.tsym.type, formals, targs.toList());
 892         } else {
 893             return site;
 894         }
 895     }
 896 
 897     /**
 898      * Create a symbol for a class that implements a given functional interface
 899      * and overrides its functional descriptor. This routine is used for two
 900      * main purposes: (i) checking well-formedness of a functional interface;
 901      * (ii) perform functional interface bridge calculation.
 902      */
 903     public ClassSymbol makeFunctionalInterfaceClass(Env<AttrContext> env, Name name, Type target, long cflags) {
 904         if (target == null || target == syms.unknownType) {
 905             return null;
 906         }
 907         Symbol descSym = findDescriptorSymbol(target.tsym);
 908         Type descType = findDescriptorType(target);
 909         ClassSymbol csym = new ClassSymbol(cflags, name, env.enclClass.sym.outermostClass());
 910         csym.completer = Completer.NULL_COMPLETER;
 911         csym.members_field = WriteableScope.create(csym);
 912         MethodSymbol instDescSym = new MethodSymbol(descSym.flags(), descSym.name, descType, csym);
 913         csym.members_field.enter(instDescSym);
 914         Type.ClassType ctype = new Type.ClassType(Type.noType, List.nil(), csym);
 915         ctype.supertype_field = syms.objectType;
 916         ctype.interfaces_field = target.isIntersection() ?
 917                 directSupertypes(target) :
 918                 List.of(target);
 919         csym.type = ctype;
 920         csym.sourcefile = ((ClassSymbol)csym.owner).sourcefile;
 921         return csym;
 922     }
 923 
 924     /**
 925      * Find the minimal set of methods that are overridden by the functional
 926      * descriptor in 'origin'. All returned methods are assumed to have different
 927      * erased signatures.
 928      */
 929     public List<Symbol> functionalInterfaceBridges(TypeSymbol origin) {
 930         Assert.check(isFunctionalInterface(origin));
 931         Symbol descSym = findDescriptorSymbol(origin);
 932         CompoundScope members = membersClosure(origin.type, false);
 933         ListBuffer<Symbol> overridden = new ListBuffer<>();
 934         outer: for (Symbol m2 : members.getSymbolsByName(descSym.name, bridgeFilter)) {
 935             if (m2 == descSym) continue;
 936             else if (descSym.overrides(m2, origin, Types.this, false)) {
 937                 for (Symbol m3 : overridden) {
 938                     if (isSameType(m3.erasure(Types.this), m2.erasure(Types.this)) ||
 939                             (m3.overrides(m2, origin, Types.this, false) &&
 940                             (pendingBridges((ClassSymbol)origin, m3.enclClass()) ||
 941                             (((MethodSymbol)m2).binaryImplementation((ClassSymbol)m3.owner, Types.this) != null)))) {
 942                         continue outer;
 943                     }
 944                 }
 945                 overridden.add(m2);
 946             }
 947         }
 948         return overridden.toList();
 949     }
 950     //where
 951         // Use anonymous class instead of lambda expression intentionally,
 952         // because the variable `names` has modifier: final.
 953         private Predicate<Symbol> bridgeFilter = new Predicate<Symbol>() {
 954             public boolean test(Symbol t) {
 955                 return t.kind == MTH &&
 956                         t.name != names.init &&
 957                         t.name != names.clinit &&
 958                         (t.flags() & SYNTHETIC) == 0;
 959             }
 960         };
 961 
 962         private boolean pendingBridges(ClassSymbol origin, TypeSymbol s) {
 963             //a symbol will be completed from a classfile if (a) symbol has
 964             //an associated file object with CLASS kind and (b) the symbol has
 965             //not been entered
 966             if (origin.classfile != null &&
 967                     origin.classfile.getKind() == JavaFileObject.Kind.CLASS &&
 968                     enter.getEnv(origin) == null) {
 969                 return false;
 970             }
 971             if (origin == s) {
 972                 return true;
 973             }
 974             for (Type t : interfaces(origin.type)) {
 975                 if (pendingBridges((ClassSymbol)t.tsym, s)) {
 976                     return true;
 977                 }
 978             }
 979             return false;
 980         }
 981     // </editor-fold>
 982 
 983    /**
 984     * Scope filter used to skip methods that should be ignored (such as methods
 985     * overridden by j.l.Object) during function interface conversion interface check
 986     */
 987     class DescriptorFilter implements Predicate<Symbol> {
 988 
 989        TypeSymbol origin;
 990 
 991        DescriptorFilter(TypeSymbol origin) {
 992            this.origin = origin;
 993        }
 994 
 995        @Override
 996        public boolean test(Symbol sym) {
 997            return sym.kind == MTH &&
 998                    (sym.flags() & (ABSTRACT | DEFAULT)) == ABSTRACT &&
 999                    !overridesObjectMethod(origin, sym) &&
1000                    (interfaceCandidates(origin.type, (MethodSymbol)sym).head.flags() & DEFAULT) == 0;
1001        }
1002     }
1003 
1004     // <editor-fold defaultstate="collapsed" desc="isSubtype">
1005     /**
1006      * Is t an unchecked subtype of s?
1007      */
1008     public boolean isSubtypeUnchecked(Type t, Type s) {
1009         return isSubtypeUnchecked(t, s, noWarnings);
1010     }
1011     /**
1012      * Is t an unchecked subtype of s?
1013      */
1014     public boolean isSubtypeUnchecked(Type t, Type s, Warner warn) {
1015         boolean result = isSubtypeUncheckedInternal(t, s, true, warn);
1016         if (result) {
1017             checkUnsafeVarargsConversion(t, s, warn);
1018         }
1019         return result;
1020     }
1021     //where
1022         private boolean isSubtypeUncheckedInternal(Type t, Type s, boolean capture, Warner warn) {
1023             if (t.hasTag(ARRAY) && s.hasTag(ARRAY)) {
1024                 if (((ArrayType)t).elemtype.isPrimitive()) {
1025                     return isSameType(elemtype(t), elemtype(s));
1026                 } else {
1027                     return isSubtypeUncheckedInternal(elemtype(t), elemtype(s), false, warn);
1028                 }
1029             } else if (isSubtype(t, s, capture)) {
1030                 return true;
1031             } else if (t.hasTag(TYPEVAR)) {
1032                 return isSubtypeUncheckedInternal(t.getUpperBound(), s, false, warn);
1033             } else if (!s.isRaw()) {
1034                 Type t2 = asSuper(t, s.tsym);
1035                 if (t2 != null && t2.isRaw()) {
1036                     if (isReifiable(s)) {
1037                         warn.silentWarn(LintCategory.UNCHECKED);
1038                     } else {
1039                         warn.warn(LintCategory.UNCHECKED);
1040                     }
1041                     return true;
1042                 }
1043             }
1044             return false;
1045         }
1046 
1047         private void checkUnsafeVarargsConversion(Type t, Type s, Warner warn) {
1048             if (!t.hasTag(ARRAY) || isReifiable(t)) {
1049                 return;
1050             }
1051             ArrayType from = (ArrayType)t;
1052             boolean shouldWarn = false;
1053             switch (s.getTag()) {
1054                 case ARRAY:
1055                     ArrayType to = (ArrayType)s;
1056                     shouldWarn = from.isVarargs() &&
1057                             !to.isVarargs() &&
1058                             !isReifiable(from);
1059                     break;
1060                 case CLASS:
1061                     shouldWarn = from.isVarargs();
1062                     break;
1063             }
1064             if (shouldWarn) {
1065                 warn.warn(LintCategory.VARARGS);
1066             }
1067         }
1068 
1069     /**
1070      * Is t a subtype of s?<br>
1071      * (not defined for Method and ForAll types)
1072      */
1073     public final boolean isSubtype(Type t, Type s) {
1074         return isSubtype(t, s, true);
1075     }
1076     public final boolean isSubtypeNoCapture(Type t, Type s) {
1077         return isSubtype(t, s, false);
1078     }
1079     public boolean isSubtype(Type t, Type s, boolean capture) {
1080         if (t.equalsIgnoreMetadata(s))
1081             return true;
1082         if (s.isPartial())
1083             return isSuperType(s, t);
1084 
1085         if (s.isCompound()) {
1086             for (Type s2 : interfaces(s).prepend(supertype(s))) {
1087                 if (!isSubtype(t, s2, capture))
1088                     return false;
1089             }
1090             return true;
1091         }
1092 
1093         // Generally, if 's' is a lower-bounded type variable, recur on lower bound; but
1094         // for inference variables and intersections, we need to keep 's'
1095         // (see JLS 4.10.2 for intersections and 18.2.3 for inference vars)
1096         if (!t.hasTag(UNDETVAR) && !t.isCompound()) {
1097             // TODO: JDK-8039198, bounds checking sometimes passes in a wildcard as s
1098             Type lower = cvarLowerBound(wildLowerBound(s));
1099             if (s != lower && !lower.hasTag(BOT))
1100                 return isSubtype(capture ? capture(t) : t, lower, false);
1101         }
1102 
1103         return isSubtype.visit(capture ? capture(t) : t, s);
1104     }
1105     // where
1106         private TypeRelation isSubtype = new TypeRelation()
1107         {
1108             @Override
1109             public Boolean visitType(Type t, Type s) {
1110                 switch (t.getTag()) {
1111                  case BYTE:
1112                      return (!s.hasTag(CHAR) && t.getTag().isSubRangeOf(s.getTag()));
1113                  case CHAR:
1114                      return (!s.hasTag(SHORT) && t.getTag().isSubRangeOf(s.getTag()));
1115                  case SHORT: case INT: case LONG:
1116                  case FLOAT: case DOUBLE:
1117                      return t.getTag().isSubRangeOf(s.getTag());
1118                  case BOOLEAN: case VOID:
1119                      return t.hasTag(s.getTag());
1120                  case TYPEVAR:
1121                      return isSubtypeNoCapture(t.getUpperBound(), s);
1122                  case BOT:
1123                      return
1124                          s.hasTag(BOT) || s.hasTag(CLASS) ||
1125                          s.hasTag(ARRAY) || s.hasTag(TYPEVAR);
1126                  case WILDCARD: //we shouldn't be here - avoids crash (see 7034495)
1127                  case NONE:
1128                      return false;
1129                  default:
1130                      throw new AssertionError("isSubtype " + t.getTag());
1131                  }
1132             }
1133 
1134             private Set<TypePair> cache = new HashSet<>();
1135 
1136             private boolean containsTypeRecursive(Type t, Type s) {
1137                 TypePair pair = new TypePair(t, s);
1138                 if (cache.add(pair)) {
1139                     try {
1140                         return containsType(t.getTypeArguments(),
1141                                             s.getTypeArguments());
1142                     } finally {
1143                         cache.remove(pair);
1144                     }
1145                 } else {
1146                     return containsType(t.getTypeArguments(),
1147                                         rewriteSupers(s).getTypeArguments());
1148                 }
1149             }
1150 
1151             private Type rewriteSupers(Type t) {
1152                 if (!t.isParameterized())
1153                     return t;
1154                 ListBuffer<Type> from = new ListBuffer<>();
1155                 ListBuffer<Type> to = new ListBuffer<>();
1156                 adaptSelf(t, from, to);
1157                 if (from.isEmpty())
1158                     return t;
1159                 ListBuffer<Type> rewrite = new ListBuffer<>();
1160                 boolean changed = false;
1161                 for (Type orig : to.toList()) {
1162                     Type s = rewriteSupers(orig);
1163                     if (s.isSuperBound() && !s.isExtendsBound()) {
1164                         s = new WildcardType(syms.objectType,
1165                                              BoundKind.UNBOUND,
1166                                              syms.boundClass,
1167                                              s.getMetadata());
1168                         changed = true;
1169                     } else if (s != orig) {
1170                         s = new WildcardType(wildUpperBound(s),
1171                                              BoundKind.EXTENDS,
1172                                              syms.boundClass,
1173                                              s.getMetadata());
1174                         changed = true;
1175                     }
1176                     rewrite.append(s);
1177                 }
1178                 if (changed)
1179                     return subst(t.tsym.type, from.toList(), rewrite.toList());
1180                 else
1181                     return t;
1182             }
1183 
1184             @Override
1185             public Boolean visitClassType(ClassType t, Type s) {
1186                 Type sup = asSuper(t, s.tsym);
1187                 if (sup == null) return false;
1188                 // If t is an intersection, sup might not be a class type
1189                 if (!sup.hasTag(CLASS)) return isSubtypeNoCapture(sup, s);
1190                 return sup.tsym == s.tsym
1191                      // Check type variable containment
1192                     && (!s.isParameterized() || containsTypeRecursive(s, sup))
1193                     && isSubtypeNoCapture(sup.getEnclosingType(),
1194                                           s.getEnclosingType());
1195             }
1196 
1197             @Override
1198             public Boolean visitArrayType(ArrayType t, Type s) {
1199                 if (s.hasTag(ARRAY)) {
1200                     if (t.elemtype.isPrimitive())
1201                         return isSameType(t.elemtype, elemtype(s));
1202                     else
1203                         return isSubtypeNoCapture(t.elemtype, elemtype(s));
1204                 }
1205 
1206                 if (s.hasTag(CLASS)) {
1207                     Name sname = s.tsym.getQualifiedName();
1208                     return sname == names.java_lang_Object
1209                         || sname == names.java_lang_Cloneable
1210                         || sname == names.java_io_Serializable;
1211                 }
1212 
1213                 return false;
1214             }
1215 
1216             @Override
1217             public Boolean visitUndetVar(UndetVar t, Type s) {
1218                 //todo: test against origin needed? or replace with substitution?
1219                 if (t == s || t.qtype == s || s.hasTag(ERROR)) {
1220                     return true;
1221                 } else if (s.hasTag(BOT)) {
1222                     //if 's' is 'null' there's no instantiated type U for which
1223                     //U <: s (but 'null' itself, which is not a valid type)
1224                     return false;
1225                 }
1226 
1227                 t.addBound(InferenceBound.UPPER, s, Types.this);
1228                 return true;
1229             }
1230 
1231             @Override
1232             public Boolean visitErrorType(ErrorType t, Type s) {
1233                 return true;
1234             }
1235         };
1236 
1237     /**
1238      * Is t a subtype of every type in given list `ts'?<br>
1239      * (not defined for Method and ForAll types)<br>
1240      * Allows unchecked conversions.
1241      */
1242     public boolean isSubtypeUnchecked(Type t, List<Type> ts, Warner warn) {
1243         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
1244             if (!isSubtypeUnchecked(t, l.head, warn))
1245                 return false;
1246         return true;
1247     }
1248 
1249     /**
1250      * Are corresponding elements of ts subtypes of ss?  If lists are
1251      * of different length, return false.
1252      */
1253     public boolean isSubtypes(List<Type> ts, List<Type> ss) {
1254         while (ts.tail != null && ss.tail != null
1255                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
1256                isSubtype(ts.head, ss.head)) {
1257             ts = ts.tail;
1258             ss = ss.tail;
1259         }
1260         return ts.tail == null && ss.tail == null;
1261         /*inlined: ts.isEmpty() && ss.isEmpty();*/
1262     }
1263 
1264     /**
1265      * Are corresponding elements of ts subtypes of ss, allowing
1266      * unchecked conversions?  If lists are of different length,
1267      * return false.
1268      **/
1269     public boolean isSubtypesUnchecked(List<Type> ts, List<Type> ss, Warner warn) {
1270         while (ts.tail != null && ss.tail != null
1271                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
1272                isSubtypeUnchecked(ts.head, ss.head, warn)) {
1273             ts = ts.tail;
1274             ss = ss.tail;
1275         }
1276         return ts.tail == null && ss.tail == null;
1277         /*inlined: ts.isEmpty() && ss.isEmpty();*/
1278     }
1279     // </editor-fold>
1280 
1281     // <editor-fold defaultstate="collapsed" desc="isSuperType">
1282     /**
1283      * Is t a supertype of s?
1284      */
1285     public boolean isSuperType(Type t, Type s) {
1286         switch (t.getTag()) {
1287         case ERROR:
1288             return true;
1289         case UNDETVAR: {
1290             UndetVar undet = (UndetVar)t;
1291             if (t == s ||
1292                 undet.qtype == s ||
1293                 s.hasTag(ERROR) ||
1294                 s.hasTag(BOT)) {
1295                 return true;
1296             }
1297             undet.addBound(InferenceBound.LOWER, s, this);
1298             return true;
1299         }
1300         default:
1301             return isSubtype(s, t);
1302         }
1303     }
1304     // </editor-fold>
1305 
1306     // <editor-fold defaultstate="collapsed" desc="isSameType">
1307     /**
1308      * Are corresponding elements of the lists the same type?  If
1309      * lists are of different length, return false.
1310      */
1311     public boolean isSameTypes(List<Type> ts, List<Type> ss) {
1312         while (ts.tail != null && ss.tail != null
1313                /*inlined: ts.nonEmpty() && ss.nonEmpty()*/ &&
1314                isSameType(ts.head, ss.head)) {
1315             ts = ts.tail;
1316             ss = ss.tail;
1317         }
1318         return ts.tail == null && ss.tail == null;
1319         /*inlined: ts.isEmpty() && ss.isEmpty();*/
1320     }
1321 
1322     /**
1323      * A polymorphic signature method (JLS 15.12.3) is a method that
1324      *   (i) is declared in the java.lang.invoke.MethodHandle/VarHandle classes;
1325      *  (ii) takes a single variable arity parameter;
1326      * (iii) whose declared type is Object[];
1327      *  (iv) has any return type, Object signifying a polymorphic return type; and
1328      *   (v) is native.
1329     */
1330    public boolean isSignaturePolymorphic(MethodSymbol msym) {
1331        List<Type> argtypes = msym.type.getParameterTypes();
1332        return (msym.flags_field & NATIVE) != 0 &&
1333               (msym.owner == syms.methodHandleType.tsym || msym.owner == syms.varHandleType.tsym) &&
1334                argtypes.length() == 1 &&
1335                argtypes.head.hasTag(TypeTag.ARRAY) &&
1336                ((ArrayType)argtypes.head).elemtype.tsym == syms.objectType.tsym;
1337    }
1338 
1339     /**
1340      * Is t the same type as s?
1341      */
1342     public boolean isSameType(Type t, Type s) {
1343         return isSameTypeVisitor.visit(t, s);
1344     }
1345     // where
1346 
1347         /**
1348          * Type-equality relation - type variables are considered
1349          * equals if they share the same object identity.
1350          */
1351         TypeRelation isSameTypeVisitor = new TypeRelation() {
1352 
1353             public Boolean visitType(Type t, Type s) {
1354                 if (t.equalsIgnoreMetadata(s))
1355                     return true;
1356 
1357                 if (s.isPartial())
1358                     return visit(s, t);
1359 
1360                 switch (t.getTag()) {
1361                 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
1362                 case DOUBLE: case BOOLEAN: case VOID: case BOT: case NONE:
1363                     return t.hasTag(s.getTag());
1364                 case TYPEVAR: {
1365                     if (s.hasTag(TYPEVAR)) {
1366                         //type-substitution does not preserve type-var types
1367                         //check that type var symbols and bounds are indeed the same
1368                         return t == s;
1369                     }
1370                     else {
1371                         //special case for s == ? super X, where upper(s) = u
1372                         //check that u == t, where u has been set by Type.withTypeVar
1373                         return s.isSuperBound() &&
1374                                 !s.isExtendsBound() &&
1375                                 visit(t, wildUpperBound(s));
1376                     }
1377                 }
1378                 default:
1379                     throw new AssertionError("isSameType " + t.getTag());
1380                 }
1381             }
1382 
1383             @Override
1384             public Boolean visitWildcardType(WildcardType t, Type s) {
1385                 if (!s.hasTag(WILDCARD)) {
1386                     return false;
1387                 } else {
1388                     WildcardType t2 = (WildcardType)s;
1389                     return (t.kind == t2.kind || (t.isExtendsBound() && s.isExtendsBound())) &&
1390                             isSameType(t.type, t2.type);
1391                 }
1392             }
1393 
1394             @Override
1395             public Boolean visitClassType(ClassType t, Type s) {
1396                 if (t == s)
1397                     return true;
1398 
1399                 if (s.isPartial())
1400                     return visit(s, t);
1401 
1402                 if (s.isSuperBound() && !s.isExtendsBound())
1403                     return visit(t, wildUpperBound(s)) && visit(t, wildLowerBound(s));
1404 
1405                 if (t.isCompound() && s.isCompound()) {
1406                     if (!visit(supertype(t), supertype(s)))
1407                         return false;
1408 
1409                     Map<Symbol,Type> tMap = new HashMap<>();
1410                     for (Type ti : interfaces(t)) {
1411                         tMap.put(ti.tsym, ti);
1412                     }
1413                     for (Type si : interfaces(s)) {
1414                         if (!tMap.containsKey(si.tsym))
1415                             return false;
1416                         Type ti = tMap.remove(si.tsym);
1417                         if (!visit(ti, si))
1418                             return false;
1419                     }
1420                     return tMap.isEmpty();
1421                 }
1422                 return t.tsym == s.tsym
1423                     && visit(t.getEnclosingType(), s.getEnclosingType())
1424                     && containsTypeEquivalent(t.getTypeArguments(), s.getTypeArguments());
1425             }
1426 
1427             @Override
1428             public Boolean visitArrayType(ArrayType t, Type s) {
1429                 if (t == s)
1430                     return true;
1431 
1432                 if (s.isPartial())
1433                     return visit(s, t);
1434 
1435                 return s.hasTag(ARRAY)
1436                     && containsTypeEquivalent(t.elemtype, elemtype(s));
1437             }
1438 
1439             @Override
1440             public Boolean visitMethodType(MethodType t, Type s) {
1441                 // isSameType for methods does not take thrown
1442                 // exceptions into account!
1443                 return hasSameArgs(t, s) && visit(t.getReturnType(), s.getReturnType());
1444             }
1445 
1446             @Override
1447             public Boolean visitPackageType(PackageType t, Type s) {
1448                 return t == s;
1449             }
1450 
1451             @Override
1452             public Boolean visitForAll(ForAll t, Type s) {
1453                 if (!s.hasTag(FORALL)) {
1454                     return false;
1455                 }
1456 
1457                 ForAll forAll = (ForAll)s;
1458                 return hasSameBounds(t, forAll)
1459                     && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
1460             }
1461 
1462             @Override
1463             public Boolean visitUndetVar(UndetVar t, Type s) {
1464                 if (s.hasTag(WILDCARD)) {
1465                     // FIXME, this might be leftovers from before capture conversion
1466                     return false;
1467                 }
1468 
1469                 if (t == s || t.qtype == s || s.hasTag(ERROR)) {
1470                     return true;
1471                 }
1472 
1473                 t.addBound(InferenceBound.EQ, s, Types.this);
1474 
1475                 return true;
1476             }
1477 
1478             @Override
1479             public Boolean visitErrorType(ErrorType t, Type s) {
1480                 return true;
1481             }
1482         };
1483 
1484     // </editor-fold>
1485 
1486     // <editor-fold defaultstate="collapsed" desc="Contains Type">
1487     public boolean containedBy(Type t, Type s) {
1488         switch (t.getTag()) {
1489         case UNDETVAR:
1490             if (s.hasTag(WILDCARD)) {
1491                 UndetVar undetvar = (UndetVar)t;
1492                 WildcardType wt = (WildcardType)s;
1493                 switch(wt.kind) {
1494                     case UNBOUND:
1495                         break;
1496                     case EXTENDS: {
1497                         Type bound = wildUpperBound(s);
1498                         undetvar.addBound(InferenceBound.UPPER, bound, this);
1499                         break;
1500                     }
1501                     case SUPER: {
1502                         Type bound = wildLowerBound(s);
1503                         undetvar.addBound(InferenceBound.LOWER, bound, this);
1504                         break;
1505                     }
1506                 }
1507                 return true;
1508             } else {
1509                 return isSameType(t, s);
1510             }
1511         case ERROR:
1512             return true;
1513         default:
1514             return containsType(s, t);
1515         }
1516     }
1517 
1518     boolean containsType(List<Type> ts, List<Type> ss) {
1519         while (ts.nonEmpty() && ss.nonEmpty()
1520                && containsType(ts.head, ss.head)) {
1521             ts = ts.tail;
1522             ss = ss.tail;
1523         }
1524         return ts.isEmpty() && ss.isEmpty();
1525     }
1526 
1527     /**
1528      * Check if t contains s.
1529      *
1530      * <p>T contains S if:
1531      *
1532      * <p>{@code L(T) <: L(S) && U(S) <: U(T)}
1533      *
1534      * <p>This relation is only used by ClassType.isSubtype(), that
1535      * is,
1536      *
1537      * <p>{@code C<S> <: C<T> if T contains S.}
1538      *
1539      * <p>Because of F-bounds, this relation can lead to infinite
1540      * recursion.  Thus we must somehow break that recursion.  Notice
1541      * that containsType() is only called from ClassType.isSubtype().
1542      * Since the arguments have already been checked against their
1543      * bounds, we know:
1544      *
1545      * <p>{@code U(S) <: U(T) if T is "super" bound (U(T) *is* the bound)}
1546      *
1547      * <p>{@code L(T) <: L(S) if T is "extends" bound (L(T) is bottom)}
1548      *
1549      * @param t a type
1550      * @param s a type
1551      */
1552     public boolean containsType(Type t, Type s) {
1553         return containsType.visit(t, s);
1554     }
1555     // where
1556         private TypeRelation containsType = new TypeRelation() {
1557 
1558             public Boolean visitType(Type t, Type s) {
1559                 if (s.isPartial())
1560                     return containedBy(s, t);
1561                 else
1562                     return isSameType(t, s);
1563             }
1564 
1565 //            void debugContainsType(WildcardType t, Type s) {
1566 //                System.err.println();
1567 //                System.err.format(" does %s contain %s?%n", t, s);
1568 //                System.err.format(" %s U(%s) <: U(%s) %s = %s%n",
1569 //                                  wildUpperBound(s), s, t, wildUpperBound(t),
1570 //                                  t.isSuperBound()
1571 //                                  || isSubtypeNoCapture(wildUpperBound(s), wildUpperBound(t)));
1572 //                System.err.format(" %s L(%s) <: L(%s) %s = %s%n",
1573 //                                  wildLowerBound(t), t, s, wildLowerBound(s),
1574 //                                  t.isExtendsBound()
1575 //                                  || isSubtypeNoCapture(wildLowerBound(t), wildLowerBound(s)));
1576 //                System.err.println();
1577 //            }
1578 
1579             @Override
1580             public Boolean visitWildcardType(WildcardType t, Type s) {
1581                 if (s.isPartial())
1582                     return containedBy(s, t);
1583                 else {
1584 //                    debugContainsType(t, s);
1585                     return isSameWildcard(t, s)
1586                         || isCaptureOf(s, t)
1587                         || ((t.isExtendsBound() || isSubtypeNoCapture(wildLowerBound(t), wildLowerBound(s))) &&
1588                             (t.isSuperBound() || isSubtypeNoCapture(wildUpperBound(s), wildUpperBound(t))));
1589                 }
1590             }
1591 
1592             @Override
1593             public Boolean visitUndetVar(UndetVar t, Type s) {
1594                 if (!s.hasTag(WILDCARD)) {
1595                     return isSameType(t, s);
1596                 } else {
1597                     return false;
1598                 }
1599             }
1600 
1601             @Override
1602             public Boolean visitErrorType(ErrorType t, Type s) {
1603                 return true;
1604             }
1605         };
1606 
1607     public boolean isCaptureOf(Type s, WildcardType t) {
1608         if (!s.hasTag(TYPEVAR) || !((TypeVar)s).isCaptured())
1609             return false;
1610         return isSameWildcard(t, ((CapturedType)s).wildcard);
1611     }
1612 
1613     public boolean isSameWildcard(WildcardType t, Type s) {
1614         if (!s.hasTag(WILDCARD))
1615             return false;
1616         WildcardType w = (WildcardType)s;
1617         return w.kind == t.kind && w.type == t.type;
1618     }
1619 
1620     public boolean containsTypeEquivalent(List<Type> ts, List<Type> ss) {
1621         while (ts.nonEmpty() && ss.nonEmpty()
1622                && containsTypeEquivalent(ts.head, ss.head)) {
1623             ts = ts.tail;
1624             ss = ss.tail;
1625         }
1626         return ts.isEmpty() && ss.isEmpty();
1627     }
1628     // </editor-fold>
1629 
1630     // <editor-fold defaultstate="collapsed" desc="isCastable">
1631     public boolean isCastable(Type t, Type s) {
1632         return isCastable(t, s, noWarnings);
1633     }
1634 
1635     /**
1636      * Is t castable to s?<br>
1637      * s is assumed to be an erased type.<br>
1638      * (not defined for Method and ForAll types).
1639      */
1640     public boolean isCastable(Type t, Type s, Warner warn) {
1641         // if same type
1642         if (t == s)
1643             return true;
1644         // if one of the types is primitive
1645         if (t.isPrimitive() != s.isPrimitive()) {
1646             t = skipTypeVars(t, false);
1647             return (isConvertible(t, s, warn)
1648                     || (s.isPrimitive() &&
1649                         isSubtype(boxedClass(s).type, t)));
1650         }
1651         boolean result;
1652         if (warn != warnStack.head) {
1653             try {
1654                 warnStack = warnStack.prepend(warn);
1655                 checkUnsafeVarargsConversion(t, s, warn);
1656                 result = isCastable.visit(t,s);
1657             } finally {
1658                 warnStack = warnStack.tail;
1659             }
1660         } else {
1661             result = isCastable.visit(t,s);
1662         }
1663         if (result && t.hasTag(CLASS) && t.tsym.kind.matches(Kinds.KindSelector.TYP)
1664                 && s.hasTag(CLASS) && s.tsym.kind.matches(Kinds.KindSelector.TYP)
1665                 && (t.tsym.isSealed() || s.tsym.isSealed())) {
1666             return (t.isCompound() || s.isCompound()) ?
1667                     true :
1668                     !(new DisjointChecker().areDisjoint((ClassSymbol)t.tsym, (ClassSymbol)s.tsym));
1669         }
1670         return result;
1671     }
1672     // where
1673         class DisjointChecker {
1674             Set<Pair<ClassSymbol, ClassSymbol>> pairsSeen = new HashSet<>();
1675             /* there are three cases for ts and ss:
1676              *   - one is a class and the other one is an interface (case I)
1677              *   - both are classes                                 (case II)
1678              *   - both are interfaces                              (case III)
1679              * all those cases are covered in JLS 23, section: "5.1.6.1 Allowed Narrowing Reference Conversion"
1680              */
1681             private boolean areDisjoint(ClassSymbol ts, ClassSymbol ss) {
1682                 Pair<ClassSymbol, ClassSymbol> newPair = new Pair<>(ts, ss);
1683                 /* if we are seeing the same pair again then there is an issue with the sealed hierarchy
1684                  * bail out, a detailed error will be reported downstream
1685                  */
1686                 if (!pairsSeen.add(newPair))
1687                     return false;
1688 
1689                 if (ts.isInterface() != ss.isInterface()) { // case I: one is a class and the other one is an interface
1690                     ClassSymbol isym = ts.isInterface() ? ts : ss; // isym is the interface and csym the class
1691                     ClassSymbol csym = isym == ts ? ss : ts;
1692                     if (!isSubtype(erasure(csym.type), erasure(isym.type))) {
1693                         if (csym.isFinal()) {
1694                             return true;
1695                         } else if (csym.isSealed()) {
1696                             return areDisjoint(isym, csym.getPermittedSubclasses());
1697                         } else if (isym.isSealed()) {
1698                             // if the class is not final and not sealed then it has to be freely extensible
1699                             return areDisjoint(csym, isym.getPermittedSubclasses());
1700                         }
1701                     } // now both are classes or both are interfaces
1702                 } else if (!ts.isInterface()) {              // case II: both are classes
1703                     return !isSubtype(erasure(ss.type), erasure(ts.type)) && !isSubtype(erasure(ts.type), erasure(ss.type));
1704                 } else {                                     // case III: both are interfaces
1705                     if (!isSubtype(erasure(ts.type), erasure(ss.type)) && !isSubtype(erasure(ss.type), erasure(ts.type))) {
1706                         if (ts.isSealed()) {
1707                             return areDisjoint(ss, ts.getPermittedSubclasses());
1708                         } else if (ss.isSealed()) {
1709                             return areDisjoint(ts, ss.getPermittedSubclasses());
1710                         }
1711                     }
1712                 }
1713                 // at this point we haven't been able to statically prove that the classes or interfaces are disjoint
1714                 return false;
1715             }
1716 
1717             boolean areDisjoint(ClassSymbol csym, List<Type> permittedSubtypes) {
1718                 return permittedSubtypes.stream().allMatch(psubtype -> areDisjoint(csym, (ClassSymbol) psubtype.tsym));
1719             }
1720         }
1721 
1722         private TypeRelation isCastable = new TypeRelation() {
1723 
1724             public Boolean visitType(Type t, Type s) {
1725                 if (s.hasTag(ERROR) || t.hasTag(NONE))
1726                     return true;
1727 
1728                 switch (t.getTag()) {
1729                 case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT:
1730                 case DOUBLE:
1731                     return s.isNumeric();
1732                 case BOOLEAN:
1733                     return s.hasTag(BOOLEAN);
1734                 case VOID:
1735                     return false;
1736                 case BOT:
1737                     return isSubtype(t, s);
1738                 default:
1739                     throw new AssertionError();
1740                 }
1741             }
1742 
1743             @Override
1744             public Boolean visitWildcardType(WildcardType t, Type s) {
1745                 return isCastable(wildUpperBound(t), s, warnStack.head);
1746             }
1747 
1748             @Override
1749             public Boolean visitClassType(ClassType t, Type s) {
1750                 if (s.hasTag(ERROR) || s.hasTag(BOT))
1751                     return true;
1752 
1753                 if (s.hasTag(TYPEVAR)) {
1754                     if (isCastable(t, s.getUpperBound(), noWarnings)) {
1755                         warnStack.head.warn(LintCategory.UNCHECKED);
1756                         return true;
1757                     } else {
1758                         return false;
1759                     }
1760                 }
1761 
1762                 if (t.isCompound() || s.isCompound()) {
1763                     return !t.isCompound() ?
1764                             visitCompoundType((ClassType)s, t, true) :
1765                             visitCompoundType(t, s, false);
1766                 }
1767 
1768                 if (s.hasTag(CLASS) || s.hasTag(ARRAY)) {
1769                     boolean upcast;
1770                     if ((upcast = isSubtype(erasure(t), erasure(s)))
1771                         || isSubtype(erasure(s), erasure(t))) {
1772                         if (!upcast && s.hasTag(ARRAY)) {
1773                             if (!isReifiable(s))
1774                                 warnStack.head.warn(LintCategory.UNCHECKED);
1775                             return true;
1776                         } else if (s.isRaw()) {
1777                             return true;
1778                         } else if (t.isRaw()) {
1779                             if (!isUnbounded(s))
1780                                 warnStack.head.warn(LintCategory.UNCHECKED);
1781                             return true;
1782                         }
1783                         // Assume |a| <: |b|
1784                         final Type a = upcast ? t : s;
1785                         final Type b = upcast ? s : t;
1786                         final boolean HIGH = true;
1787                         final boolean LOW = false;
1788                         final boolean DONT_REWRITE_TYPEVARS = false;
1789                         Type aHigh = rewriteQuantifiers(a, HIGH, DONT_REWRITE_TYPEVARS);
1790                         Type aLow  = rewriteQuantifiers(a, LOW,  DONT_REWRITE_TYPEVARS);
1791                         Type bHigh = rewriteQuantifiers(b, HIGH, DONT_REWRITE_TYPEVARS);
1792                         Type bLow  = rewriteQuantifiers(b, LOW,  DONT_REWRITE_TYPEVARS);
1793                         Type lowSub = asSub(bLow, aLow.tsym);
1794                         Type highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
1795                         if (highSub == null) {
1796                             final boolean REWRITE_TYPEVARS = true;
1797                             aHigh = rewriteQuantifiers(a, HIGH, REWRITE_TYPEVARS);
1798                             aLow  = rewriteQuantifiers(a, LOW,  REWRITE_TYPEVARS);
1799                             bHigh = rewriteQuantifiers(b, HIGH, REWRITE_TYPEVARS);
1800                             bLow  = rewriteQuantifiers(b, LOW,  REWRITE_TYPEVARS);
1801                             lowSub = asSub(bLow, aLow.tsym);
1802                             highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym);
1803                         }
1804                         if (highSub != null) {
1805                             if (!(a.tsym == highSub.tsym && a.tsym == lowSub.tsym)) {
1806                                 Assert.error(a.tsym + " != " + highSub.tsym + " != " + lowSub.tsym);
1807                             }
1808                             if (!disjointTypes(aHigh.allparams(), highSub.allparams())
1809                                 && !disjointTypes(aHigh.allparams(), lowSub.allparams())
1810                                 && !disjointTypes(aLow.allparams(), highSub.allparams())
1811                                 && !disjointTypes(aLow.allparams(), lowSub.allparams())) {
1812                                 if (upcast ? giveWarning(a, b) :
1813                                     giveWarning(b, a))
1814                                     warnStack.head.warn(LintCategory.UNCHECKED);
1815                                 return true;
1816                             }
1817                         }
1818                         if (isReifiable(s))
1819                             return isSubtypeUnchecked(a, b);
1820                         else
1821                             return isSubtypeUnchecked(a, b, warnStack.head);
1822                     }
1823 
1824                     // Sidecast
1825                     if (s.hasTag(CLASS)) {
1826                         if ((s.tsym.flags() & INTERFACE) != 0) {
1827                             return ((t.tsym.flags() & FINAL) == 0)
1828                                 ? sideCast(t, s, warnStack.head)
1829                                 : sideCastFinal(t, s, warnStack.head);
1830                         } else if ((t.tsym.flags() & INTERFACE) != 0) {
1831                             return ((s.tsym.flags() & FINAL) == 0)
1832                                 ? sideCast(t, s, warnStack.head)
1833                                 : sideCastFinal(t, s, warnStack.head);
1834                         } else {
1835                             // unrelated class types
1836                             return false;
1837                         }
1838                     }
1839                 }
1840                 return false;
1841             }
1842 
1843             boolean visitCompoundType(ClassType ct, Type s, boolean reverse) {
1844                 Warner warn = noWarnings;
1845                 for (Type c : directSupertypes(ct)) {
1846                     warn.clear();
1847                     if (reverse ? !isCastable(s, c, warn) : !isCastable(c, s, warn))
1848                         return false;
1849                 }
1850                 if (warn.hasLint(LintCategory.UNCHECKED))
1851                     warnStack.head.warn(LintCategory.UNCHECKED);
1852                 return true;
1853             }
1854 
1855             @Override
1856             public Boolean visitArrayType(ArrayType t, Type s) {
1857                 switch (s.getTag()) {
1858                 case ERROR:
1859                 case BOT:
1860                     return true;
1861                 case TYPEVAR:
1862                     if (isCastable(s, t, noWarnings)) {
1863                         warnStack.head.warn(LintCategory.UNCHECKED);
1864                         return true;
1865                     } else {
1866                         return false;
1867                     }
1868                 case CLASS:
1869                     return isSubtype(t, s);
1870                 case ARRAY:
1871                     if (elemtype(t).isPrimitive() || elemtype(s).isPrimitive()) {
1872                         return elemtype(t).hasTag(elemtype(s).getTag());
1873                     } else {
1874                         return isCastable(elemtype(t), elemtype(s), warnStack.head);
1875                     }
1876                 default:
1877                     return false;
1878                 }
1879             }
1880 
1881             @Override
1882             public Boolean visitTypeVar(TypeVar t, Type s) {
1883                 switch (s.getTag()) {
1884                 case ERROR:
1885                 case BOT:
1886                     return true;
1887                 case TYPEVAR:
1888                     if (isSubtype(t, s)) {
1889                         return true;
1890                     } else if (isCastable(t.getUpperBound(), s, noWarnings)) {
1891                         warnStack.head.warn(LintCategory.UNCHECKED);
1892                         return true;
1893                     } else {
1894                         return false;
1895                     }
1896                 default:
1897                     return isCastable(t.getUpperBound(), s, warnStack.head);
1898                 }
1899             }
1900 
1901             @Override
1902             public Boolean visitErrorType(ErrorType t, Type s) {
1903                 return true;
1904             }
1905         };
1906     // </editor-fold>
1907 
1908     // <editor-fold defaultstate="collapsed" desc="disjointTypes">
1909     public boolean disjointTypes(List<Type> ts, List<Type> ss) {
1910         while (ts.tail != null && ss.tail != null) {
1911             if (disjointType(ts.head, ss.head)) return true;
1912             ts = ts.tail;
1913             ss = ss.tail;
1914         }
1915         return false;
1916     }
1917 
1918     /**
1919      * Two types or wildcards are considered disjoint if it can be
1920      * proven that no type can be contained in both. It is
1921      * conservative in that it is allowed to say that two types are
1922      * not disjoint, even though they actually are.
1923      *
1924      * The type {@code C<X>} is castable to {@code C<Y>} exactly if
1925      * {@code X} and {@code Y} are not disjoint.
1926      */
1927     public boolean disjointType(Type t, Type s) {
1928         return disjointType.visit(t, s);
1929     }
1930     // where
1931         private TypeRelation disjointType = new TypeRelation() {
1932 
1933             private Set<TypePair> cache = new HashSet<>();
1934 
1935             @Override
1936             public Boolean visitType(Type t, Type s) {
1937                 if (s.hasTag(WILDCARD))
1938                     return visit(s, t);
1939                 else
1940                     return notSoftSubtypeRecursive(t, s) || notSoftSubtypeRecursive(s, t);
1941             }
1942 
1943             private boolean isCastableRecursive(Type t, Type s) {
1944                 TypePair pair = new TypePair(t, s);
1945                 if (cache.add(pair)) {
1946                     try {
1947                         return Types.this.isCastable(t, s);
1948                     } finally {
1949                         cache.remove(pair);
1950                     }
1951                 } else {
1952                     return true;
1953                 }
1954             }
1955 
1956             private boolean notSoftSubtypeRecursive(Type t, Type s) {
1957                 TypePair pair = new TypePair(t, s);
1958                 if (cache.add(pair)) {
1959                     try {
1960                         return Types.this.notSoftSubtype(t, s);
1961                     } finally {
1962                         cache.remove(pair);
1963                     }
1964                 } else {
1965                     return false;
1966                 }
1967             }
1968 
1969             @Override
1970             public Boolean visitWildcardType(WildcardType t, Type s) {
1971                 if (t.isUnbound())
1972                     return false;
1973 
1974                 if (!s.hasTag(WILDCARD)) {
1975                     if (t.isExtendsBound())
1976                         return notSoftSubtypeRecursive(s, t.type);
1977                     else
1978                         return notSoftSubtypeRecursive(t.type, s);
1979                 }
1980 
1981                 if (s.isUnbound())
1982                     return false;
1983 
1984                 if (t.isExtendsBound()) {
1985                     if (s.isExtendsBound())
1986                         return !isCastableRecursive(t.type, wildUpperBound(s));
1987                     else if (s.isSuperBound())
1988                         return notSoftSubtypeRecursive(wildLowerBound(s), t.type);
1989                 } else if (t.isSuperBound()) {
1990                     if (s.isExtendsBound())
1991                         return notSoftSubtypeRecursive(t.type, wildUpperBound(s));
1992                 }
1993                 return false;
1994             }
1995         };
1996     // </editor-fold>
1997 
1998     // <editor-fold defaultstate="collapsed" desc="cvarLowerBounds">
1999     public List<Type> cvarLowerBounds(List<Type> ts) {
2000         return ts.map(cvarLowerBoundMapping);
2001     }
2002         private final TypeMapping<Void> cvarLowerBoundMapping = new TypeMapping<Void>() {
2003             @Override
2004             public Type visitCapturedType(CapturedType t, Void _unused) {
2005                 return cvarLowerBound(t);
2006             }
2007         };
2008     // </editor-fold>
2009 
2010     // <editor-fold defaultstate="collapsed" desc="notSoftSubtype">
2011     /**
2012      * This relation answers the question: is impossible that
2013      * something of type `t' can be a subtype of `s'? This is
2014      * different from the question "is `t' not a subtype of `s'?"
2015      * when type variables are involved: Integer is not a subtype of T
2016      * where {@code <T extends Number>} but it is not true that Integer cannot
2017      * possibly be a subtype of T.
2018      */
2019     public boolean notSoftSubtype(Type t, Type s) {
2020         if (t == s) return false;
2021         if (t.hasTag(TYPEVAR)) {
2022             TypeVar tv = (TypeVar) t;
2023             return !isCastable(tv.getUpperBound(),
2024                                relaxBound(s),
2025                                noWarnings);
2026         }
2027         if (!s.hasTag(WILDCARD))
2028             s = cvarUpperBound(s);
2029 
2030         return !isSubtype(t, relaxBound(s));
2031     }
2032 
2033     private Type relaxBound(Type t) {
2034         return (t.hasTag(TYPEVAR)) ?
2035                 rewriteQuantifiers(skipTypeVars(t, false), true, true) :
2036                 t;
2037     }
2038     // </editor-fold>
2039 
2040     // <editor-fold defaultstate="collapsed" desc="isReifiable">
2041     public boolean isReifiable(Type t) {
2042         return isReifiable.visit(t);
2043     }
2044     // where
2045         private UnaryVisitor<Boolean> isReifiable = new UnaryVisitor<Boolean>() {
2046 
2047             public Boolean visitType(Type t, Void ignored) {
2048                 return true;
2049             }
2050 
2051             @Override
2052             public Boolean visitClassType(ClassType t, Void ignored) {
2053                 if (t.isCompound())
2054                     return false;
2055                 else {
2056                     if (!t.isParameterized())
2057                         return true;
2058 
2059                     for (Type param : t.allparams()) {
2060                         if (!param.isUnbound())
2061                             return false;
2062                     }
2063                     return true;
2064                 }
2065             }
2066 
2067             @Override
2068             public Boolean visitArrayType(ArrayType t, Void ignored) {
2069                 return visit(t.elemtype);
2070             }
2071 
2072             @Override
2073             public Boolean visitTypeVar(TypeVar t, Void ignored) {
2074                 return false;
2075             }
2076         };
2077     // </editor-fold>
2078 
2079     // <editor-fold defaultstate="collapsed" desc="Array Utils">
2080     public boolean isArray(Type t) {
2081         while (t.hasTag(WILDCARD))
2082             t = wildUpperBound(t);
2083         return t.hasTag(ARRAY);
2084     }
2085 
2086     /**
2087      * The element type of an array.
2088      */
2089     public Type elemtype(Type t) {
2090         switch (t.getTag()) {
2091         case WILDCARD:
2092             return elemtype(wildUpperBound(t));
2093         case ARRAY:
2094             return ((ArrayType)t).elemtype;
2095         case FORALL:
2096             return elemtype(((ForAll)t).qtype);
2097         case ERROR:
2098             return t;
2099         default:
2100             return null;
2101         }
2102     }
2103 
2104     public Type elemtypeOrType(Type t) {
2105         Type elemtype = elemtype(t);
2106         return elemtype != null ?
2107             elemtype :
2108             t;
2109     }
2110 
2111     /**
2112      * Mapping to take element type of an arraytype
2113      */
2114     private TypeMapping<Void> elemTypeFun = new TypeMapping<Void>() {
2115         @Override
2116         public Type visitArrayType(ArrayType t, Void _unused) {
2117             return t.elemtype;
2118         }
2119 
2120         @Override
2121         public Type visitTypeVar(TypeVar t, Void _unused) {
2122             return visit(skipTypeVars(t, false));
2123         }
2124     };
2125 
2126     /**
2127      * The number of dimensions of an array type.
2128      */
2129     public int dimensions(Type t) {
2130         int result = 0;
2131         while (t.hasTag(ARRAY)) {
2132             result++;
2133             t = elemtype(t);
2134         }
2135         return result;
2136     }
2137 
2138     /**
2139      * Returns an ArrayType with the component type t
2140      *
2141      * @param t The component type of the ArrayType
2142      * @return the ArrayType for the given component
2143      */
2144     public ArrayType makeArrayType(Type t) {




2145         if (t.hasTag(VOID) || t.hasTag(PACKAGE)) {
2146             Assert.error("Type t must not be a VOID or PACKAGE type, " + t.toString());
2147         }
2148         return new ArrayType(t, syms.arrayClass);




2149     }
2150     // </editor-fold>
2151 
2152     // <editor-fold defaultstate="collapsed" desc="asSuper">
2153     /**
2154      * Return the (most specific) base type of t that starts with the
2155      * given symbol.  If none exists, return null.
2156      *
2157      * Caveat Emptor: Since javac represents the class of all arrays with a singleton
2158      * symbol Symtab.arrayClass, which by being a singleton cannot hold any discriminant,
2159      * this method could yield surprising answers when invoked on arrays. For example when
2160      * invoked with t being byte [] and sym being t.sym itself, asSuper would answer null.
2161      *
2162      * @param t a type
2163      * @param sym a symbol
2164      */
2165     public Type asSuper(Type t, Symbol sym) {
2166         /* Some examples:
2167          *
2168          * (Enum<E>, Comparable) => Comparable<E>
2169          * (c.s.s.d.AttributeTree.ValueKind, Enum) => Enum<c.s.s.d.AttributeTree.ValueKind>
2170          * (c.s.s.t.ExpressionTree, c.s.s.t.Tree) => c.s.s.t.Tree
2171          * (j.u.List<capture#160 of ? extends c.s.s.d.DocTree>, Iterable) =>
2172          *     Iterable<capture#160 of ? extends c.s.s.d.DocTree>
2173          */
2174         if (sym.type == syms.objectType) { //optimization
2175             return syms.objectType;
2176         }
2177         return asSuper.visit(t, sym);
2178     }
2179     // where
2180         private SimpleVisitor<Type,Symbol> asSuper = new SimpleVisitor<Type,Symbol>() {
2181 
2182             private Set<Symbol> seenTypes = new HashSet<>();
2183 
2184             public Type visitType(Type t, Symbol sym) {
2185                 return null;
2186             }
2187 
2188             @Override
2189             public Type visitClassType(ClassType t, Symbol sym) {
2190                 if (t.tsym == sym)
2191                     return t;
2192 
2193                 Symbol c = t.tsym;
2194                 if (!seenTypes.add(c)) {
2195                     return null;
2196                 }
2197                 try {
2198                     Type st = supertype(t);
2199                     if (st.hasTag(CLASS) || st.hasTag(TYPEVAR)) {
2200                         Type x = asSuper(st, sym);
2201                         if (x != null)
2202                             return x;
2203                     }
2204                     if ((sym.flags() & INTERFACE) != 0) {
2205                         for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
2206                             if (!l.head.hasTag(ERROR)) {
2207                                 Type x = asSuper(l.head, sym);
2208                                 if (x != null)
2209                                     return x;
2210                             }
2211                         }
2212                     }
2213                     return null;
2214                 } finally {
2215                     seenTypes.remove(c);
2216                 }
2217             }
2218 
2219             @Override
2220             public Type visitArrayType(ArrayType t, Symbol sym) {
2221                 return isSubtype(t, sym.type) ? sym.type : null;
2222             }
2223 
2224             @Override
2225             public Type visitTypeVar(TypeVar t, Symbol sym) {
2226                 if (t.tsym == sym)
2227                     return t;
2228                 else
2229                     return asSuper(t.getUpperBound(), sym);
2230             }
2231 
2232             @Override
2233             public Type visitErrorType(ErrorType t, Symbol sym) {
2234                 return t;
2235             }
2236         };
2237 
2238     /**
2239      * Return the base type of t or any of its outer types that starts
2240      * with the given symbol.  If none exists, return null.
2241      *
2242      * @param t a type
2243      * @param sym a symbol
2244      */
2245     public Type asOuterSuper(Type t, Symbol sym) {
2246         switch (t.getTag()) {
2247         case CLASS:
2248             do {
2249                 Type s = asSuper(t, sym);
2250                 if (s != null) return s;
2251                 t = t.getEnclosingType();
2252             } while (t.hasTag(CLASS));
2253             return null;
2254         case ARRAY:
2255             return isSubtype(t, sym.type) ? sym.type : null;
2256         case TYPEVAR:
2257             return asSuper(t, sym);
2258         case ERROR:
2259             return t;
2260         default:
2261             return null;
2262         }
2263     }
2264 
2265     /**
2266      * Return the base type of t or any of its enclosing types that
2267      * starts with the given symbol.  If none exists, return null.
2268      *
2269      * @param t a type
2270      * @param sym a symbol
2271      */
2272     public Type asEnclosingSuper(Type t, Symbol sym) {
2273         switch (t.getTag()) {
2274         case CLASS:
2275             do {
2276                 Type s = asSuper(t, sym);
2277                 if (s != null) return s;
2278                 Type outer = t.getEnclosingType();
2279                 t = (outer.hasTag(CLASS)) ? outer :
2280                     (t.tsym.owner.enclClass() != null) ? t.tsym.owner.enclClass().type :
2281                     Type.noType;
2282             } while (t.hasTag(CLASS));
2283             return null;
2284         case ARRAY:
2285             return isSubtype(t, sym.type) ? sym.type : null;
2286         case TYPEVAR:
2287             return asSuper(t, sym);
2288         case ERROR:
2289             return t;
2290         default:
2291             return null;
2292         }
2293     }
2294     // </editor-fold>
2295 
2296     // <editor-fold defaultstate="collapsed" desc="memberType">
2297     /**
2298      * The type of given symbol, seen as a member of t.
2299      *
2300      * @param t a type
2301      * @param sym a symbol
2302      */
2303     public Type memberType(Type t, Symbol sym) {
2304         return (sym.flags() & STATIC) != 0
2305             ? sym.type
2306             : memberType.visit(t, sym);
2307         }
2308     // where
2309         private SimpleVisitor<Type,Symbol> memberType = new SimpleVisitor<Type,Symbol>() {
2310 
2311             public Type visitType(Type t, Symbol sym) {
2312                 return sym.type;
2313             }
2314 
2315             @Override
2316             public Type visitWildcardType(WildcardType t, Symbol sym) {
2317                 return memberType(wildUpperBound(t), sym);
2318             }
2319 
2320             @Override
2321             public Type visitClassType(ClassType t, Symbol sym) {
2322                 Symbol owner = sym.owner;
2323                 long flags = sym.flags();
2324                 if (((flags & STATIC) == 0) && owner.type.isParameterized()) {
2325                     Type base = asOuterSuper(t, owner);
2326                     //if t is an intersection type T = CT & I1 & I2 ... & In
2327                     //its supertypes CT, I1, ... In might contain wildcards
2328                     //so we need to go through capture conversion
2329                     base = t.isCompound() ? capture(base) : base;
2330                     if (base != null) {
2331                         List<Type> ownerParams = owner.type.allparams();
2332                         List<Type> baseParams = base.allparams();
2333                         if (ownerParams.nonEmpty()) {
2334                             if (baseParams.isEmpty()) {
2335                                 // then base is a raw type
2336                                 return erasure(sym.type);
2337                             } else {
2338                                 return subst(sym.type, ownerParams, baseParams);
2339                             }
2340                         }
2341                     }
2342                 }
2343                 return sym.type;
2344             }
2345 
2346             @Override
2347             public Type visitTypeVar(TypeVar t, Symbol sym) {
2348                 return memberType(t.getUpperBound(), sym);
2349             }
2350 
2351             @Override
2352             public Type visitErrorType(ErrorType t, Symbol sym) {
2353                 return t;
2354             }
2355         };
2356     // </editor-fold>
2357 
2358     // <editor-fold defaultstate="collapsed" desc="isAssignable">
2359     public boolean isAssignable(Type t, Type s) {
2360         return isAssignable(t, s, noWarnings);
2361     }
2362 
2363     /**
2364      * Is t assignable to s?<br>
2365      * Equivalent to subtype except for constant values and raw
2366      * types.<br>
2367      * (not defined for Method and ForAll types)
2368      */
2369     public boolean isAssignable(Type t, Type s, Warner warn) {
2370         if (t.hasTag(ERROR))
2371             return true;
2372         if (t.getTag().isSubRangeOf(INT) && t.constValue() != null) {
2373             int value = ((Number)t.constValue()).intValue();
2374             switch (s.getTag()) {
2375             case BYTE:
2376             case CHAR:
2377             case SHORT:
2378             case INT:
2379                 if (s.getTag().checkRange(value))
2380                     return true;
2381                 break;
2382             case CLASS:
2383                 switch (unboxedType(s).getTag()) {
2384                 case BYTE:
2385                 case CHAR:
2386                 case SHORT:
2387                     return isAssignable(t, unboxedType(s), warn);
2388                 }
2389                 break;
2390             }
2391         }
2392         return isConvertible(t, s, warn);
2393     }
2394     // </editor-fold>
2395 
2396     // <editor-fold defaultstate="collapsed" desc="erasure">
2397     /**
2398      * The erasure of t {@code |t|} -- the type that results when all
2399      * type parameters in t are deleted.
2400      */
2401     public Type erasure(Type t) {
2402         return eraseNotNeeded(t) ? t : erasure(t, false);
2403     }
2404     //where
2405     private boolean eraseNotNeeded(Type t) {
2406         // We don't want to erase primitive types and String type as that
2407         // operation is idempotent. Also, erasing these could result in loss
2408         // of information such as constant values attached to such types.
2409         return (t.isPrimitive()) || (syms.stringType.tsym == t.tsym);
2410     }
2411 
2412     private Type erasure(Type t, boolean recurse) {
2413         if (t.isPrimitive()) {
2414             return t; /* fast special case */
2415         } else {
2416             Type out = erasure.visit(t, recurse);
2417             return out;
2418         }
2419     }
2420     // where
2421         private TypeMapping<Boolean> erasure = new StructuralTypeMapping<Boolean>() {
2422             @SuppressWarnings("fallthrough")
2423             private Type combineMetadata(final Type s,
2424                                          final Type t) {
2425                 if (t.getMetadata().nonEmpty()) {
2426                     switch (s.getTag()) {
2427                         case CLASS:
2428                             if (s instanceof UnionClassType ||
2429                                 s instanceof IntersectionClassType) {
2430                                 return s;
2431                             }
2432                             //fall-through
2433                         case BYTE, CHAR, SHORT, LONG, FLOAT, INT, DOUBLE, BOOLEAN,
2434                              ARRAY, MODULE, TYPEVAR, WILDCARD, BOT:
2435                             return s.dropMetadata(Annotations.class);
2436                         case VOID, METHOD, PACKAGE, FORALL, DEFERRED,
2437                              NONE, ERROR, UNDETVAR, UNINITIALIZED_THIS,
2438                              UNINITIALIZED_OBJECT:
2439                             return s;
2440                         default:
2441                             throw new AssertionError(s.getTag().name());
2442                     }
2443                 } else {
2444                     return s;
2445                 }
2446             }
2447 
2448             public Type visitType(Type t, Boolean recurse) {
2449                 if (t.isPrimitive())
2450                     return t; /*fast special case*/
2451                 else {
2452                     //other cases already handled
2453                     return combineMetadata(t, t);
2454                 }
2455             }
2456 
2457             @Override
2458             public Type visitWildcardType(WildcardType t, Boolean recurse) {
2459                 Type erased = erasure(wildUpperBound(t), recurse);
2460                 return combineMetadata(erased, t);
2461             }
2462 
2463             @Override
2464             public Type visitClassType(ClassType t, Boolean recurse) {
2465                 Type erased = t.tsym.erasure(Types.this);
2466                 if (recurse) {
2467                     erased = new ErasedClassType(erased.getEnclosingType(),erased.tsym,
2468                             t.dropMetadata(Annotations.class).getMetadata());
2469                     return erased;
2470                 } else {
2471                     return combineMetadata(erased, t);
2472                 }
2473             }
2474 
2475             @Override
2476             public Type visitTypeVar(TypeVar t, Boolean recurse) {
2477                 Type erased = erasure(t.getUpperBound(), recurse);
2478                 return combineMetadata(erased, t);
2479             }
2480         };
2481 
2482     public List<Type> erasure(List<Type> ts) {
2483         return erasure.visit(ts, false);
2484     }
2485 
2486     public Type erasureRecursive(Type t) {
2487         return erasure(t, true);
2488     }
2489 
2490     public List<Type> erasureRecursive(List<Type> ts) {
2491         return erasure.visit(ts, true);
2492     }
2493     // </editor-fold>
2494 
2495     // <editor-fold defaultstate="collapsed" desc="makeIntersectionType">
2496     /**
2497      * Make an intersection type from non-empty list of types.  The list should be ordered according to
2498      * {@link TypeSymbol#precedes(TypeSymbol, Types)}. Note that this might cause a symbol completion.
2499      * Hence, this version of makeIntersectionType may not be called during a classfile read.
2500      *
2501      * @param bounds    the types from which the intersection type is formed
2502      */
2503     public IntersectionClassType makeIntersectionType(List<Type> bounds) {
2504         return makeIntersectionType(bounds, bounds.head.tsym.isInterface());
2505     }
2506 
2507     /**
2508      * Make an intersection type from non-empty list of types.  The list should be ordered according to
2509      * {@link TypeSymbol#precedes(TypeSymbol, Types)}. This does not cause symbol completion as
2510      * an extra parameter indicates as to whether all bounds are interfaces - in which case the
2511      * supertype is implicitly assumed to be 'Object'.
2512      *
2513      * @param bounds        the types from which the intersection type is formed
2514      * @param allInterfaces are all bounds interface types?
2515      */
2516     public IntersectionClassType makeIntersectionType(List<Type> bounds, boolean allInterfaces) {
2517         Assert.check(bounds.nonEmpty());
2518         Type firstExplicitBound = bounds.head;
2519         if (allInterfaces) {
2520             bounds = bounds.prepend(syms.objectType);
2521         }
2522         ClassSymbol bc =
2523             new ClassSymbol(ABSTRACT|PUBLIC|SYNTHETIC|COMPOUND|ACYCLIC,
2524                             Type.moreInfo
2525                                 ? names.fromString(bounds.toString())
2526                                 : names.empty,
2527                             null,
2528                             syms.noSymbol);
2529         IntersectionClassType intersectionType = new IntersectionClassType(bounds, bc, allInterfaces);
2530         bc.type = intersectionType;
2531         bc.erasure_field = (bounds.head.hasTag(TYPEVAR)) ?
2532                 syms.objectType : // error condition, recover
2533                 erasure(firstExplicitBound);
2534         bc.members_field = WriteableScope.create(bc);
2535         return intersectionType;
2536     }
2537     // </editor-fold>
2538 
2539     // <editor-fold defaultstate="collapsed" desc="supertype">
2540     public Type supertype(Type t) {
2541         return supertype.visit(t);
2542     }
2543     // where
2544         private UnaryVisitor<Type> supertype = new UnaryVisitor<Type>() {
2545 
2546             public Type visitType(Type t, Void ignored) {
2547                 // A note on wildcards: there is no good way to
2548                 // determine a supertype for a lower-bounded wildcard.
2549                 return Type.noType;
2550             }
2551 
2552             @Override
2553             public Type visitClassType(ClassType t, Void ignored) {
2554                 if (t.supertype_field == null) {
2555                     Type supertype = ((ClassSymbol)t.tsym).getSuperclass();
2556                     // An interface has no superclass; its supertype is Object.
2557                     if (t.isInterface())
2558                         supertype = ((ClassType)t.tsym.type).supertype_field;
2559                     if (t.supertype_field == null) {
2560                         List<Type> actuals = classBound(t).allparams();
2561                         List<Type> formals = t.tsym.type.allparams();
2562                         if (t.hasErasedSupertypes()) {
2563                             t.supertype_field = erasureRecursive(supertype);
2564                         } else if (formals.nonEmpty()) {
2565                             t.supertype_field = subst(supertype, formals, actuals);
2566                         }
2567                         else {
2568                             t.supertype_field = supertype;
2569                         }
2570                     }
2571                 }
2572                 return t.supertype_field;
2573             }
2574 
2575             /**
2576              * The supertype is always a class type. If the type
2577              * variable's bounds start with a class type, this is also
2578              * the supertype.  Otherwise, the supertype is
2579              * java.lang.Object.
2580              */
2581             @Override
2582             public Type visitTypeVar(TypeVar t, Void ignored) {
2583                 if (t.getUpperBound().hasTag(TYPEVAR) ||
2584                     (!t.getUpperBound().isCompound() && !t.getUpperBound().isInterface())) {
2585                     return t.getUpperBound();
2586                 } else {
2587                     return supertype(t.getUpperBound());
2588                 }
2589             }
2590 
2591             @Override
2592             public Type visitArrayType(ArrayType t, Void ignored) {
2593                 if (t.elemtype.isPrimitive() || isSameType(t.elemtype, syms.objectType))
2594                     return arraySuperType();
2595                 else
2596                     return new ArrayType(supertype(t.elemtype), t.tsym);
2597             }
2598 
2599             @Override
2600             public Type visitErrorType(ErrorType t, Void ignored) {
2601                 return Type.noType;
2602             }
2603         };
2604     // </editor-fold>
2605 
2606     // <editor-fold defaultstate="collapsed" desc="interfaces">
2607     /**
2608      * Return the interfaces implemented by this class.
2609      */
2610     public List<Type> interfaces(Type t) {
2611         return interfaces.visit(t);
2612     }
2613     // where
2614         private UnaryVisitor<List<Type>> interfaces = new UnaryVisitor<List<Type>>() {
2615 
2616             public List<Type> visitType(Type t, Void ignored) {
2617                 return List.nil();
2618             }
2619 
2620             @Override
2621             public List<Type> visitClassType(ClassType t, Void ignored) {
2622                 if (t.interfaces_field == null) {
2623                     List<Type> interfaces = ((ClassSymbol)t.tsym).getInterfaces();
2624                     if (t.interfaces_field == null) {
2625                         // If t.interfaces_field is null, then t must
2626                         // be a parameterized type (not to be confused
2627                         // with a generic type declaration).
2628                         // Terminology:
2629                         //    Parameterized type: List<String>
2630                         //    Generic type declaration: class List<E> { ... }
2631                         // So t corresponds to List<String> and
2632                         // t.tsym.type corresponds to List<E>.
2633                         // The reason t must be parameterized type is
2634                         // that completion will happen as a side
2635                         // effect of calling
2636                         // ClassSymbol.getInterfaces.  Since
2637                         // t.interfaces_field is null after
2638                         // completion, we can assume that t is not the
2639                         // type of a class/interface declaration.
2640                         Assert.check(t != t.tsym.type, t);
2641                         List<Type> actuals = t.allparams();
2642                         List<Type> formals = t.tsym.type.allparams();
2643                         if (t.hasErasedSupertypes()) {
2644                             t.interfaces_field = erasureRecursive(interfaces);
2645                         } else if (formals.nonEmpty()) {
2646                             t.interfaces_field = subst(interfaces, formals, actuals);
2647                         }
2648                         else {
2649                             t.interfaces_field = interfaces;
2650                         }
2651                     }
2652                 }
2653                 return t.interfaces_field;
2654             }
2655 
2656             @Override
2657             public List<Type> visitTypeVar(TypeVar t, Void ignored) {
2658                 if (t.getUpperBound().isCompound())
2659                     return interfaces(t.getUpperBound());
2660 
2661                 if (t.getUpperBound().isInterface())
2662                     return List.of(t.getUpperBound());
2663 
2664                 return List.nil();
2665             }
2666         };
2667 
2668     public List<Type> directSupertypes(Type t) {
2669         return directSupertypes.visit(t);
2670     }
2671     // where
2672         private final UnaryVisitor<List<Type>> directSupertypes = new UnaryVisitor<List<Type>>() {
2673 
2674             public List<Type> visitType(final Type type, final Void ignored) {
2675                 if (!type.isIntersection()) {
2676                     final Type sup = supertype(type);
2677                     return (sup == Type.noType || sup == type || sup == null)
2678                         ? interfaces(type)
2679                         : interfaces(type).prepend(sup);
2680                 } else {
2681                     return ((IntersectionClassType)type).getExplicitComponents();
2682                 }
2683             }
2684         };
2685 
2686     public boolean isDirectSuperInterface(TypeSymbol isym, TypeSymbol origin) {
2687         for (Type i2 : interfaces(origin.type)) {
2688             if (isym == i2.tsym) return true;
2689         }
2690         return false;
2691     }
2692     // </editor-fold>
2693 
2694     // <editor-fold defaultstate="collapsed" desc="isDerivedRaw">
2695     Map<Type,Boolean> isDerivedRawCache = new HashMap<>();
2696 
2697     public boolean isDerivedRaw(Type t) {
2698         Boolean result = isDerivedRawCache.get(t);
2699         if (result == null) {
2700             result = isDerivedRawInternal(t);
2701             isDerivedRawCache.put(t, result);
2702         }
2703         return result;
2704     }
2705 
2706     public boolean isDerivedRawInternal(Type t) {
2707         if (t.isErroneous())
2708             return false;
2709         return
2710             t.isRaw() ||
2711             supertype(t) != Type.noType && isDerivedRaw(supertype(t)) ||
2712             isDerivedRaw(interfaces(t));
2713     }
2714 
2715     public boolean isDerivedRaw(List<Type> ts) {
2716         List<Type> l = ts;
2717         while (l.nonEmpty() && !isDerivedRaw(l.head)) l = l.tail;
2718         return l.nonEmpty();
2719     }
2720     // </editor-fold>
2721 
2722     // <editor-fold defaultstate="collapsed" desc="setBounds">
2723     /**
2724      * Same as {@link Types#setBounds(TypeVar, List, boolean)}, except that third parameter is computed directly,
2725      * as follows: if all all bounds are interface types, the computed supertype is Object,otherwise
2726      * the supertype is simply left null (in this case, the supertype is assumed to be the head of
2727      * the bound list passed as second argument). Note that this check might cause a symbol completion.
2728      * Hence, this version of setBounds may not be called during a classfile read.
2729      *
2730      * @param t         a type variable
2731      * @param bounds    the bounds, must be nonempty
2732      */
2733     public void setBounds(TypeVar t, List<Type> bounds) {
2734         setBounds(t, bounds, bounds.head.tsym.isInterface());
2735     }
2736 
2737     /**
2738      * Set the bounds field of the given type variable to reflect a (possibly multiple) list of bounds.
2739      * This does not cause symbol completion as an extra parameter indicates as to whether all bounds
2740      * are interfaces - in which case the supertype is implicitly assumed to be 'Object'.
2741      *
2742      * @param t             a type variable
2743      * @param bounds        the bounds, must be nonempty
2744      * @param allInterfaces are all bounds interface types?
2745      */
2746     public void setBounds(TypeVar t, List<Type> bounds, boolean allInterfaces) {
2747         t.setUpperBound( bounds.tail.isEmpty() ?
2748                 bounds.head :
2749                 makeIntersectionType(bounds, allInterfaces) );
2750         t.rank_field = -1;
2751     }
2752     // </editor-fold>
2753 
2754     // <editor-fold defaultstate="collapsed" desc="getBounds">
2755     /**
2756      * Return list of bounds of the given type variable.
2757      */
2758     public List<Type> getBounds(TypeVar t) {
2759         if (t.getUpperBound().hasTag(NONE))
2760             return List.nil();
2761         else if (t.getUpperBound().isErroneous() || !t.getUpperBound().isCompound())
2762             return List.of(t.getUpperBound());
2763         else if ((erasure(t).tsym.flags() & INTERFACE) == 0)
2764             return interfaces(t).prepend(supertype(t));
2765         else
2766             // No superclass was given in bounds.
2767             // In this case, supertype is Object, erasure is first interface.
2768             return interfaces(t);
2769     }
2770     // </editor-fold>
2771 
2772     // <editor-fold defaultstate="collapsed" desc="classBound">
2773     /**
2774      * If the given type is a (possibly selected) type variable,
2775      * return the bounding class of this type, otherwise return the
2776      * type itself.
2777      */
2778     public Type classBound(Type t) {
2779         return classBound.visit(t);
2780     }
2781     // where
2782         private UnaryVisitor<Type> classBound = new UnaryVisitor<Type>() {
2783 
2784             public Type visitType(Type t, Void ignored) {
2785                 return t;
2786             }
2787 
2788             @Override
2789             public Type visitClassType(ClassType t, Void ignored) {
2790                 Type outer1 = classBound(t.getEnclosingType());
2791                 if (outer1 != t.getEnclosingType())
2792                     return new ClassType(outer1, t.getTypeArguments(), t.tsym,
2793                                          t.getMetadata());
2794                 else
2795                     return t;
2796             }
2797 
2798             @Override
2799             public Type visitTypeVar(TypeVar t, Void ignored) {
2800                 return classBound(supertype(t));
2801             }
2802 
2803             @Override
2804             public Type visitErrorType(ErrorType t, Void ignored) {
2805                 return t;
2806             }
2807         };
2808     // </editor-fold>
2809 
2810     // <editor-fold defaultstate="collapsed" desc="subsignature / override equivalence">
2811     /**
2812      * Returns true iff the first signature is a <em>subsignature</em>
2813      * of the other.  This is <b>not</b> an equivalence
2814      * relation.
2815      *
2816      * @jls 8.4.2 Method Signature
2817      * @see #overrideEquivalent(Type t, Type s)
2818      * @param t first signature (possibly raw).
2819      * @param s second signature (could be subjected to erasure).
2820      * @return true if t is a subsignature of s.
2821      */
2822     public boolean isSubSignature(Type t, Type s) {
2823         return hasSameArgs(t, s, true) || hasSameArgs(t, erasure(s), true);
2824     }
2825 
2826     /**
2827      * Returns true iff these signatures are related by <em>override
2828      * equivalence</em>.  This is the natural extension of
2829      * isSubSignature to an equivalence relation.
2830      *
2831      * @jls 8.4.2 Method Signature
2832      * @see #isSubSignature(Type t, Type s)
2833      * @param t a signature (possible raw, could be subjected to
2834      * erasure).
2835      * @param s a signature (possible raw, could be subjected to
2836      * erasure).
2837      * @return true if either argument is a subsignature of the other.
2838      */
2839     public boolean overrideEquivalent(Type t, Type s) {
2840         return hasSameArgs(t, s) ||
2841             hasSameArgs(t, erasure(s)) || hasSameArgs(erasure(t), s);
2842     }
2843 
2844     public boolean overridesObjectMethod(TypeSymbol origin, Symbol msym) {
2845         for (Symbol sym : syms.objectType.tsym.members().getSymbolsByName(msym.name)) {
2846             if (msym.overrides(sym, origin, Types.this, true)) {
2847                 return true;
2848             }
2849         }
2850         return false;
2851     }
2852 
2853     /**
2854      * This enum defines the strategy for implementing most specific return type check
2855      * during the most specific and functional interface checks.
2856      */
2857     public enum MostSpecificReturnCheck {
2858         /**
2859          * Return r1 is more specific than r2 if {@code r1 <: r2}. Extra care required for (i) handling
2860          * method type variables (if either method is generic) and (ii) subtyping should be replaced
2861          * by type-equivalence for primitives. This is essentially an inlined version of
2862          * {@link Types#resultSubtype(Type, Type, Warner)}, where the assignability check has been
2863          * replaced with a strict subtyping check.
2864          */
2865         BASIC() {
2866             @Override
2867             public boolean test(Type mt1, Type mt2, Types types) {
2868                 List<Type> tvars = mt1.getTypeArguments();
2869                 List<Type> svars = mt2.getTypeArguments();
2870                 Type t = mt1.getReturnType();
2871                 Type s = types.subst(mt2.getReturnType(), svars, tvars);
2872                 return types.isSameType(t, s) ||
2873                     !t.isPrimitive() &&
2874                     !s.isPrimitive() &&
2875                     types.isSubtype(t, s);
2876             }
2877         },
2878         /**
2879          * Return r1 is more specific than r2 if r1 is return-type-substitutable for r2.
2880          */
2881         RTS() {
2882             @Override
2883             public boolean test(Type mt1, Type mt2, Types types) {
2884                 return types.returnTypeSubstitutable(mt1, mt2);
2885             }
2886         };
2887 
2888         public abstract boolean test(Type mt1, Type mt2, Types types);
2889     }
2890 
2891     /**
2892      * Merge multiple abstract methods. The preferred method is a method that is a subsignature
2893      * of all the other signatures and whose return type is more specific {@link MostSpecificReturnCheck}.
2894      * The resulting preferred method has a throws clause that is the intersection of the merged
2895      * methods' clauses.
2896      */
2897     public Optional<Symbol> mergeAbstracts(List<Symbol> ambiguousInOrder, Type site, boolean sigCheck) {
2898         //first check for preconditions
2899         boolean shouldErase = false;
2900         List<Type> erasedParams = ambiguousInOrder.head.erasure(this).getParameterTypes();
2901         for (Symbol s : ambiguousInOrder) {
2902             if ((s.flags() & ABSTRACT) == 0 ||
2903                     (sigCheck && !isSameTypes(erasedParams, s.erasure(this).getParameterTypes()))) {
2904                 return Optional.empty();
2905             } else if (s.type.hasTag(FORALL)) {
2906                 shouldErase = true;
2907             }
2908         }
2909         //then merge abstracts
2910         for (MostSpecificReturnCheck mostSpecificReturnCheck : MostSpecificReturnCheck.values()) {
2911             outer: for (Symbol s : ambiguousInOrder) {
2912                 Type mt = memberType(site, s);
2913                 List<Type> allThrown = mt.getThrownTypes();
2914                 for (Symbol s2 : ambiguousInOrder) {
2915                     if (s != s2) {
2916                         Type mt2 = memberType(site, s2);
2917                         if (!isSubSignature(mt, mt2) ||
2918                                 !mostSpecificReturnCheck.test(mt, mt2, this)) {
2919                             //ambiguity cannot be resolved
2920                             continue outer;
2921                         } else {
2922                             List<Type> thrownTypes2 = mt2.getThrownTypes();
2923                             if (!mt.hasTag(FORALL) && shouldErase) {
2924                                 thrownTypes2 = erasure(thrownTypes2);
2925                             } else if (mt.hasTag(FORALL)) {
2926                                 //subsignature implies that if most specific is generic, then all other
2927                                 //methods are too
2928                                 Assert.check(mt2.hasTag(FORALL));
2929                                 // if both are generic methods, adjust thrown types ahead of intersection computation
2930                                 thrownTypes2 = subst(thrownTypes2, mt2.getTypeArguments(), mt.getTypeArguments());
2931                             }
2932                             allThrown = chk.intersect(allThrown, thrownTypes2);
2933                         }
2934                     }
2935                 }
2936                 return (allThrown == mt.getThrownTypes()) ?
2937                         Optional.of(s) :
2938                         Optional.of(new MethodSymbol(
2939                                 s.flags(),
2940                                 s.name,
2941                                 createMethodTypeWithThrown(s.type, allThrown),
2942                                 s.owner) {
2943                             @Override
2944                             public Symbol baseSymbol() {
2945                                 return s;
2946                             }
2947                         });
2948             }
2949         }
2950         return Optional.empty();
2951     }
2952 
2953     // <editor-fold defaultstate="collapsed" desc="Determining method implementation in given site">
2954     class ImplementationCache {
2955 
2956         private WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>> _map = new WeakHashMap<>();
2957 
2958         class Entry {
2959             final MethodSymbol cachedImpl;
2960             final Predicate<Symbol> implFilter;
2961             final boolean checkResult;
2962             final int prevMark;
2963 
2964             public Entry(MethodSymbol cachedImpl,
2965                     Predicate<Symbol> scopeFilter,
2966                     boolean checkResult,
2967                     int prevMark) {
2968                 this.cachedImpl = cachedImpl;
2969                 this.implFilter = scopeFilter;
2970                 this.checkResult = checkResult;
2971                 this.prevMark = prevMark;
2972             }
2973 
2974             boolean matches(Predicate<Symbol> scopeFilter, boolean checkResult, int mark) {
2975                 return this.implFilter == scopeFilter &&
2976                         this.checkResult == checkResult &&
2977                         this.prevMark == mark;
2978             }
2979         }
2980 
2981         MethodSymbol get(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Predicate<Symbol> implFilter) {
2982             SoftReference<Map<TypeSymbol, Entry>> ref_cache = _map.get(ms);
2983             Map<TypeSymbol, Entry> cache = ref_cache != null ? ref_cache.get() : null;
2984             if (cache == null) {
2985                 cache = new HashMap<>();
2986                 _map.put(ms, new SoftReference<>(cache));
2987             }
2988             Entry e = cache.get(origin);
2989             CompoundScope members = membersClosure(origin.type, true);
2990             if (e == null ||
2991                     !e.matches(implFilter, checkResult, members.getMark())) {
2992                 MethodSymbol impl = implementationInternal(ms, origin, checkResult, implFilter);
2993                 cache.put(origin, new Entry(impl, implFilter, checkResult, members.getMark()));
2994                 return impl;
2995             }
2996             else {
2997                 return e.cachedImpl;
2998             }
2999         }
3000 
3001         private MethodSymbol implementationInternal(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Predicate<Symbol> implFilter) {
3002             for (Type t = origin.type; t.hasTag(CLASS) || t.hasTag(TYPEVAR); t = supertype(t)) {
3003                 t = skipTypeVars(t, false);
3004                 TypeSymbol c = t.tsym;
3005                 Symbol bestSoFar = null;
3006                 for (Symbol sym : c.members().getSymbolsByName(ms.name, implFilter)) {
3007                     if (sym != null && sym.overrides(ms, origin, Types.this, checkResult)) {
3008                         bestSoFar = sym;
3009                         if ((sym.flags() & ABSTRACT) == 0) {
3010                             //if concrete impl is found, exit immediately
3011                             break;
3012                         }
3013                     }
3014                 }
3015                 if (bestSoFar != null) {
3016                     //return either the (only) concrete implementation or the first abstract one
3017                     return (MethodSymbol)bestSoFar;
3018                 }
3019             }
3020             return null;
3021         }
3022     }
3023 
3024     private ImplementationCache implCache = new ImplementationCache();
3025 
3026     public MethodSymbol implementation(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Predicate<Symbol> implFilter) {
3027         return implCache.get(ms, origin, checkResult, implFilter);
3028     }
3029     // </editor-fold>
3030 
3031     // <editor-fold defaultstate="collapsed" desc="compute transitive closure of all members in given site">
3032     class MembersClosureCache extends SimpleVisitor<Scope.CompoundScope, Void> {
3033 
3034         private Map<TypeSymbol, CompoundScope> _map = new HashMap<>();
3035 
3036         Set<TypeSymbol> seenTypes = new HashSet<>();
3037 
3038         class MembersScope extends CompoundScope {
3039 
3040             CompoundScope scope;
3041 
3042             public MembersScope(CompoundScope scope) {
3043                 super(scope.owner);
3044                 this.scope = scope;
3045             }
3046 
3047             Predicate<Symbol> combine(Predicate<Symbol> sf) {
3048                 return s -> !s.owner.isInterface() && (sf == null || sf.test(s));
3049             }
3050 
3051             @Override
3052             public Iterable<Symbol> getSymbols(Predicate<Symbol> sf, LookupKind lookupKind) {
3053                 return scope.getSymbols(combine(sf), lookupKind);
3054             }
3055 
3056             @Override
3057             public Iterable<Symbol> getSymbolsByName(Name name, Predicate<Symbol> sf, LookupKind lookupKind) {
3058                 return scope.getSymbolsByName(name, combine(sf), lookupKind);
3059             }
3060 
3061             @Override
3062             public int getMark() {
3063                 return scope.getMark();
3064             }
3065         }
3066 
3067         CompoundScope nilScope;
3068 
3069         /** members closure visitor methods **/
3070 
3071         public CompoundScope visitType(Type t, Void _unused) {
3072             if (nilScope == null) {
3073                 nilScope = new CompoundScope(syms.noSymbol);
3074             }
3075             return nilScope;
3076         }
3077 
3078         @Override
3079         public CompoundScope visitClassType(ClassType t, Void _unused) {
3080             if (!seenTypes.add(t.tsym)) {
3081                 //this is possible when an interface is implemented in multiple
3082                 //superclasses, or when a class hierarchy is circular - in such
3083                 //cases we don't need to recurse (empty scope is returned)
3084                 return new CompoundScope(t.tsym);
3085             }
3086             try {
3087                 seenTypes.add(t.tsym);
3088                 ClassSymbol csym = (ClassSymbol)t.tsym;
3089                 CompoundScope membersClosure = _map.get(csym);
3090                 if (membersClosure == null) {
3091                     membersClosure = new CompoundScope(csym);
3092                     for (Type i : interfaces(t)) {
3093                         membersClosure.prependSubScope(visit(i, null));
3094                     }
3095                     membersClosure.prependSubScope(visit(supertype(t), null));
3096                     membersClosure.prependSubScope(csym.members());
3097                     _map.put(csym, membersClosure);
3098                 }
3099                 return membersClosure;
3100             }
3101             finally {
3102                 seenTypes.remove(t.tsym);
3103             }
3104         }
3105 
3106         @Override
3107         public CompoundScope visitTypeVar(TypeVar t, Void _unused) {
3108             return visit(t.getUpperBound(), null);
3109         }
3110     }
3111 
3112     private MembersClosureCache membersCache = new MembersClosureCache();
3113 
3114     public CompoundScope membersClosure(Type site, boolean skipInterface) {
3115         CompoundScope cs = membersCache.visit(site, null);
3116         Assert.checkNonNull(cs, () -> "type " + site);
3117         return skipInterface ? membersCache.new MembersScope(cs) : cs;
3118     }
3119     // </editor-fold>
3120 
3121 
3122     /** Return first abstract member of class `sym'.
3123      */
3124     public MethodSymbol firstUnimplementedAbstract(ClassSymbol sym) {
3125         try {
3126             return firstUnimplementedAbstractImpl(sym, sym);
3127         } catch (CompletionFailure ex) {
3128             chk.completionError(enter.getEnv(sym).tree.pos(), ex);
3129             return null;
3130         }
3131     }
3132         //where:
3133         private MethodSymbol firstUnimplementedAbstractImpl(ClassSymbol impl, ClassSymbol c) {
3134             MethodSymbol undef = null;
3135             // Do not bother to search in classes that are not abstract,
3136             // since they cannot have abstract members.
3137             if (c == impl || (c.flags() & (ABSTRACT | INTERFACE)) != 0) {
3138                 Scope s = c.members();
3139                 for (Symbol sym : s.getSymbols(NON_RECURSIVE)) {
3140                     if (sym.kind == MTH &&
3141                         (sym.flags() & (ABSTRACT|DEFAULT|PRIVATE)) == ABSTRACT) {
3142                         MethodSymbol absmeth = (MethodSymbol)sym;
3143                         MethodSymbol implmeth = absmeth.implementation(impl, this, true);
3144                         if (implmeth == null || implmeth == absmeth) {
3145                             //look for default implementations
3146                             MethodSymbol prov = interfaceCandidates(impl.type, absmeth).head;
3147                             if (prov != null && prov.overrides(absmeth, impl, this, true)) {
3148                                 implmeth = prov;
3149                             }
3150                         }
3151                         if (implmeth == null || implmeth == absmeth) {
3152                             undef = absmeth;
3153                             break;
3154                         }
3155                     }
3156                 }
3157                 if (undef == null) {
3158                     Type st = supertype(c.type);
3159                     if (st.hasTag(CLASS))
3160                         undef = firstUnimplementedAbstractImpl(impl, (ClassSymbol)st.tsym);
3161                 }
3162                 for (List<Type> l = interfaces(c.type);
3163                      undef == null && l.nonEmpty();
3164                      l = l.tail) {
3165                     undef = firstUnimplementedAbstractImpl(impl, (ClassSymbol)l.head.tsym);
3166                 }
3167             }
3168             return undef;
3169         }
3170 
3171     public class CandidatesCache {
3172         public Map<Entry, List<MethodSymbol>> cache = new WeakHashMap<>();
3173 
3174         class Entry {
3175             Type site;
3176             MethodSymbol msym;
3177 
3178             Entry(Type site, MethodSymbol msym) {
3179                 this.site = site;
3180                 this.msym = msym;
3181             }
3182 
3183             @Override
3184             public boolean equals(Object obj) {
3185                 return (obj instanceof Entry entry)
3186                         && entry.msym == msym
3187                         && isSameType(site, entry.site);
3188             }
3189 
3190             @Override
3191             public int hashCode() {
3192                 return Types.this.hashCode(site) & ~msym.hashCode();
3193             }
3194         }
3195 
3196         public List<MethodSymbol> get(Entry e) {
3197             return cache.get(e);
3198         }
3199 
3200         public void put(Entry e, List<MethodSymbol> msymbols) {
3201             cache.put(e, msymbols);
3202         }
3203     }
3204 
3205     public CandidatesCache candidatesCache = new CandidatesCache();
3206 
3207     //where
3208     public List<MethodSymbol> interfaceCandidates(Type site, MethodSymbol ms) {
3209         CandidatesCache.Entry e = candidatesCache.new Entry(site, ms);
3210         List<MethodSymbol> candidates = candidatesCache.get(e);
3211         if (candidates == null) {
3212             Predicate<Symbol> filter = new MethodFilter(ms, site);
3213             List<MethodSymbol> candidates2 = List.nil();
3214             for (Symbol s : membersClosure(site, false).getSymbols(filter)) {
3215                 if (!site.tsym.isInterface() && !s.owner.isInterface()) {
3216                     return List.of((MethodSymbol)s);
3217                 } else if (!candidates2.contains(s)) {
3218                     candidates2 = candidates2.prepend((MethodSymbol)s);
3219                 }
3220             }
3221             candidates = prune(candidates2);
3222             candidatesCache.put(e, candidates);
3223         }
3224         return candidates;
3225     }
3226 
3227     public List<MethodSymbol> prune(List<MethodSymbol> methods) {
3228         ListBuffer<MethodSymbol> methodsMin = new ListBuffer<>();
3229         for (MethodSymbol m1 : methods) {
3230             boolean isMin_m1 = true;
3231             for (MethodSymbol m2 : methods) {
3232                 if (m1 == m2) continue;
3233                 if (m2.owner != m1.owner &&
3234                         asSuper(m2.owner.type, m1.owner) != null) {
3235                     isMin_m1 = false;
3236                     break;
3237                 }
3238             }
3239             if (isMin_m1)
3240                 methodsMin.append(m1);
3241         }
3242         return methodsMin.toList();
3243     }
3244     // where
3245             private class MethodFilter implements Predicate<Symbol> {
3246 
3247                 Symbol msym;
3248                 Type site;
3249 
3250                 MethodFilter(Symbol msym, Type site) {
3251                     this.msym = msym;
3252                     this.site = site;
3253                 }
3254 
3255                 @Override
3256                 public boolean test(Symbol s) {
3257                     return s.kind == MTH &&
3258                             s.name == msym.name &&
3259                             (s.flags() & SYNTHETIC) == 0 &&
3260                             s.isInheritedIn(site.tsym, Types.this) &&
3261                             overrideEquivalent(memberType(site, s), memberType(site, msym));
3262                 }
3263             }
3264     // </editor-fold>
3265 
3266     /**
3267      * Does t have the same arguments as s?  It is assumed that both
3268      * types are (possibly polymorphic) method types.  Monomorphic
3269      * method types "have the same arguments", if their argument lists
3270      * are equal.  Polymorphic method types "have the same arguments",
3271      * if they have the same arguments after renaming all type
3272      * variables of one to corresponding type variables in the other,
3273      * where correspondence is by position in the type parameter list.
3274      */
3275     public boolean hasSameArgs(Type t, Type s) {
3276         return hasSameArgs(t, s, true);
3277     }
3278 
3279     public boolean hasSameArgs(Type t, Type s, boolean strict) {
3280         return hasSameArgs(t, s, strict ? hasSameArgs_strict : hasSameArgs_nonstrict);
3281     }
3282 
3283     private boolean hasSameArgs(Type t, Type s, TypeRelation hasSameArgs) {
3284         return hasSameArgs.visit(t, s);
3285     }
3286     // where
3287         private class HasSameArgs extends TypeRelation {
3288 
3289             boolean strict;
3290 
3291             public HasSameArgs(boolean strict) {
3292                 this.strict = strict;
3293             }
3294 
3295             public Boolean visitType(Type t, Type s) {
3296                 throw new AssertionError();
3297             }
3298 
3299             @Override
3300             public Boolean visitMethodType(MethodType t, Type s) {
3301                 return s.hasTag(METHOD)
3302                     && containsTypeEquivalent(t.argtypes, s.getParameterTypes());
3303             }
3304 
3305             @Override
3306             public Boolean visitForAll(ForAll t, Type s) {
3307                 if (!s.hasTag(FORALL))
3308                     return strict ? false : visitMethodType(t.asMethodType(), s);
3309 
3310                 ForAll forAll = (ForAll)s;
3311                 return hasSameBounds(t, forAll)
3312                     && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars));
3313             }
3314 
3315             @Override
3316             public Boolean visitErrorType(ErrorType t, Type s) {
3317                 return false;
3318             }
3319         }
3320 
3321     TypeRelation hasSameArgs_strict = new HasSameArgs(true);
3322         TypeRelation hasSameArgs_nonstrict = new HasSameArgs(false);
3323 
3324     // </editor-fold>
3325 
3326     // <editor-fold defaultstate="collapsed" desc="subst">
3327     public List<Type> subst(List<Type> ts,
3328                             List<Type> from,
3329                             List<Type> to) {
3330         return ts.map(new Subst(from, to));
3331     }
3332 
3333     /**
3334      * Substitute all occurrences of a type in `from' with the
3335      * corresponding type in `to' in 't'. Match lists `from' and `to'
3336      * from the right: If lists have different length, discard leading
3337      * elements of the longer list.
3338      */
3339     public Type subst(Type t, List<Type> from, List<Type> to) {
3340         return t.map(new Subst(from, to));
3341     }
3342 
3343     /* this class won't substitute all types for example UndetVars are never substituted, this is
3344      * by design as UndetVars are used locally during inference and shouldn't escape from inference routines,
3345      * some specialized applications could need a tailored solution
3346      */
3347     private class Subst extends StructuralTypeMapping<Void> {
3348         List<Type> from;
3349         List<Type> to;
3350 
3351         public Subst(List<Type> from, List<Type> to) {
3352             int fromLength = from.length();
3353             int toLength = to.length();
3354             while (fromLength > toLength) {
3355                 fromLength--;
3356                 from = from.tail;
3357             }
3358             while (fromLength < toLength) {
3359                 toLength--;
3360                 to = to.tail;
3361             }
3362             this.from = from;
3363             this.to = to;
3364         }
3365 
3366         @Override
3367         public Type visitTypeVar(TypeVar t, Void ignored) {
3368             for (List<Type> from = this.from, to = this.to;
3369                  from.nonEmpty();
3370                  from = from.tail, to = to.tail) {
3371                 if (t.equalsIgnoreMetadata(from.head)) {
3372                     return to.head.withTypeVar(t);
3373                 }
3374             }
3375             return t;
3376         }
3377 
3378         @Override
3379         public Type visitClassType(ClassType t, Void ignored) {
3380             if (!t.isCompound()) {
3381                 return super.visitClassType(t, ignored);
3382             } else {
3383                 Type st = visit(supertype(t));
3384                 List<Type> is = visit(interfaces(t), ignored);
3385                 if (st == supertype(t) && is == interfaces(t))
3386                     return t;
3387                 else
3388                     return makeIntersectionType(is.prepend(st));
3389             }
3390         }
3391 
3392         @Override
3393         public Type visitWildcardType(WildcardType t, Void ignored) {
3394             WildcardType t2 = (WildcardType)super.visitWildcardType(t, ignored);
3395             if (t2 != t && t.isExtendsBound() && t2.type.isExtendsBound()) {
3396                 t2.type = wildUpperBound(t2.type);
3397             }
3398             return t2;
3399         }
3400 
3401         @Override
3402         public Type visitForAll(ForAll t, Void ignored) {
3403             if (Type.containsAny(to, t.tvars)) {
3404                 //perform alpha-renaming of free-variables in 't'
3405                 //if 'to' types contain variables that are free in 't'
3406                 List<Type> freevars = newInstances(t.tvars);
3407                 t = new ForAll(freevars,
3408                                Types.this.subst(t.qtype, t.tvars, freevars));
3409             }
3410             List<Type> tvars1 = substBounds(t.tvars, from, to);
3411             Type qtype1 = visit(t.qtype);
3412             if (tvars1 == t.tvars && qtype1 == t.qtype) {
3413                 return t;
3414             } else if (tvars1 == t.tvars) {
3415                 return new ForAll(tvars1, qtype1) {
3416                     @Override
3417                     public boolean needsStripping() {
3418                         return true;
3419                     }
3420                 };
3421             } else {
3422                 return new ForAll(tvars1, Types.this.subst(qtype1, t.tvars, tvars1)) {
3423                     @Override
3424                     public boolean needsStripping() {
3425                         return true;
3426                     }
3427                 };
3428             }
3429         }
3430     }
3431 
3432     public List<Type> substBounds(List<Type> tvars,
3433                                   List<Type> from,
3434                                   List<Type> to) {
3435         if (tvars.isEmpty())
3436             return tvars;
3437         ListBuffer<Type> newBoundsBuf = new ListBuffer<>();
3438         boolean changed = false;
3439         // calculate new bounds
3440         for (Type t : tvars) {
3441             TypeVar tv = (TypeVar) t;
3442             Type bound = subst(tv.getUpperBound(), from, to);
3443             if (bound != tv.getUpperBound())
3444                 changed = true;
3445             newBoundsBuf.append(bound);
3446         }
3447         if (!changed)
3448             return tvars;
3449         ListBuffer<Type> newTvars = new ListBuffer<>();
3450         // create new type variables without bounds
3451         for (Type t : tvars) {
3452             newTvars.append(new TypeVar(t.tsym, null, syms.botType,
3453                                         t.getMetadata()));
3454         }
3455         // the new bounds should use the new type variables in place
3456         // of the old
3457         List<Type> newBounds = newBoundsBuf.toList();
3458         from = tvars;
3459         to = newTvars.toList();
3460         for (; !newBounds.isEmpty(); newBounds = newBounds.tail) {
3461             newBounds.head = subst(newBounds.head, from, to);
3462         }
3463         newBounds = newBoundsBuf.toList();
3464         // set the bounds of new type variables to the new bounds
3465         for (Type t : newTvars.toList()) {
3466             TypeVar tv = (TypeVar) t;
3467             tv.setUpperBound( newBounds.head );
3468             newBounds = newBounds.tail;
3469         }
3470         return newTvars.toList();
3471     }
3472 
3473     public TypeVar substBound(TypeVar t, List<Type> from, List<Type> to) {
3474         Type bound1 = subst(t.getUpperBound(), from, to);
3475         if (bound1 == t.getUpperBound())
3476             return t;
3477         else {
3478             // create new type variable without bounds
3479             TypeVar tv = new TypeVar(t.tsym, null, syms.botType,
3480                                      t.getMetadata());
3481             // the new bound should use the new type variable in place
3482             // of the old
3483             tv.setUpperBound( subst(bound1, List.of(t), List.of(tv)) );
3484             return tv;
3485         }
3486     }
3487     // </editor-fold>
3488 
3489     // <editor-fold defaultstate="collapsed" desc="hasSameBounds">
3490     /**
3491      * Does t have the same bounds for quantified variables as s?
3492      */
3493     public boolean hasSameBounds(ForAll t, ForAll s) {
3494         List<Type> l1 = t.tvars;
3495         List<Type> l2 = s.tvars;
3496         while (l1.nonEmpty() && l2.nonEmpty() &&
3497                isSameType(l1.head.getUpperBound(),
3498                           subst(l2.head.getUpperBound(),
3499                                 s.tvars,
3500                                 t.tvars))) {
3501             l1 = l1.tail;
3502             l2 = l2.tail;
3503         }
3504         return l1.isEmpty() && l2.isEmpty();
3505     }
3506     // </editor-fold>
3507 
3508     // <editor-fold defaultstate="collapsed" desc="newInstances">
3509     /** Create new vector of type variables from list of variables
3510      *  changing all recursive bounds from old to new list.
3511      */
3512     public List<Type> newInstances(List<Type> tvars) {
3513         List<Type> tvars1 = tvars.map(newInstanceFun);
3514         for (List<Type> l = tvars1; l.nonEmpty(); l = l.tail) {
3515             TypeVar tv = (TypeVar) l.head;
3516             tv.setUpperBound( subst(tv.getUpperBound(), tvars, tvars1) );
3517         }
3518         return tvars1;
3519     }
3520         private static final TypeMapping<Void> newInstanceFun = new TypeMapping<Void>() {
3521             @Override
3522             public TypeVar visitTypeVar(TypeVar t, Void _unused) {
3523                 return new TypeVar(t.tsym, t.getUpperBound(), t.getLowerBound(), t.getMetadata());
3524             }
3525         };
3526     // </editor-fold>
3527 
3528     public Type createMethodTypeWithParameters(Type original, List<Type> newParams) {
3529         return original.accept(methodWithParameters, newParams);
3530     }
3531     // where
3532         private final MapVisitor<List<Type>> methodWithParameters = new MapVisitor<List<Type>>() {
3533             public Type visitType(Type t, List<Type> newParams) {
3534                 throw new IllegalArgumentException("Not a method type: " + t);
3535             }
3536             public Type visitMethodType(MethodType t, List<Type> newParams) {
3537                 return new MethodType(newParams, t.restype, t.thrown, t.tsym);
3538             }
3539             public Type visitForAll(ForAll t, List<Type> newParams) {
3540                 return new ForAll(t.tvars, t.qtype.accept(this, newParams));
3541             }
3542         };
3543 
3544     public Type createMethodTypeWithThrown(Type original, List<Type> newThrown) {
3545         return original.accept(methodWithThrown, newThrown);
3546     }
3547     // where
3548         private final MapVisitor<List<Type>> methodWithThrown = new MapVisitor<List<Type>>() {
3549             public Type visitType(Type t, List<Type> newThrown) {
3550                 throw new IllegalArgumentException("Not a method type: " + t);
3551             }
3552             public Type visitMethodType(MethodType t, List<Type> newThrown) {
3553                 return new MethodType(t.argtypes, t.restype, newThrown, t.tsym);
3554             }
3555             public Type visitForAll(ForAll t, List<Type> newThrown) {
3556                 return new ForAll(t.tvars, t.qtype.accept(this, newThrown));
3557             }
3558         };
3559 
3560     public Type createMethodTypeWithReturn(Type original, Type newReturn) {
3561         return original.accept(methodWithReturn, newReturn);
3562     }
3563     // where
3564         private final MapVisitor<Type> methodWithReturn = new MapVisitor<Type>() {
3565             public Type visitType(Type t, Type newReturn) {
3566                 throw new IllegalArgumentException("Not a method type: " + t);
3567             }
3568             public Type visitMethodType(MethodType t, Type newReturn) {
3569                 return new MethodType(t.argtypes, newReturn, t.thrown, t.tsym) {
3570                     @Override
3571                     public Type baseType() {
3572                         return t;
3573                     }
3574                 };
3575             }
3576             public Type visitForAll(ForAll t, Type newReturn) {
3577                 return new ForAll(t.tvars, t.qtype.accept(this, newReturn)) {
3578                     @Override
3579                     public Type baseType() {
3580                         return t;
3581                     }
3582                 };
3583             }
3584         };
3585 
3586     // <editor-fold defaultstate="collapsed" desc="createErrorType">
3587     public Type createErrorType(Type originalType) {
3588         return new ErrorType(originalType, syms.errSymbol);
3589     }
3590 
3591     public Type createErrorType(ClassSymbol c, Type originalType) {
3592         return new ErrorType(c, originalType);
3593     }
3594 
3595     public Type createErrorType(Name name, TypeSymbol container, Type originalType) {
3596         return new ErrorType(name, container, originalType);
3597     }
3598     // </editor-fold>
3599 
3600     // <editor-fold defaultstate="collapsed" desc="rank">
3601     /**
3602      * The rank of a class is the length of the longest path between
3603      * the class and java.lang.Object in the class inheritance
3604      * graph. Undefined for all but reference types.
3605      */
3606     public int rank(Type t) {
3607         switch(t.getTag()) {
3608         case CLASS: {
3609             ClassType cls = (ClassType)t;
3610             if (cls.rank_field < 0) {
3611                 Name fullname = cls.tsym.getQualifiedName();
3612                 if (fullname == names.java_lang_Object)
3613                     cls.rank_field = 0;
3614                 else {
3615                     int r = rank(supertype(cls));
3616                     for (List<Type> l = interfaces(cls);
3617                          l.nonEmpty();
3618                          l = l.tail) {
3619                         if (rank(l.head) > r)
3620                             r = rank(l.head);
3621                     }
3622                     cls.rank_field = r + 1;
3623                 }
3624             }
3625             return cls.rank_field;
3626         }
3627         case TYPEVAR: {
3628             TypeVar tvar = (TypeVar)t;
3629             if (tvar.rank_field < 0) {
3630                 int r = rank(supertype(tvar));
3631                 for (List<Type> l = interfaces(tvar);
3632                      l.nonEmpty();
3633                      l = l.tail) {
3634                     if (rank(l.head) > r) r = rank(l.head);
3635                 }
3636                 tvar.rank_field = r + 1;
3637             }
3638             return tvar.rank_field;
3639         }
3640         case ERROR:
3641         case NONE:
3642             return 0;
3643         default:
3644             throw new AssertionError();
3645         }
3646     }
3647     // </editor-fold>
3648 
3649     /**
3650      * Helper method for generating a string representation of a given type
3651      * accordingly to a given locale
3652      */
3653     public String toString(Type t, Locale locale) {
3654         return Printer.createStandardPrinter(messages).visit(t, locale);
3655     }
3656 
3657     /**
3658      * Helper method for generating a string representation of a given type
3659      * accordingly to a given locale
3660      */
3661     public String toString(Symbol t, Locale locale) {
3662         return Printer.createStandardPrinter(messages).visit(t, locale);
3663     }
3664 
3665     // <editor-fold defaultstate="collapsed" desc="toString">
3666     /**
3667      * This toString is slightly more descriptive than the one on Type.
3668      *
3669      * @deprecated Types.toString(Type t, Locale l) provides better support
3670      * for localization
3671      */
3672     @Deprecated
3673     public String toString(Type t) {
3674         if (t.hasTag(FORALL)) {
3675             ForAll forAll = (ForAll)t;
3676             return typaramsString(forAll.tvars) + forAll.qtype;
3677         }
3678         return "" + t;
3679     }
3680     // where
3681         private String typaramsString(List<Type> tvars) {
3682             StringBuilder s = new StringBuilder();
3683             s.append('<');
3684             boolean first = true;
3685             for (Type t : tvars) {
3686                 if (!first) s.append(", ");
3687                 first = false;
3688                 appendTyparamString(((TypeVar)t), s);
3689             }
3690             s.append('>');
3691             return s.toString();
3692         }
3693         private void appendTyparamString(TypeVar t, StringBuilder buf) {
3694             buf.append(t);
3695             if (t.getUpperBound() == null ||
3696                 t.getUpperBound().tsym.getQualifiedName() == names.java_lang_Object)
3697                 return;
3698             buf.append(" extends "); // Java syntax; no need for i18n
3699             Type bound = t.getUpperBound();
3700             if (!bound.isCompound()) {
3701                 buf.append(bound);
3702             } else if ((erasure(t).tsym.flags() & INTERFACE) == 0) {
3703                 buf.append(supertype(t));
3704                 for (Type intf : interfaces(t)) {
3705                     buf.append('&');
3706                     buf.append(intf);
3707                 }
3708             } else {
3709                 // No superclass was given in bounds.
3710                 // In this case, supertype is Object, erasure is first interface.
3711                 boolean first = true;
3712                 for (Type intf : interfaces(t)) {
3713                     if (!first) buf.append('&');
3714                     first = false;
3715                     buf.append(intf);
3716                 }
3717             }
3718         }
3719     // </editor-fold>
3720 
3721     // <editor-fold defaultstate="collapsed" desc="Determining least upper bounds of types">
3722     /**
3723      * A cache for closures.
3724      *
3725      * <p>A closure is a list of all the supertypes and interfaces of
3726      * a class or interface type, ordered by ClassSymbol.precedes
3727      * (that is, subclasses come first, arbitrarily but fixed
3728      * otherwise).
3729      */
3730     private Map<Type,List<Type>> closureCache = new HashMap<>();
3731 
3732     /**
3733      * Returns the closure of a class or interface type.
3734      */
3735     public List<Type> closure(Type t) {
3736         List<Type> cl = closureCache.get(t);
3737         if (cl == null) {
3738             Type st = supertype(t);
3739             if (!t.isCompound()) {
3740                 if (st.hasTag(CLASS)) {
3741                     cl = insert(closure(st), t);
3742                 } else if (st.hasTag(TYPEVAR)) {
3743                     cl = closure(st).prepend(t);
3744                 } else {
3745                     cl = List.of(t);
3746                 }
3747             } else {
3748                 cl = closure(supertype(t));
3749             }
3750             for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail)
3751                 cl = union(cl, closure(l.head));
3752             closureCache.put(t, cl);
3753         }
3754         return cl;
3755     }
3756 
3757     /**
3758      * Collect types into a new closure (using a {@code ClosureHolder})
3759      */
3760     public Collector<Type, ClosureHolder, List<Type>> closureCollector(boolean minClosure, BiPredicate<Type, Type> shouldSkip) {
3761         return Collector.of(() -> new ClosureHolder(minClosure, shouldSkip),
3762                 ClosureHolder::add,
3763                 ClosureHolder::merge,
3764                 ClosureHolder::closure);
3765     }
3766     //where
3767         class ClosureHolder {
3768             List<Type> closure;
3769             final boolean minClosure;
3770             final BiPredicate<Type, Type> shouldSkip;
3771 
3772             ClosureHolder(boolean minClosure, BiPredicate<Type, Type> shouldSkip) {
3773                 this.closure = List.nil();
3774                 this.minClosure = minClosure;
3775                 this.shouldSkip = shouldSkip;
3776             }
3777 
3778             void add(Type type) {
3779                 closure = insert(closure, type, shouldSkip);
3780             }
3781 
3782             ClosureHolder merge(ClosureHolder other) {
3783                 closure = union(closure, other.closure, shouldSkip);
3784                 return this;
3785             }
3786 
3787             List<Type> closure() {
3788                 return minClosure ? closureMin(closure) : closure;
3789             }
3790         }
3791 
3792     BiPredicate<Type, Type> basicClosureSkip = (t1, t2) -> t1.tsym == t2.tsym;
3793 
3794     /**
3795      * Insert a type in a closure
3796      */
3797     public List<Type> insert(List<Type> cl, Type t, BiPredicate<Type, Type> shouldSkip) {
3798         if (cl.isEmpty()) {
3799             return cl.prepend(t);
3800         } else if (shouldSkip.test(t, cl.head)) {
3801             return cl;
3802         } else if (t.tsym.precedes(cl.head.tsym, this)) {
3803             return cl.prepend(t);
3804         } else {
3805             // t comes after head, or the two are unrelated
3806             return insert(cl.tail, t, shouldSkip).prepend(cl.head);
3807         }
3808     }
3809 
3810     public List<Type> insert(List<Type> cl, Type t) {
3811         return insert(cl, t, basicClosureSkip);
3812     }
3813 
3814     /**
3815      * Form the union of two closures
3816      */
3817     public List<Type> union(List<Type> cl1, List<Type> cl2, BiPredicate<Type, Type> shouldSkip) {
3818         if (cl1.isEmpty()) {
3819             return cl2;
3820         } else if (cl2.isEmpty()) {
3821             return cl1;
3822         } else if (shouldSkip.test(cl1.head, cl2.head)) {
3823             return union(cl1.tail, cl2.tail, shouldSkip).prepend(cl1.head);
3824         } else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) {
3825             return union(cl1, cl2.tail, shouldSkip).prepend(cl2.head);
3826         } else {
3827             return union(cl1.tail, cl2, shouldSkip).prepend(cl1.head);
3828         }
3829     }
3830 
3831     public List<Type> union(List<Type> cl1, List<Type> cl2) {
3832         return union(cl1, cl2, basicClosureSkip);
3833     }
3834 
3835     /**
3836      * Intersect two closures
3837      */
3838     public List<Type> intersect(List<Type> cl1, List<Type> cl2) {
3839         if (cl1 == cl2)
3840             return cl1;
3841         if (cl1.isEmpty() || cl2.isEmpty())
3842             return List.nil();
3843         if (cl1.head.tsym.precedes(cl2.head.tsym, this))
3844             return intersect(cl1.tail, cl2);
3845         if (cl2.head.tsym.precedes(cl1.head.tsym, this))
3846             return intersect(cl1, cl2.tail);
3847         if (isSameType(cl1.head, cl2.head))
3848             return intersect(cl1.tail, cl2.tail).prepend(cl1.head);
3849         if (cl1.head.tsym == cl2.head.tsym &&
3850             cl1.head.hasTag(CLASS) && cl2.head.hasTag(CLASS)) {
3851             if (cl1.head.isParameterized() && cl2.head.isParameterized()) {
3852                 Type merge = merge(cl1.head,cl2.head);
3853                 return intersect(cl1.tail, cl2.tail).prepend(merge);
3854             }
3855             if (cl1.head.isRaw() || cl2.head.isRaw())
3856                 return intersect(cl1.tail, cl2.tail).prepend(erasure(cl1.head));
3857         }
3858         return intersect(cl1.tail, cl2.tail);
3859     }
3860     // where
3861         class TypePair {
3862             final Type t1;
3863             final Type t2;;
3864 
3865             TypePair(Type t1, Type t2) {
3866                 this.t1 = t1;
3867                 this.t2 = t2;
3868             }
3869             @Override
3870             public int hashCode() {
3871                 return 127 * Types.this.hashCode(t1) + Types.this.hashCode(t2);
3872             }
3873             @Override
3874             public boolean equals(Object obj) {
3875                 return (obj instanceof TypePair typePair)
3876                         && isSameType(t1, typePair.t1)
3877                         && isSameType(t2, typePair.t2);
3878             }
3879         }
3880         Set<TypePair> mergeCache = new HashSet<>();
3881         private Type merge(Type c1, Type c2) {
3882             ClassType class1 = (ClassType) c1;
3883             List<Type> act1 = class1.getTypeArguments();
3884             ClassType class2 = (ClassType) c2;
3885             List<Type> act2 = class2.getTypeArguments();
3886             ListBuffer<Type> merged = new ListBuffer<>();
3887             List<Type> typarams = class1.tsym.type.getTypeArguments();
3888 
3889             while (act1.nonEmpty() && act2.nonEmpty() && typarams.nonEmpty()) {
3890                 if (containsType(act1.head, act2.head)) {
3891                     merged.append(act1.head);
3892                 } else if (containsType(act2.head, act1.head)) {
3893                     merged.append(act2.head);
3894                 } else {
3895                     TypePair pair = new TypePair(c1, c2);
3896                     Type m;
3897                     if (mergeCache.add(pair)) {
3898                         m = new WildcardType(lub(wildUpperBound(act1.head),
3899                                                  wildUpperBound(act2.head)),
3900                                              BoundKind.EXTENDS,
3901                                              syms.boundClass);
3902                         mergeCache.remove(pair);
3903                     } else {
3904                         m = new WildcardType(syms.objectType,
3905                                              BoundKind.UNBOUND,
3906                                              syms.boundClass);
3907                     }
3908                     merged.append(m.withTypeVar(typarams.head));
3909                 }
3910                 act1 = act1.tail;
3911                 act2 = act2.tail;
3912                 typarams = typarams.tail;
3913             }
3914             Assert.check(act1.isEmpty() && act2.isEmpty() && typarams.isEmpty());
3915             // There is no spec detailing how type annotations are to
3916             // be inherited.  So set it to noAnnotations for now
3917             return new ClassType(class1.getEnclosingType(), merged.toList(),
3918                                  class1.tsym);
3919         }
3920 
3921     /**
3922      * Return the minimum type of a closure, a compound type if no
3923      * unique minimum exists.
3924      */
3925     private Type compoundMin(List<Type> cl) {
3926         if (cl.isEmpty()) return syms.objectType;
3927         List<Type> compound = closureMin(cl);
3928         if (compound.isEmpty())
3929             return null;
3930         else if (compound.tail.isEmpty())
3931             return compound.head;
3932         else
3933             return makeIntersectionType(compound);
3934     }
3935 
3936     /**
3937      * Return the minimum types of a closure, suitable for computing
3938      * compoundMin or glb.
3939      */
3940     private List<Type> closureMin(List<Type> cl) {
3941         ListBuffer<Type> classes = new ListBuffer<>();
3942         ListBuffer<Type> interfaces = new ListBuffer<>();
3943         Set<Type> toSkip = new HashSet<>();
3944         while (!cl.isEmpty()) {
3945             Type current = cl.head;
3946             boolean keep = !toSkip.contains(current);
3947             if (keep && current.hasTag(TYPEVAR)) {
3948                 // skip lower-bounded variables with a subtype in cl.tail
3949                 for (Type t : cl.tail) {
3950                     if (isSubtypeNoCapture(t, current)) {
3951                         keep = false;
3952                         break;
3953                     }
3954                 }
3955             }
3956             if (keep) {
3957                 if (current.isInterface())
3958                     interfaces.append(current);
3959                 else
3960                     classes.append(current);
3961                 for (Type t : cl.tail) {
3962                     // skip supertypes of 'current' in cl.tail
3963                     if (isSubtypeNoCapture(current, t))
3964                         toSkip.add(t);
3965                 }
3966             }
3967             cl = cl.tail;
3968         }
3969         return classes.appendList(interfaces).toList();
3970     }
3971 
3972     /**
3973      * Return the least upper bound of list of types.  if the lub does
3974      * not exist return null.
3975      */
3976     public Type lub(List<Type> ts) {
3977         return lub(ts.toArray(new Type[ts.length()]));
3978     }
3979 
3980     /**
3981      * Return the least upper bound (lub) of set of types.  If the lub
3982      * does not exist return the type of null (bottom).
3983      */
3984     public Type lub(Type... ts) {
3985         final int UNKNOWN_BOUND = 0;
3986         final int ARRAY_BOUND = 1;
3987         final int CLASS_BOUND = 2;
3988 
3989         int[] kinds = new int[ts.length];
3990 
3991         int boundkind = UNKNOWN_BOUND;
3992         for (int i = 0 ; i < ts.length ; i++) {
3993             Type t = ts[i];
3994             switch (t.getTag()) {
3995             case CLASS:
3996                 boundkind |= kinds[i] = CLASS_BOUND;
3997                 break;
3998             case ARRAY:
3999                 boundkind |= kinds[i] = ARRAY_BOUND;
4000                 break;
4001             case  TYPEVAR:
4002                 do {
4003                     t = t.getUpperBound();
4004                 } while (t.hasTag(TYPEVAR));
4005                 if (t.hasTag(ARRAY)) {
4006                     boundkind |= kinds[i] = ARRAY_BOUND;
4007                 } else {
4008                     boundkind |= kinds[i] = CLASS_BOUND;
4009                 }
4010                 break;
4011             default:
4012                 kinds[i] = UNKNOWN_BOUND;
4013                 if (t.isPrimitive())
4014                     return syms.errType;
4015             }
4016         }
4017         switch (boundkind) {
4018         case 0:
4019             return syms.botType;
4020 
4021         case ARRAY_BOUND:
4022             // calculate lub(A[], B[])
4023             Type[] elements = new Type[ts.length];
4024             for (int i = 0 ; i < ts.length ; i++) {
4025                 Type elem = elements[i] = elemTypeFun.apply(ts[i]);
4026                 if (elem.isPrimitive()) {
4027                     // if a primitive type is found, then return
4028                     // arraySuperType unless all the types are the
4029                     // same
4030                     Type first = ts[0];
4031                     for (int j = 1 ; j < ts.length ; j++) {
4032                         if (!isSameType(first, ts[j])) {
4033                              // lub(int[], B[]) is Cloneable & Serializable
4034                             return arraySuperType();
4035                         }
4036                     }
4037                     // all the array types are the same, return one
4038                     // lub(int[], int[]) is int[]
4039                     return first;
4040                 }
4041             }
4042             // lub(A[], B[]) is lub(A, B)[]
4043             return new ArrayType(lub(elements), syms.arrayClass);
4044 
4045         case CLASS_BOUND:
4046             // calculate lub(A, B)
4047             int startIdx = 0;
4048             for (int i = 0; i < ts.length ; i++) {
4049                 Type t = ts[i];
4050                 if (t.hasTag(CLASS) || t.hasTag(TYPEVAR)) {
4051                     break;
4052                 } else {
4053                     startIdx++;
4054                 }
4055             }
4056             Assert.check(startIdx < ts.length);
4057             //step 1 - compute erased candidate set (EC)
4058             List<Type> cl = erasedSupertypes(ts[startIdx]);
4059             for (int i = startIdx + 1 ; i < ts.length ; i++) {
4060                 Type t = ts[i];
4061                 if (t.hasTag(CLASS) || t.hasTag(TYPEVAR))
4062                     cl = intersect(cl, erasedSupertypes(t));
4063             }
4064             //step 2 - compute minimal erased candidate set (MEC)
4065             List<Type> mec = closureMin(cl);
4066             //step 3 - for each element G in MEC, compute lci(Inv(G))
4067             List<Type> candidates = List.nil();
4068             for (Type erasedSupertype : mec) {
4069                 List<Type> lci = List.of(asSuper(ts[startIdx], erasedSupertype.tsym));
4070                 for (int i = startIdx + 1 ; i < ts.length ; i++) {
4071                     Type superType = asSuper(ts[i], erasedSupertype.tsym);
4072                     lci = intersect(lci, superType != null ? List.of(superType) : List.nil());
4073                 }
4074                 candidates = candidates.appendList(lci);
4075             }
4076             //step 4 - let MEC be { G1, G2 ... Gn }, then we have that
4077             //lub = lci(Inv(G1)) & lci(Inv(G2)) & ... & lci(Inv(Gn))
4078             return compoundMin(candidates);
4079 
4080         default:
4081             // calculate lub(A, B[])
4082             List<Type> classes = List.of(arraySuperType());
4083             for (int i = 0 ; i < ts.length ; i++) {
4084                 if (kinds[i] != ARRAY_BOUND) // Filter out any arrays
4085                     classes = classes.prepend(ts[i]);
4086             }
4087             // lub(A, B[]) is lub(A, arraySuperType)
4088             return lub(classes);
4089         }
4090     }
4091     // where
4092         List<Type> erasedSupertypes(Type t) {
4093             ListBuffer<Type> buf = new ListBuffer<>();
4094             for (Type sup : closure(t)) {
4095                 if (sup.hasTag(TYPEVAR)) {
4096                     buf.append(sup);
4097                 } else {
4098                     buf.append(erasure(sup));
4099                 }
4100             }
4101             return buf.toList();
4102         }
4103 
4104         private Type arraySuperType;
4105         private Type arraySuperType() {
4106             // initialized lazily to avoid problems during compiler startup
4107             if (arraySuperType == null) {
4108                 // JLS 10.8: all arrays implement Cloneable and Serializable.
4109                 arraySuperType = makeIntersectionType(List.of(syms.serializableType,
4110                         syms.cloneableType), true);
4111             }
4112             return arraySuperType;
4113         }
4114     // </editor-fold>
4115 
4116     // <editor-fold defaultstate="collapsed" desc="Greatest lower bound">
4117     public Type glb(List<Type> ts) {
4118         Type t1 = ts.head;
4119         for (Type t2 : ts.tail) {
4120             if (t1.isErroneous())
4121                 return t1;
4122             t1 = glb(t1, t2);
4123         }
4124         return t1;
4125     }
4126     //where
4127     public Type glb(Type t, Type s) {
4128         if (s == null)
4129             return t;
4130         else if (t.isPrimitive() || s.isPrimitive())
4131             return syms.errType;
4132         else if (isSubtypeNoCapture(t, s))
4133             return t;
4134         else if (isSubtypeNoCapture(s, t))
4135             return s;
4136 
4137         List<Type> closure = union(closure(t), closure(s));
4138         return glbFlattened(closure, t);
4139     }
4140     //where
4141     /**
4142      * Perform glb for a list of non-primitive, non-error, non-compound types;
4143      * redundant elements are removed.  Bounds should be ordered according to
4144      * {@link Symbol#precedes(TypeSymbol,Types)}.
4145      *
4146      * @param flatBounds List of type to glb
4147      * @param errT Original type to use if the result is an error type
4148      */
4149     private Type glbFlattened(List<Type> flatBounds, Type errT) {
4150         List<Type> bounds = closureMin(flatBounds);
4151 
4152         if (bounds.isEmpty()) {             // length == 0
4153             return syms.objectType;
4154         } else if (bounds.tail.isEmpty()) { // length == 1
4155             return bounds.head;
4156         } else {                            // length > 1
4157             int classCount = 0;
4158             List<Type> cvars = List.nil();
4159             List<Type> lowers = List.nil();
4160             for (Type bound : bounds) {
4161                 if (!bound.isInterface()) {
4162                     classCount++;
4163                     Type lower = cvarLowerBound(bound);
4164                     if (bound != lower && !lower.hasTag(BOT)) {
4165                         cvars = cvars.append(bound);
4166                         lowers = lowers.append(lower);
4167                     }
4168                 }
4169             }
4170             if (classCount > 1) {
4171                 if (lowers.isEmpty()) {
4172                     return createErrorType(errT);
4173                 } else {
4174                     // try again with lower bounds included instead of capture variables
4175                     List<Type> newBounds = bounds.diff(cvars).appendList(lowers);
4176                     return glb(newBounds);
4177                 }
4178             }
4179         }
4180         return makeIntersectionType(bounds);
4181     }
4182     // </editor-fold>
4183 
4184     // <editor-fold defaultstate="collapsed" desc="hashCode">
4185     /**
4186      * Compute a hash code on a type.
4187      */
4188     public int hashCode(Type t) {
4189         return hashCode(t, false);
4190     }
4191 
4192     public int hashCode(Type t, boolean strict) {
4193         return strict ?
4194                 hashCodeStrictVisitor.visit(t) :
4195                 hashCodeVisitor.visit(t);
4196     }
4197     // where
4198         private static final HashCodeVisitor hashCodeVisitor = new HashCodeVisitor();
4199         private static final HashCodeVisitor hashCodeStrictVisitor = new HashCodeVisitor() {
4200             @Override
4201             public Integer visitTypeVar(TypeVar t, Void ignored) {
4202                 return System.identityHashCode(t);
4203             }
4204         };
4205 
4206         private static class HashCodeVisitor extends UnaryVisitor<Integer> {
4207             public Integer visitType(Type t, Void ignored) {
4208                 return t.getTag().ordinal();
4209             }
4210 
4211             @Override
4212             public Integer visitClassType(ClassType t, Void ignored) {
4213                 int result = visit(t.getEnclosingType());
4214                 result *= 127;
4215                 result += t.tsym.flatName().hashCode();
4216                 for (Type s : t.getTypeArguments()) {
4217                     result *= 127;
4218                     result += visit(s);
4219                 }
4220                 return result;
4221             }
4222 
4223             @Override
4224             public Integer visitMethodType(MethodType t, Void ignored) {
4225                 int h = METHOD.ordinal();
4226                 for (List<Type> thisargs = t.argtypes;
4227                      thisargs.tail != null;
4228                      thisargs = thisargs.tail)
4229                     h = (h << 5) + visit(thisargs.head);
4230                 return (h << 5) + visit(t.restype);
4231             }
4232 
4233             @Override
4234             public Integer visitWildcardType(WildcardType t, Void ignored) {
4235                 int result = t.kind.hashCode();
4236                 if (t.type != null) {
4237                     result *= 127;
4238                     result += visit(t.type);
4239                 }
4240                 return result;
4241             }
4242 
4243             @Override
4244             public Integer visitArrayType(ArrayType t, Void ignored) {
4245                 return visit(t.elemtype) + 12;
4246             }
4247 
4248             @Override
4249             public Integer visitTypeVar(TypeVar t, Void ignored) {
4250                 return System.identityHashCode(t);
4251             }
4252 
4253             @Override
4254             public Integer visitUndetVar(UndetVar t, Void ignored) {
4255                 return System.identityHashCode(t);
4256             }
4257 
4258             @Override
4259             public Integer visitErrorType(ErrorType t, Void ignored) {
4260                 return 0;
4261             }
4262         }
4263     // </editor-fold>
4264 
4265     // <editor-fold defaultstate="collapsed" desc="Return-Type-Substitutable">
4266     /**
4267      * Does t have a result that is a subtype of the result type of s,
4268      * suitable for covariant returns?  It is assumed that both types
4269      * are (possibly polymorphic) method types.  Monomorphic method
4270      * types are handled in the obvious way.  Polymorphic method types
4271      * require renaming all type variables of one to corresponding
4272      * type variables in the other, where correspondence is by
4273      * position in the type parameter list. */
4274     public boolean resultSubtype(Type t, Type s, Warner warner) {
4275         List<Type> tvars = t.getTypeArguments();
4276         List<Type> svars = s.getTypeArguments();
4277         Type tres = t.getReturnType();
4278         Type sres = subst(s.getReturnType(), svars, tvars);
4279         return covariantReturnType(tres, sres, warner);
4280     }
4281 
4282     /**
4283      * Return-Type-Substitutable.
4284      * @jls 8.4.5 Method Result
4285      */
4286     public boolean returnTypeSubstitutable(Type r1, Type r2) {
4287         if (hasSameArgs(r1, r2))
4288             return resultSubtype(r1, r2, noWarnings);
4289         else
4290             return covariantReturnType(r1.getReturnType(),
4291                                        erasure(r2.getReturnType()),
4292                                        noWarnings);
4293     }
4294 
4295     public boolean returnTypeSubstitutable(Type r1,
4296                                            Type r2, Type r2res,
4297                                            Warner warner) {
4298         if (isSameType(r1.getReturnType(), r2res))
4299             return true;
4300         if (r1.getReturnType().isPrimitive() || r2res.isPrimitive())
4301             return false;
4302 
4303         if (hasSameArgs(r1, r2))
4304             return covariantReturnType(r1.getReturnType(), r2res, warner);
4305         if (isSubtypeUnchecked(r1.getReturnType(), r2res, warner))
4306             return true;
4307         if (!isSubtype(r1.getReturnType(), erasure(r2res)))
4308             return false;
4309         warner.warn(LintCategory.UNCHECKED);
4310         return true;
4311     }
4312 
4313     /**
4314      * Is t an appropriate return type in an overrider for a
4315      * method that returns s?
4316      */
4317     public boolean covariantReturnType(Type t, Type s, Warner warner) {
4318         return
4319             isSameType(t, s) ||
4320             !t.isPrimitive() &&
4321             !s.isPrimitive() &&
4322             isAssignable(t, s, warner);
4323     }
4324     // </editor-fold>
4325 
4326     // <editor-fold defaultstate="collapsed" desc="Box/unbox support">
4327     /**
4328      * Return the class that boxes the given primitive.
4329      */
4330     public ClassSymbol boxedClass(Type t) {
4331         return syms.enterClass(syms.java_base, syms.boxedName[t.getTag().ordinal()]);
4332     }
4333 
4334     /**
4335      * Return the boxed type if 't' is primitive, otherwise return 't' itself.
4336      */
4337     public Type boxedTypeOrType(Type t) {
4338         return t.isPrimitive() ?
4339             boxedClass(t).type :
4340             t;
4341     }
4342 
4343     /**
4344      * Return the primitive type corresponding to a boxed type.
4345      */
4346     public Type unboxedType(Type t) {
4347         if (t.hasTag(ERROR))
4348             return Type.noType;
4349         for (int i=0; i<syms.boxedName.length; i++) {
4350             Name box = syms.boxedName[i];
4351             if (box != null &&
4352                 asSuper(t, syms.enterClass(syms.java_base, box)) != null)
4353                 return syms.typeOfTag[i];
4354         }
4355         return Type.noType;
4356     }
4357 
4358     /**
4359      * Return the unboxed type if 't' is a boxed class, otherwise return 't' itself.
4360      */
4361     public Type unboxedTypeOrType(Type t) {
4362         Type unboxedType = unboxedType(t);
4363         return unboxedType.hasTag(NONE) ? t : unboxedType;
4364     }
4365     // </editor-fold>
4366 
4367     // <editor-fold defaultstate="collapsed" desc="Capture conversion">
4368     /*
4369      * JLS 5.1.10 Capture Conversion:
4370      *
4371      * Let G name a generic type declaration with n formal type
4372      * parameters A1 ... An with corresponding bounds U1 ... Un. There
4373      * exists a capture conversion from G<T1 ... Tn> to G<S1 ... Sn>,
4374      * where, for 1 <= i <= n:
4375      *
4376      * + If Ti is a wildcard type argument (4.5.1) of the form ? then
4377      *   Si is a fresh type variable whose upper bound is
4378      *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is the null
4379      *   type.
4380      *
4381      * + If Ti is a wildcard type argument of the form ? extends Bi,
4382      *   then Si is a fresh type variable whose upper bound is
4383      *   glb(Bi, Ui[A1 := S1, ..., An := Sn]) and whose lower bound is
4384      *   the null type, where glb(V1,... ,Vm) is V1 & ... & Vm. It is
4385      *   a compile-time error if for any two classes (not interfaces)
4386      *   Vi and Vj,Vi is not a subclass of Vj or vice versa.
4387      *
4388      * + If Ti is a wildcard type argument of the form ? super Bi,
4389      *   then Si is a fresh type variable whose upper bound is
4390      *   Ui[A1 := S1, ..., An := Sn] and whose lower bound is Bi.
4391      *
4392      * + Otherwise, Si = Ti.
4393      *
4394      * Capture conversion on any type other than a parameterized type
4395      * (4.5) acts as an identity conversion (5.1.1). Capture
4396      * conversions never require a special action at run time and
4397      * therefore never throw an exception at run time.
4398      *
4399      * Capture conversion is not applied recursively.
4400      */
4401     /**
4402      * Capture conversion as specified by the JLS.
4403      */
4404 
4405     public List<Type> capture(List<Type> ts) {
4406         List<Type> buf = List.nil();
4407         for (Type t : ts) {
4408             buf = buf.prepend(capture(t));
4409         }
4410         return buf.reverse();
4411     }
4412 
4413     public Type capture(Type t) {
4414         if (!t.hasTag(CLASS)) {
4415             return t;
4416         }
4417         if (t.getEnclosingType() != Type.noType) {
4418             Type capturedEncl = capture(t.getEnclosingType());
4419             if (capturedEncl != t.getEnclosingType()) {
4420                 Type type1 = memberType(capturedEncl, t.tsym);
4421                 t = subst(type1, t.tsym.type.getTypeArguments(), t.getTypeArguments());
4422             }
4423         }
4424         ClassType cls = (ClassType)t;
4425         if (cls.isRaw() || !cls.isParameterized())
4426             return cls;
4427 
4428         ClassType G = (ClassType)cls.asElement().asType();
4429         List<Type> A = G.getTypeArguments();
4430         List<Type> T = cls.getTypeArguments();
4431         List<Type> S = freshTypeVariables(T);
4432 
4433         List<Type> currentA = A;
4434         List<Type> currentT = T;
4435         List<Type> currentS = S;
4436         boolean captured = false;
4437         while (!currentA.isEmpty() &&
4438                !currentT.isEmpty() &&
4439                !currentS.isEmpty()) {
4440             if (currentS.head != currentT.head) {
4441                 captured = true;
4442                 WildcardType Ti = (WildcardType)currentT.head;
4443                 Type Ui = currentA.head.getUpperBound();
4444                 CapturedType Si = (CapturedType)currentS.head;
4445                 if (Ui == null)
4446                     Ui = syms.objectType;
4447                 switch (Ti.kind) {
4448                 case UNBOUND:
4449                     Si.setUpperBound( subst(Ui, A, S) );
4450                     Si.lower = syms.botType;
4451                     break;
4452                 case EXTENDS:
4453                     Si.setUpperBound( glb(Ti.getExtendsBound(), subst(Ui, A, S)) );
4454                     Si.lower = syms.botType;
4455                     break;
4456                 case SUPER:
4457                     Si.setUpperBound( subst(Ui, A, S) );
4458                     Si.lower = Ti.getSuperBound();
4459                     break;
4460                 }
4461                 Type tmpBound = Si.getUpperBound().hasTag(UNDETVAR) ? ((UndetVar)Si.getUpperBound()).qtype : Si.getUpperBound();
4462                 Type tmpLower = Si.lower.hasTag(UNDETVAR) ? ((UndetVar)Si.lower).qtype : Si.lower;
4463                 if (!Si.getUpperBound().hasTag(ERROR) &&
4464                     !Si.lower.hasTag(ERROR) &&
4465                     isSameType(tmpBound, tmpLower)) {
4466                     currentS.head = Si.getUpperBound();
4467                 }
4468             }
4469             currentA = currentA.tail;
4470             currentT = currentT.tail;
4471             currentS = currentS.tail;
4472         }
4473         if (!currentA.isEmpty() || !currentT.isEmpty() || !currentS.isEmpty())
4474             return erasure(t); // some "rare" type involved
4475 
4476         if (captured)
4477             return new ClassType(cls.getEnclosingType(), S, cls.tsym,
4478                                  cls.getMetadata());
4479         else
4480             return t;
4481     }
4482     // where
4483         public List<Type> freshTypeVariables(List<Type> types) {
4484             ListBuffer<Type> result = new ListBuffer<>();
4485             for (Type t : types) {
4486                 if (t.hasTag(WILDCARD)) {
4487                     Type bound = ((WildcardType)t).getExtendsBound();
4488                     if (bound == null)
4489                         bound = syms.objectType;
4490                     result.append(new CapturedType(capturedName,
4491                                                    syms.noSymbol,
4492                                                    bound,
4493                                                    syms.botType,
4494                                                    (WildcardType)t));
4495                 } else {
4496                     result.append(t);
4497                 }
4498             }
4499             return result.toList();
4500         }
4501     // </editor-fold>
4502 
4503     // <editor-fold defaultstate="collapsed" desc="Internal utility methods">
4504     private boolean sideCast(Type from, Type to, Warner warn) {
4505         // We are casting from type $from$ to type $to$, which are
4506         // non-final unrelated types.  This method
4507         // tries to reject a cast by transferring type parameters
4508         // from $to$ to $from$ by common superinterfaces.
4509         boolean reverse = false;
4510         Type target = to;
4511         if ((to.tsym.flags() & INTERFACE) == 0) {
4512             Assert.check((from.tsym.flags() & INTERFACE) != 0);
4513             reverse = true;
4514             to = from;
4515             from = target;
4516         }
4517         List<Type> commonSupers = superClosure(to, erasure(from));
4518         boolean giveWarning = commonSupers.isEmpty();
4519         // The arguments to the supers could be unified here to
4520         // get a more accurate analysis
4521         while (commonSupers.nonEmpty()) {
4522             Type t1 = asSuper(from, commonSupers.head.tsym);
4523             Type t2 = commonSupers.head; // same as asSuper(to, commonSupers.head.tsym);
4524             if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
4525                 return false;
4526             giveWarning = giveWarning || (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2));
4527             commonSupers = commonSupers.tail;
4528         }
4529         if (giveWarning && !isReifiable(reverse ? from : to))
4530             warn.warn(LintCategory.UNCHECKED);
4531         return true;
4532     }
4533 
4534     private boolean sideCastFinal(Type from, Type to, Warner warn) {
4535         // We are casting from type $from$ to type $to$, which are
4536         // unrelated types one of which is final and the other of
4537         // which is an interface.  This method
4538         // tries to reject a cast by transferring type parameters
4539         // from the final class to the interface.
4540         boolean reverse = false;
4541         Type target = to;
4542         if ((to.tsym.flags() & INTERFACE) == 0) {
4543             Assert.check((from.tsym.flags() & INTERFACE) != 0);
4544             reverse = true;
4545             to = from;
4546             from = target;
4547         }
4548         Assert.check((from.tsym.flags() & FINAL) != 0);
4549         Type t1 = asSuper(from, to.tsym);
4550         if (t1 == null) return false;
4551         Type t2 = to;
4552         if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments()))
4553             return false;
4554         if (!isReifiable(target) &&
4555             (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2)))
4556             warn.warn(LintCategory.UNCHECKED);
4557         return true;
4558     }
4559 
4560     private boolean giveWarning(Type from, Type to) {
4561         List<Type> bounds = to.isCompound() ?
4562                 directSupertypes(to) : List.of(to);
4563         for (Type b : bounds) {
4564             Type subFrom = asSub(from, b.tsym);
4565             if (b.isParameterized() &&
4566                     (!(isUnbounded(b) ||
4567                     isSubtype(from, b) ||
4568                     ((subFrom != null) && containsType(b.allparams(), subFrom.allparams()))))) {
4569                 return true;
4570             }
4571         }
4572         return false;
4573     }
4574 
4575     private List<Type> superClosure(Type t, Type s) {
4576         List<Type> cl = List.nil();
4577         for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) {
4578             if (isSubtype(s, erasure(l.head))) {
4579                 cl = insert(cl, l.head);
4580             } else {
4581                 cl = union(cl, superClosure(l.head, s));
4582             }
4583         }
4584         return cl;
4585     }
4586 
4587     private boolean containsTypeEquivalent(Type t, Type s) {
4588         return isSameType(t, s) || // shortcut
4589             containsType(t, s) && containsType(s, t);
4590     }
4591 
4592     // <editor-fold defaultstate="collapsed" desc="adapt">
4593     /**
4594      * Adapt a type by computing a substitution which maps a source
4595      * type to a target type.
4596      *
4597      * @param source    the source type
4598      * @param target    the target type
4599      * @param from      the type variables of the computed substitution
4600      * @param to        the types of the computed substitution.
4601      */
4602     public void adapt(Type source,
4603                        Type target,
4604                        ListBuffer<Type> from,
4605                        ListBuffer<Type> to) throws AdaptFailure {
4606         new Adapter(from, to).adapt(source, target);
4607     }
4608 
4609     class Adapter extends SimpleVisitor<Void, Type> {
4610 
4611         ListBuffer<Type> from;
4612         ListBuffer<Type> to;
4613         Map<Symbol,Type> mapping;
4614 
4615         Adapter(ListBuffer<Type> from, ListBuffer<Type> to) {
4616             this.from = from;
4617             this.to = to;
4618             mapping = new HashMap<>();
4619         }
4620 
4621         public void adapt(Type source, Type target) throws AdaptFailure {
4622             visit(source, target);
4623             List<Type> fromList = from.toList();
4624             List<Type> toList = to.toList();
4625             while (!fromList.isEmpty()) {
4626                 Type val = mapping.get(fromList.head.tsym);
4627                 if (toList.head != val)
4628                     toList.head = val;
4629                 fromList = fromList.tail;
4630                 toList = toList.tail;
4631             }
4632         }
4633 
4634         @Override
4635         public Void visitClassType(ClassType source, Type target) throws AdaptFailure {
4636             if (target.hasTag(CLASS))
4637                 adaptRecursive(source.allparams(), target.allparams());
4638             return null;
4639         }
4640 
4641         @Override
4642         public Void visitArrayType(ArrayType source, Type target) throws AdaptFailure {
4643             if (target.hasTag(ARRAY))
4644                 adaptRecursive(elemtype(source), elemtype(target));
4645             return null;
4646         }
4647 
4648         @Override
4649         public Void visitWildcardType(WildcardType source, Type target) throws AdaptFailure {
4650             if (source.isExtendsBound())
4651                 adaptRecursive(wildUpperBound(source), wildUpperBound(target));
4652             else if (source.isSuperBound())
4653                 adaptRecursive(wildLowerBound(source), wildLowerBound(target));
4654             return null;
4655         }
4656 
4657         @Override
4658         public Void visitTypeVar(TypeVar source, Type target) throws AdaptFailure {
4659             // Check to see if there is
4660             // already a mapping for $source$, in which case
4661             // the old mapping will be merged with the new
4662             Type val = mapping.get(source.tsym);
4663             if (val != null) {
4664                 if (val.isSuperBound() && target.isSuperBound()) {
4665                     val = isSubtype(wildLowerBound(val), wildLowerBound(target))
4666                         ? target : val;
4667                 } else if (val.isExtendsBound() && target.isExtendsBound()) {
4668                     val = isSubtype(wildUpperBound(val), wildUpperBound(target))
4669                         ? val : target;
4670                 } else if (!isSameType(val, target)) {
4671                     throw new AdaptFailure();
4672                 }
4673             } else {
4674                 val = target;
4675                 from.append(source);
4676                 to.append(target);
4677             }
4678             mapping.put(source.tsym, val);
4679             return null;
4680         }
4681 
4682         @Override
4683         public Void visitType(Type source, Type target) {
4684             return null;
4685         }
4686 
4687         private Set<TypePair> cache = new HashSet<>();
4688 
4689         private void adaptRecursive(Type source, Type target) {
4690             TypePair pair = new TypePair(source, target);
4691             if (cache.add(pair)) {
4692                 try {
4693                     visit(source, target);
4694                 } finally {
4695                     cache.remove(pair);
4696                 }
4697             }
4698         }
4699 
4700         private void adaptRecursive(List<Type> source, List<Type> target) {
4701             if (source.length() == target.length()) {
4702                 while (source.nonEmpty()) {
4703                     adaptRecursive(source.head, target.head);
4704                     source = source.tail;
4705                     target = target.tail;
4706                 }
4707             }
4708         }
4709     }
4710 
4711     public static class AdaptFailure extends RuntimeException {
4712         static final long serialVersionUID = -7490231548272701566L;
4713     }
4714 
4715     private void adaptSelf(Type t,
4716                            ListBuffer<Type> from,
4717                            ListBuffer<Type> to) {
4718         try {
4719             //if (t.tsym.type != t)
4720                 adapt(t.tsym.type, t, from, to);
4721         } catch (AdaptFailure ex) {
4722             // Adapt should never fail calculating a mapping from
4723             // t.tsym.type to t as there can be no merge problem.
4724             throw new AssertionError(ex);
4725         }
4726     }
4727     // </editor-fold>
4728 
4729     /**
4730      * Rewrite all type variables (universal quantifiers) in the given
4731      * type to wildcards (existential quantifiers).  This is used to
4732      * determine if a cast is allowed.  For example, if high is true
4733      * and {@code T <: Number}, then {@code List<T>} is rewritten to
4734      * {@code List<?  extends Number>}.  Since {@code List<Integer> <:
4735      * List<? extends Number>} a {@code List<T>} can be cast to {@code
4736      * List<Integer>} with a warning.
4737      * @param t a type
4738      * @param high if true return an upper bound; otherwise a lower
4739      * bound
4740      * @param rewriteTypeVars only rewrite captured wildcards if false;
4741      * otherwise rewrite all type variables
4742      * @return the type rewritten with wildcards (existential
4743      * quantifiers) only
4744      */
4745     private Type rewriteQuantifiers(Type t, boolean high, boolean rewriteTypeVars) {
4746         return new Rewriter(high, rewriteTypeVars).visit(t);
4747     }
4748 
4749     class Rewriter extends UnaryVisitor<Type> {
4750 
4751         boolean high;
4752         boolean rewriteTypeVars;
4753         // map to avoid visiting same type argument twice, like in Foo<T>.Bar<T>
4754         Map<Type, Type> argMap = new HashMap<>();
4755         // cycle detection within an argument, see JDK-8324809
4756         Set<Type> seen = new HashSet<>();
4757 
4758         Rewriter(boolean high, boolean rewriteTypeVars) {
4759             this.high = high;
4760             this.rewriteTypeVars = rewriteTypeVars;
4761         }
4762 
4763         @Override
4764         public Type visitClassType(ClassType t, Void s) {
4765             ListBuffer<Type> rewritten = new ListBuffer<>();
4766             boolean changed = false;
4767             for (Type arg : t.allparams()) {
4768                 Type bound = argMap.get(arg);
4769                 if (bound == null) {
4770                     argMap.put(arg, bound = visit(arg));
4771                 }
4772                 if (arg != bound) {
4773                     changed = true;
4774                 }
4775                 rewritten.append(bound);
4776             }
4777             if (changed)
4778                 return subst(t.tsym.type,
4779                         t.tsym.type.allparams(),
4780                         rewritten.toList());
4781             else
4782                 return t;
4783         }
4784 
4785         public Type visitType(Type t, Void s) {
4786             return t;
4787         }
4788 
4789         @Override
4790         public Type visitCapturedType(CapturedType t, Void s) {
4791             Type w_bound = t.wildcard.type;
4792             Type bound = w_bound.contains(t) ?
4793                         erasure(w_bound) :
4794                         visit(w_bound);
4795             return rewriteAsWildcardType(visit(bound), t.wildcard.bound, t.wildcard.kind);
4796         }
4797 
4798         @Override
4799         public Type visitTypeVar(TypeVar t, Void s) {
4800             if (seen.add(t)) {
4801                 if (rewriteTypeVars) {
4802                     Type bound = t.getUpperBound().contains(t) ?
4803                             erasure(t.getUpperBound()) :
4804                             visit(t.getUpperBound());
4805                     return rewriteAsWildcardType(bound, t, EXTENDS);
4806                 } else {
4807                     return t;
4808                 }
4809             } else {
4810                 return rewriteTypeVars ? makeExtendsWildcard(syms.objectType, t) : t;
4811             }
4812         }
4813 
4814         @Override
4815         public Type visitWildcardType(WildcardType t, Void s) {
4816             Type bound2 = visit(t.type);
4817             return t.type == bound2 ? t : rewriteAsWildcardType(bound2, t.bound, t.kind);
4818         }
4819 
4820         private Type rewriteAsWildcardType(Type bound, TypeVar formal, BoundKind bk) {
4821             switch (bk) {
4822                case EXTENDS: return high ?
4823                        makeExtendsWildcard(B(bound), formal) :
4824                        makeExtendsWildcard(syms.objectType, formal);
4825                case SUPER: return high ?
4826                        makeSuperWildcard(syms.botType, formal) :
4827                        makeSuperWildcard(B(bound), formal);
4828                case UNBOUND: return makeExtendsWildcard(syms.objectType, formal);
4829                default:
4830                    Assert.error("Invalid bound kind " + bk);
4831                    return null;
4832             }
4833         }
4834 
4835         Type B(Type t) {
4836             while (t.hasTag(WILDCARD)) {
4837                 WildcardType w = (WildcardType)t;
4838                 t = high ?
4839                     w.getExtendsBound() :
4840                     w.getSuperBound();
4841                 if (t == null) {
4842                     t = high ? syms.objectType : syms.botType;
4843                 }
4844             }
4845             return t;
4846         }
4847     }
4848 
4849 
4850     /**
4851      * Create a wildcard with the given upper (extends) bound; create
4852      * an unbounded wildcard if bound is Object.
4853      *
4854      * @param bound the upper bound
4855      * @param formal the formal type parameter that will be
4856      * substituted by the wildcard
4857      */
4858     private WildcardType makeExtendsWildcard(Type bound, TypeVar formal) {
4859         if (bound == syms.objectType) {
4860             return new WildcardType(syms.objectType,
4861                                     BoundKind.UNBOUND,
4862                                     syms.boundClass,
4863                                     formal);
4864         } else {
4865             return new WildcardType(bound,
4866                                     BoundKind.EXTENDS,
4867                                     syms.boundClass,
4868                                     formal);
4869         }
4870     }
4871 
4872     /**
4873      * Create a wildcard with the given lower (super) bound; create an
4874      * unbounded wildcard if bound is bottom (type of {@code null}).
4875      *
4876      * @param bound the lower bound
4877      * @param formal the formal type parameter that will be
4878      * substituted by the wildcard
4879      */
4880     private WildcardType makeSuperWildcard(Type bound, TypeVar formal) {
4881         if (bound.hasTag(BOT)) {
4882             return new WildcardType(syms.objectType,
4883                                     BoundKind.UNBOUND,
4884                                     syms.boundClass,
4885                                     formal);
4886         } else {
4887             return new WildcardType(bound,
4888                                     BoundKind.SUPER,
4889                                     syms.boundClass,
4890                                     formal);
4891         }
4892     }
4893 
4894     /**
4895      * A wrapper for a type that allows use in sets.
4896      */
4897     public static class UniqueType {
4898         public final Type type;
4899         final Types types;

4900 
4901         public UniqueType(Type type, Types types) {
4902             this.type = type;
4903             this.types = types;





4904         }
4905 
4906         public int hashCode() {
4907             return types.hashCode(type);
4908         }
4909 
4910         public boolean equals(Object obj) {
4911             return (obj instanceof UniqueType uniqueType) &&
4912                     types.isSameType(type, uniqueType.type);
4913         }
4914 




4915         public String toString() {
4916             return type.toString();
4917         }
4918 
4919     }
4920     // </editor-fold>
4921 
4922     // <editor-fold defaultstate="collapsed" desc="Visitors">
4923     /**
4924      * A default visitor for types.  All visitor methods except
4925      * visitType are implemented by delegating to visitType.  Concrete
4926      * subclasses must provide an implementation of visitType and can
4927      * override other methods as needed.
4928      *
4929      * @param <R> the return type of the operation implemented by this
4930      * visitor; use Void if no return type is needed.
4931      * @param <S> the type of the second argument (the first being the
4932      * type itself) of the operation implemented by this visitor; use
4933      * Void if a second argument is not needed.
4934      */
4935     public abstract static class DefaultTypeVisitor<R,S> implements Type.Visitor<R,S> {
4936         public final R visit(Type t, S s)               { return t.accept(this, s); }
4937         public R visitClassType(ClassType t, S s)       { return visitType(t, s); }
4938         public R visitWildcardType(WildcardType t, S s) { return visitType(t, s); }
4939         public R visitArrayType(ArrayType t, S s)       { return visitType(t, s); }
4940         public R visitMethodType(MethodType t, S s)     { return visitType(t, s); }
4941         public R visitPackageType(PackageType t, S s)   { return visitType(t, s); }
4942         public R visitModuleType(ModuleType t, S s)     { return visitType(t, s); }
4943         public R visitTypeVar(TypeVar t, S s)           { return visitType(t, s); }
4944         public R visitCapturedType(CapturedType t, S s) { return visitType(t, s); }
4945         public R visitForAll(ForAll t, S s)             { return visitType(t, s); }
4946         public R visitUndetVar(UndetVar t, S s)         { return visitType(t, s); }
4947         public R visitErrorType(ErrorType t, S s)       { return visitType(t, s); }
4948     }
4949 
4950     /**
4951      * A default visitor for symbols.  All visitor methods except
4952      * visitSymbol are implemented by delegating to visitSymbol.  Concrete
4953      * subclasses must provide an implementation of visitSymbol and can
4954      * override other methods as needed.
4955      *
4956      * @param <R> the return type of the operation implemented by this
4957      * visitor; use Void if no return type is needed.
4958      * @param <S> the type of the second argument (the first being the
4959      * symbol itself) of the operation implemented by this visitor; use
4960      * Void if a second argument is not needed.
4961      */
4962     public abstract static class DefaultSymbolVisitor<R,S> implements Symbol.Visitor<R,S> {
4963         public final R visit(Symbol s, S arg)                   { return s.accept(this, arg); }
4964         public R visitClassSymbol(ClassSymbol s, S arg)         { return visitSymbol(s, arg); }
4965         public R visitMethodSymbol(MethodSymbol s, S arg)       { return visitSymbol(s, arg); }
4966         public R visitOperatorSymbol(OperatorSymbol s, S arg)   { return visitSymbol(s, arg); }
4967         public R visitPackageSymbol(PackageSymbol s, S arg)     { return visitSymbol(s, arg); }
4968         public R visitTypeSymbol(TypeSymbol s, S arg)           { return visitSymbol(s, arg); }
4969         public R visitVarSymbol(VarSymbol s, S arg)             { return visitSymbol(s, arg); }
4970     }
4971 
4972     /**
4973      * A <em>simple</em> visitor for types.  This visitor is simple as
4974      * captured wildcards, for-all types (generic methods), and
4975      * undetermined type variables (part of inference) are hidden.
4976      * Captured wildcards are hidden by treating them as type
4977      * variables and the rest are hidden by visiting their qtypes.
4978      *
4979      * @param <R> the return type of the operation implemented by this
4980      * visitor; use Void if no return type is needed.
4981      * @param <S> the type of the second argument (the first being the
4982      * type itself) of the operation implemented by this visitor; use
4983      * Void if a second argument is not needed.
4984      */
4985     public abstract static class SimpleVisitor<R,S> extends DefaultTypeVisitor<R,S> {
4986         @Override
4987         public R visitCapturedType(CapturedType t, S s) {
4988             return visitTypeVar(t, s);
4989         }
4990         @Override
4991         public R visitForAll(ForAll t, S s) {
4992             return visit(t.qtype, s);
4993         }
4994         @Override
4995         public R visitUndetVar(UndetVar t, S s) {
4996             return visit(t.qtype, s);
4997         }
4998     }
4999 
5000     /**
5001      * A plain relation on types.  That is a 2-ary function on the
5002      * form Type&nbsp;&times;&nbsp;Type&nbsp;&rarr;&nbsp;Boolean.
5003      * <!-- In plain text: Type x Type -> Boolean -->
5004      */
5005     public abstract static class TypeRelation extends SimpleVisitor<Boolean,Type> {}
5006 
5007     /**
5008      * A convenience visitor for implementing operations that only
5009      * require one argument (the type itself), that is, unary
5010      * operations.
5011      *
5012      * @param <R> the return type of the operation implemented by this
5013      * visitor; use Void if no return type is needed.
5014      */
5015     public abstract static class UnaryVisitor<R> extends SimpleVisitor<R,Void> {
5016         public final R visit(Type t) { return t.accept(this, null); }
5017     }
5018 
5019     /**
5020      * A visitor for implementing a mapping from types to types.  The
5021      * default behavior of this class is to implement the identity
5022      * mapping (mapping a type to itself).  This can be overridden in
5023      * subclasses.
5024      *
5025      * @param <S> the type of the second argument (the first being the
5026      * type itself) of this mapping; use Void if a second argument is
5027      * not needed.
5028      */
5029     public static class MapVisitor<S> extends DefaultTypeVisitor<Type,S> {
5030         public final Type visit(Type t) { return t.accept(this, null); }
5031         public Type visitType(Type t, S s) { return t; }
5032     }
5033 
5034     /**
5035      * An abstract class for mappings from types to types (see {@link Type#map(TypeMapping)}.
5036      * This class implements the functional interface {@code Function}, that allows it to be used
5037      * fluently in stream-like processing.
5038      */
5039     public static class TypeMapping<S> extends MapVisitor<S> implements Function<Type, Type> {
5040         @Override
5041         public Type apply(Type type) { return visit(type); }
5042 
5043         List<Type> visit(List<Type> ts, S s) {
5044             return ts.map(t -> visit(t, s));
5045         }
5046 
5047         @Override
5048         public Type visitCapturedType(CapturedType t, S s) {
5049             return visitTypeVar(t, s);
5050         }
5051     }
5052     // </editor-fold>
5053 
5054     // <editor-fold defaultstate="collapsed" desc="Unconditionality">
5055     /** Check unconditionality between any combination of reference or primitive types.
5056      *
5057      *  Rules:
5058      *    an identity conversion
5059      *    a widening reference conversion
5060      *    a widening primitive conversion (delegates to `checkUnconditionallyExactPrimitives`)
5061      *    a boxing conversion
5062      *    a boxing conversion followed by a widening reference conversion
5063      *
5064      *  @param source     Source primitive or reference type
5065      *  @param target     Target primitive or reference type
5066      */
5067     public boolean isUnconditionallyExact(Type source, Type target) {
5068         if (isSameType(source, target)) {
5069             return true;
5070         }
5071 
5072         return target.isPrimitive()
5073                 ? isUnconditionallyExactPrimitives(source, target)
5074                 : isSubtype(boxedTypeOrType(erasure(source)), target);
5075     }
5076 
5077     /** Check unconditionality between primitive types.
5078      *
5079      *  - widening from one integral type to another,
5080      *  - widening from one floating point type to another,
5081      *  - widening from byte, short, or char to a floating point type,
5082      *  - widening from int to double.
5083      *
5084      *  @param selectorType     Type of selector
5085      *  @param targetType       Target type
5086      */
5087     public boolean isUnconditionallyExactPrimitives(Type selectorType, Type targetType) {
5088         if (isSameType(selectorType, targetType)) {
5089             return true;
5090         }
5091 
5092         return (selectorType.isPrimitive() && targetType.isPrimitive()) &&
5093                 ((selectorType.hasTag(BYTE) && !targetType.hasTag(CHAR)) ||
5094                  (selectorType.hasTag(SHORT) && (selectorType.getTag().isStrictSubRangeOf(targetType.getTag()))) ||
5095                  (selectorType.hasTag(CHAR)  && (selectorType.getTag().isStrictSubRangeOf(targetType.getTag())))  ||
5096                  (selectorType.hasTag(INT)   && (targetType.hasTag(DOUBLE) || targetType.hasTag(LONG))) ||
5097                  (selectorType.hasTag(FLOAT) && (selectorType.getTag().isStrictSubRangeOf(targetType.getTag()))));
5098     }
5099     // </editor-fold>
5100 
5101     // <editor-fold defaultstate="collapsed" desc="Annotation support">
5102 
5103     public RetentionPolicy getRetention(Attribute.Compound a) {
5104         return getRetention(a.type.tsym);
5105     }
5106 
5107     public RetentionPolicy getRetention(TypeSymbol sym) {
5108         RetentionPolicy vis = RetentionPolicy.CLASS; // the default
5109         Attribute.Compound c = sym.attribute(syms.retentionType.tsym);
5110         if (c != null) {
5111             Attribute value = c.member(names.value);
5112             if (value != null && value instanceof Attribute.Enum attributeEnum) {
5113                 Name levelName = attributeEnum.value.name;
5114                 if (levelName == names.SOURCE) vis = RetentionPolicy.SOURCE;
5115                 else if (levelName == names.CLASS) vis = RetentionPolicy.CLASS;
5116                 else if (levelName == names.RUNTIME) vis = RetentionPolicy.RUNTIME;
5117                 else ;// /* fail soft */ throw new AssertionError(levelName);
5118             }
5119         }
5120         return vis;
5121     }
5122     // </editor-fold>
5123 
5124     // <editor-fold defaultstate="collapsed" desc="Signature Generation">
5125 
5126     public abstract class SignatureGenerator {
5127 
5128         public class InvalidSignatureException extends CompilerInternalException {
5129             private static final long serialVersionUID = 0;
5130 
5131             private final transient Type type;
5132 
5133             InvalidSignatureException(Type type, boolean dumpStackTraceOnError) {
5134                 super(dumpStackTraceOnError);
5135                 this.type = type;
5136             }
5137 
5138             public Type type() {
5139                 return type;
5140             }
5141         }
5142 
5143         protected abstract void append(char ch);
5144         protected abstract void append(byte[] ba);
5145         protected abstract void append(Name name);
5146         protected void classReference(ClassSymbol c) { /* by default: no-op */ }
5147 
5148         protected void reportIllegalSignature(Type t) {
5149             throw new InvalidSignatureException(t, Types.this.dumpStacktraceOnError);
5150         }
5151 
5152         /**
5153          * Assemble signature of given type in string buffer.
5154          */
5155         public void assembleSig(Type type) {
5156             switch (type.getTag()) {
5157                 case BYTE:
5158                     append('B');
5159                     break;
5160                 case SHORT:
5161                     append('S');
5162                     break;
5163                 case CHAR:
5164                     append('C');
5165                     break;
5166                 case INT:
5167                     append('I');
5168                     break;
5169                 case LONG:
5170                     append('J');
5171                     break;
5172                 case FLOAT:
5173                     append('F');
5174                     break;
5175                 case DOUBLE:
5176                     append('D');
5177                     break;
5178                 case BOOLEAN:
5179                     append('Z');
5180                     break;
5181                 case VOID:
5182                     append('V');
5183                     break;
5184                 case CLASS:
5185                     if (type.isCompound()) {
5186                         reportIllegalSignature(type);
5187                     }
5188                     append('L');
5189                     assembleClassSig(type);
5190                     append(';');
5191                     break;
5192                 case ARRAY:
5193                     ArrayType at = (ArrayType) type;
5194                     append('[');
5195                     assembleSig(at.elemtype);
5196                     break;
5197                 case METHOD:
5198                     MethodType mt = (MethodType) type;
5199                     append('(');
5200                     assembleSig(mt.argtypes);
5201                     append(')');
5202                     assembleSig(mt.restype);
5203                     if (hasTypeVar(mt.thrown)) {
5204                         for (List<Type> l = mt.thrown; l.nonEmpty(); l = l.tail) {
5205                             append('^');
5206                             assembleSig(l.head);
5207                         }
5208                     }
5209                     break;
5210                 case WILDCARD: {
5211                     Type.WildcardType ta = (Type.WildcardType) type;
5212                     switch (ta.kind) {
5213                         case SUPER:
5214                             append('-');
5215                             assembleSig(ta.type);
5216                             break;
5217                         case EXTENDS:
5218                             append('+');
5219                             assembleSig(ta.type);
5220                             break;
5221                         case UNBOUND:
5222                             append('*');
5223                             break;
5224                         default:
5225                             throw new AssertionError(ta.kind);
5226                     }
5227                     break;
5228                 }
5229                 case TYPEVAR:
5230                     if (((TypeVar)type).isCaptured()) {
5231                         reportIllegalSignature(type);
5232                     }
5233                     append('T');
5234                     append(type.tsym.name);
5235                     append(';');
5236                     break;
5237                 case FORALL:
5238                     Type.ForAll ft = (Type.ForAll) type;
5239                     assembleParamsSig(ft.tvars);
5240                     assembleSig(ft.qtype);
5241                     break;
5242                 default:
5243                     throw new AssertionError("typeSig " + type.getTag());
5244             }
5245         }
5246 
5247         public boolean hasTypeVar(List<Type> l) {
5248             while (l.nonEmpty()) {
5249                 if (l.head.hasTag(TypeTag.TYPEVAR)) {
5250                     return true;
5251                 }
5252                 l = l.tail;
5253             }
5254             return false;
5255         }
5256 
5257         public void assembleClassSig(Type type) {
5258             ClassType ct = (ClassType) type;
5259             ClassSymbol c = (ClassSymbol) ct.tsym;
5260             classReference(c);
5261             Type outer = ct.getEnclosingType();
5262             if (outer.allparams().nonEmpty()) {
5263                 boolean rawOuter =
5264                         c.owner.kind == MTH || // either a local class
5265                         c.name == Types.this.names.empty; // or anonymous
5266                 assembleClassSig(rawOuter
5267                         ? Types.this.erasure(outer)
5268                         : outer);
5269                 append(rawOuter ? '$' : '.');
5270                 Assert.check(c.flatname.startsWith(c.owner.enclClass().flatname));
5271                 append(rawOuter
5272                         ? c.flatname.subName(c.owner.enclClass().flatname.length() + 1)
5273                         : c.name);
5274             } else {
5275                 append(externalize(c.flatname));
5276             }
5277             if (ct.getTypeArguments().nonEmpty()) {
5278                 append('<');
5279                 assembleSig(ct.getTypeArguments());
5280                 append('>');
5281             }
5282         }
5283 
5284         public void assembleParamsSig(List<Type> typarams) {
5285             append('<');
5286             for (List<Type> ts = typarams; ts.nonEmpty(); ts = ts.tail) {
5287                 Type.TypeVar tvar = (Type.TypeVar) ts.head;
5288                 append(tvar.tsym.name);
5289                 List<Type> bounds = Types.this.getBounds(tvar);
5290                 if ((bounds.head.tsym.flags() & INTERFACE) != 0) {
5291                     append(':');
5292                 }
5293                 for (List<Type> l = bounds; l.nonEmpty(); l = l.tail) {
5294                     append(':');
5295                     assembleSig(l.head);
5296                 }
5297             }
5298             append('>');
5299         }
5300 
5301         public void assembleSig(List<Type> types) {
5302             for (List<Type> ts = types; ts.nonEmpty(); ts = ts.tail) {
5303                 assembleSig(ts.head);
5304             }
5305         }
5306     }
5307 
5308     public Type constantType(LoadableConstant c) {
5309         switch (c.poolTag()) {
5310             case ClassFile.CONSTANT_Class:
5311                 return syms.classType;
5312             case ClassFile.CONSTANT_String:
5313                 return syms.stringType;
5314             case ClassFile.CONSTANT_Integer:
5315                 return syms.intType;
5316             case ClassFile.CONSTANT_Float:
5317                 return syms.floatType;
5318             case ClassFile.CONSTANT_Long:
5319                 return syms.longType;
5320             case ClassFile.CONSTANT_Double:
5321                 return syms.doubleType;
5322             case ClassFile.CONSTANT_MethodHandle:
5323                 return syms.methodHandleType;
5324             case ClassFile.CONSTANT_MethodType:
5325                 return syms.methodTypeType;
5326             case ClassFile.CONSTANT_Dynamic:
5327                 return ((DynamicVarSymbol)c).type;
5328             default:
5329                 throw new AssertionError("Not a loadable constant: " + c.poolTag());
5330         }
5331     }
5332     // </editor-fold>
5333 
5334     public void newRound() {
5335         descCache._map.clear();
5336         isDerivedRawCache.clear();
5337         implCache._map.clear();
5338         membersCache._map.clear();
5339         closureCache.clear();
5340     }
5341 }
--- EOF ---