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