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