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