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