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