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