1 /*
   2  * Copyright (c) 1999, 2021, 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.annotation.Annotation;
  29 import java.util.ArrayDeque;
  30 import java.util.Collections;
  31 import java.util.EnumMap;
  32 import java.util.Map;
  33 import java.util.function.Predicate;
  34 
  35 import javax.lang.model.type.*;
  36 
  37 import com.sun.tools.javac.code.Symbol.*;
  38 import com.sun.tools.javac.code.Type.ClassType.Flavor;
  39 import com.sun.tools.javac.code.TypeMetadata.Entry;
  40 import com.sun.tools.javac.code.Types.TypeMapping;
  41 import com.sun.tools.javac.code.Types.UniqueType;
  42 import com.sun.tools.javac.comp.Infer.IncorporationAction;
  43 import com.sun.tools.javac.jvm.ClassFile;
  44 import com.sun.tools.javac.jvm.PoolConstant;
  45 import com.sun.tools.javac.util.*;
  46 import com.sun.tools.javac.util.DefinedBy.Api;
  47 
  48 import static com.sun.tools.javac.code.BoundKind.*;
  49 import static com.sun.tools.javac.code.Flags.*;
  50 import static com.sun.tools.javac.code.Kinds.Kind.*;
  51 import static com.sun.tools.javac.code.TypeTag.*;
  52 
  53 /** This class represents Java types. The class itself defines the behavior of
  54  *  the following types:
  55  *  <pre>
  56  *  base types (tags: BYTE, CHAR, SHORT, INT, LONG, FLOAT, DOUBLE, BOOLEAN),
  57  *  type `void' (tag: VOID),
  58  *  the bottom type (tag: BOT),
  59  *  the missing type (tag: NONE).
  60  *  </pre>
  61  *  <p>The behavior of the following types is defined in subclasses, which are
  62  *  all static inner classes of this class:
  63  *  <pre>
  64  *  class types (tag: CLASS, class: ClassType),
  65  *  array types (tag: ARRAY, class: ArrayType),
  66  *  method types (tag: METHOD, class: MethodType),
  67  *  package types (tag: PACKAGE, class: PackageType),
  68  *  type variables (tag: TYPEVAR, class: TypeVar),
  69  *  type arguments (tag: WILDCARD, class: WildcardType),
  70  *  generic method types (tag: FORALL, class: ForAll),
  71  *  the error type (tag: ERROR, class: ErrorType).
  72  *  </pre>
  73  *
  74  *  <p><b>This is NOT part of any supported API.
  75  *  If you write code that depends on this, you do so at your own risk.
  76  *  This code and its internal interfaces are subject to change or
  77  *  deletion without notice.</b>
  78  *
  79  *  @see TypeTag
  80  */
  81 public abstract class Type extends AnnoConstruct implements TypeMirror, PoolConstant {
  82 
  83     /**
  84      * Type metadata,  Should be {@code null} for the default value.
  85      *
  86      * Note: it is an invariant that for any {@code TypeMetadata}
  87      * class, a given {@code Type} may have at most one metadata array
  88      * entry of that class.
  89      */
  90     protected final TypeMetadata metadata;
  91 
  92     public TypeMetadata getMetadata() {
  93         return metadata;
  94     }
  95 
  96     public Entry getMetadataOfKind(final Entry.Kind kind) {
  97         return metadata != null ? metadata.get(kind) : null;
  98     }
  99 
 100     /** Constant type: no type at all. */
 101     public static final JCNoType noType = new JCNoType() {
 102         @Override @DefinedBy(Api.LANGUAGE_MODEL)
 103         public String toString() {
 104             return "none";
 105         }
 106     };
 107 
 108     /** Constant type: special type to be used during recovery of deferred expressions. */
 109     public static final JCNoType recoveryType = new JCNoType(){
 110         @Override @DefinedBy(Api.LANGUAGE_MODEL)
 111         public String toString() {
 112             return "recovery";
 113         }
 114     };
 115 
 116     /** Constant type: special type to be used for marking stuck trees. */
 117     public static final JCNoType stuckType = new JCNoType() {
 118         @Override @DefinedBy(Api.LANGUAGE_MODEL)
 119         public String toString() {
 120             return "stuck";
 121         }
 122     };
 123 
 124     /** If this switch is turned on, the names of type variables
 125      *  and anonymous classes are printed with hashcodes appended.
 126      */
 127     public static boolean moreInfo = false;
 128 
 129     /** The defining class / interface / package / type variable.
 130      */
 131     public TypeSymbol tsym;
 132 
 133     @Override
 134     public int poolTag() {
 135         throw new AssertionError("Invalid pool entry");
 136     }
 137 
 138     @Override
 139     public Object poolKey(Types types) {
 140         return new UniqueType(this, types);
 141     }
 142 
 143     /**
 144      * Checks if the current type tag is equal to the given tag.
 145      * @return true if tag is equal to the current type tag.
 146      */
 147     public boolean hasTag(TypeTag tag) {
 148         return tag == getTag();
 149     }
 150 
 151     /**
 152      * Returns the current type tag.
 153      * @return the value of the current type tag.
 154      */
 155     public abstract TypeTag getTag();
 156 
 157     public boolean isNumeric() {
 158         return false;
 159     }
 160 
 161     public boolean isIntegral() {
 162         return false;
 163     }
 164 
 165     public boolean isPrimitive() {
 166         return false;
 167     }
 168 
 169     public boolean isPrimitiveOrVoid() {
 170         return false;
 171     }
 172 
 173     public boolean isReference() {
 174         return false;
 175     }
 176 
 177     public boolean isNullOrReference() {
 178         return false;
 179     }
 180 
 181     public boolean isPartial() {
 182         return false;
 183     }
 184 
 185     /**
 186      * The constant value of this type, null if this type does not
 187      * have a constant value attribute. Only primitive types and
 188      * strings (ClassType) can have a constant value attribute.
 189      * @return the constant value attribute of this type
 190      */
 191     public Object constValue() {
 192         return null;
 193     }
 194 
 195     /** Is this a constant type whose value is false?
 196      */
 197     public boolean isFalse() {
 198         return false;
 199     }
 200 
 201     /** Is this a constant type whose value is true?
 202      */
 203     public boolean isTrue() {
 204         return false;
 205     }
 206 
 207     /**
 208      * Get the representation of this type used for modelling purposes.
 209      * By default, this is itself. For ErrorType, a different value
 210      * may be provided.
 211      */
 212     public Type getModelType() {
 213         return this;
 214     }
 215 
 216     public static List<Type> getModelTypes(List<Type> ts) {
 217         ListBuffer<Type> lb = new ListBuffer<>();
 218         for (Type t: ts)
 219             lb.append(t.getModelType());
 220         return lb.toList();
 221     }
 222 
 223     /**For ErrorType, returns the original type, otherwise returns the type itself.
 224      */
 225     public Type getOriginalType() {
 226         return this;
 227     }
 228 
 229     public <R,S> R accept(Type.Visitor<R,S> v, S s) { return v.visitType(this, s); }
 230 
 231     /** Define a type given its tag, type symbol, and type annotations
 232      */
 233 
 234     public Type(TypeSymbol tsym, TypeMetadata metadata) {
 235         Assert.checkNonNull(metadata);
 236         this.tsym = tsym;
 237         this.metadata = metadata;
 238     }
 239 
 240     public boolean isPrimitiveClass() {
 241         return false;
 242     }
 243 
 244     public boolean isValueClass() {
 245         return false;
 246     }
 247 
 248     /**
 249      * Return the `flavor' associated with a ClassType.
 250      * @see ClassType.Flavor
 251      */
 252     public Flavor getFlavor() {
 253         throw new AssertionError("Unexpected call to getFlavor() on a Type that is not a ClassType: " + this);
 254     }
 255 
 256     /**
 257      * @return true IFF the receiver is a reference projection of a primitive class type and false
 258      * for primitives or plain references
 259      */
 260     public boolean isReferenceProjection() {
 261         return false;
 262     }
 263 
 264     /**
 265      * @return the value projection type IFF the receiver is a reference projection of a primitive class type
 266      * and null otherwise
 267      */
 268     public Type valueProjection() {
 269         return null;
 270     }
 271 
 272     /**
 273      * @return the reference projection type IFF the receiver is a primitive class type
 274      * and null otherwise
 275      */
 276     public Type referenceProjection() {
 277         return null;
 278     }
 279 
 280     /**
 281      * @return the reference projection type IFF the receiver is a primitive class type or self otherwise.
 282      */
 283     public Type referenceProjectionOrSelf() {
 284         Type projection = referenceProjection();
 285         return projection != null ? projection : this;
 286     }
 287 
 288     /**
 289      * A subclass of {@link Types.TypeMapping} which applies a mapping recursively to the subterms
 290      * of a given type expression. This mapping returns the original type is no changes occurred
 291      * when recursively mapping the original type's subterms.
 292      */
 293     public abstract static class StructuralTypeMapping<S> extends Types.TypeMapping<S> {
 294 
 295         @Override
 296         public Type visitClassType(ClassType t, S s) {
 297             Type outer = t.getEnclosingType();
 298             Type outer1 = visit(outer, s);
 299             List<Type> typarams = t.getTypeArguments();
 300             List<Type> typarams1 = visit(typarams, s);
 301             if (outer1 == outer && typarams1 == typarams) return t;
 302             else return new ClassType(outer1, typarams1, t.tsym, t.metadata, t.getFlavor()) {
 303                 @Override
 304                 protected boolean needsStripping() {
 305                     return true;
 306                 }
 307             };
 308         }
 309 
 310         @Override
 311         public Type visitWildcardType(WildcardType wt, S s) {
 312             Type t = wt.type;
 313             if (t != null)
 314                 t = visit(t, s);
 315             if (t == wt.type)
 316                 return wt;
 317             else
 318                 return new WildcardType(t, wt.kind, wt.tsym, wt.bound, wt.metadata) {
 319                     @Override
 320                     protected boolean needsStripping() {
 321                         return true;
 322                     }
 323                 };
 324         }
 325 
 326         @Override
 327         public Type visitArrayType(ArrayType t, S s) {
 328             Type elemtype = t.elemtype;
 329             Type elemtype1 = visit(elemtype, s);
 330             if (elemtype1 == elemtype) return t;
 331             else return new ArrayType(elemtype1, t.tsym, t.metadata) {
 332                 @Override
 333                 protected boolean needsStripping() {
 334                     return true;
 335                 }
 336             };
 337         }
 338 
 339         @Override
 340         public Type visitMethodType(MethodType t, S s) {
 341             List<Type> argtypes = t.argtypes;
 342             Type restype = t.restype;
 343             List<Type> thrown = t.thrown;
 344             List<Type> argtypes1 = visit(argtypes, s);
 345             Type restype1 = visit(restype, s);
 346             List<Type> thrown1 = visit(thrown, s);
 347             if (argtypes1 == argtypes &&
 348                 restype1 == restype &&
 349                 thrown1 == thrown) return t;
 350             else return new MethodType(argtypes1, restype1, thrown1, t.tsym) {
 351                 @Override
 352                 protected boolean needsStripping() {
 353                     return true;
 354                 }
 355             };
 356         }
 357 
 358         @Override
 359         public Type visitForAll(ForAll t, S s) {
 360             return visit(t.qtype, s);
 361         }
 362     }
 363 
 364     /** map a type function over all immediate descendants of this type
 365      */
 366     public <Z> Type map(TypeMapping<Z> mapping, Z arg) {
 367         return mapping.visit(this, arg);
 368     }
 369 
 370     /** map a type function over all immediate descendants of this type (no arg version)
 371      */
 372     public <Z> Type map(TypeMapping<Z> mapping) {
 373         return mapping.visit(this, null);
 374     }
 375 
 376     /** Define a constant type, of the same kind as this type
 377      *  and with given constant value
 378      */
 379     public Type constType(Object constValue) {
 380         throw new AssertionError();
 381     }
 382 
 383     /**
 384      * If this is a constant type, return its underlying type.
 385      * Otherwise, return the type itself.
 386      */
 387     public Type baseType() {
 388         return this;
 389     }
 390 
 391     /**
 392      * Returns the original version of this type, before metadata were added. This routine is meant
 393      * for internal use only (i.e. {@link Type#equalsIgnoreMetadata(Type)}, {@link Type#stripMetadata});
 394      * it should not be used outside this class.
 395      */
 396     protected Type typeNoMetadata() {
 397         return metadata == TypeMetadata.EMPTY ? this : baseType();
 398     }
 399 
 400     /**
 401      * Create a new copy of this type but with the specified TypeMetadata.
 402      */
 403     public abstract Type cloneWithMetadata(TypeMetadata metadata);
 404 
 405     /**
 406      * Does this type require annotation stripping for API clients?
 407      */
 408     protected boolean needsStripping() {
 409         return false;
 410     }
 411 
 412     /**
 413      * Strip all metadata associated with this type - this could return a new clone of the type.
 414      * This routine is only used to present the correct annotated types back to the users when types
 415      * are accessed through compiler APIs; it should not be used anywhere in the compiler internals
 416      * as doing so might result in performance penalties.
 417      */
 418     public Type stripMetadataIfNeeded() {
 419         return needsStripping() ?
 420                 accept(stripMetadata, null) :
 421                 this;
 422     }
 423 
 424     public Type stripMetadata() {
 425         return accept(stripMetadata, null);
 426     }
 427     //where
 428         private static final TypeMapping<Void> stripMetadata = new StructuralTypeMapping<Void>() {
 429             @Override
 430             public Type visitClassType(ClassType t, Void aVoid) {
 431                 return super.visitClassType((ClassType)t.typeNoMetadata(), aVoid);
 432             }
 433 
 434             @Override
 435             public Type visitArrayType(ArrayType t, Void aVoid) {
 436                 return super.visitArrayType((ArrayType)t.typeNoMetadata(), aVoid);
 437             }
 438 
 439             @Override
 440             public Type visitTypeVar(TypeVar t, Void aVoid) {
 441                 return super.visitTypeVar((TypeVar)t.typeNoMetadata(), aVoid);
 442             }
 443 
 444             @Override
 445             public Type visitWildcardType(WildcardType wt, Void aVoid) {
 446                 return super.visitWildcardType((WildcardType)wt.typeNoMetadata(), aVoid);
 447             }
 448         };
 449 
 450     public Type annotatedType(final List<Attribute.TypeCompound> annos) {
 451         final Entry annoMetadata = new TypeMetadata.Annotations(annos);
 452         return cloneWithMetadata(metadata.combine(annoMetadata));
 453     }
 454 
 455     public boolean isAnnotated() {
 456         final TypeMetadata.Annotations metadata =
 457             (TypeMetadata.Annotations)getMetadataOfKind(Entry.Kind.ANNOTATIONS);
 458 
 459         return null != metadata && !metadata.getAnnotations().isEmpty();
 460     }
 461 
 462     @Override @DefinedBy(Api.LANGUAGE_MODEL)
 463     public List<Attribute.TypeCompound> getAnnotationMirrors() {
 464         final TypeMetadata.Annotations metadata =
 465             (TypeMetadata.Annotations)getMetadataOfKind(Entry.Kind.ANNOTATIONS);
 466 
 467         return metadata == null ? List.nil() : metadata.getAnnotations();
 468     }
 469 
 470 
 471     @Override @DefinedBy(Api.LANGUAGE_MODEL)
 472     public <A extends Annotation> A getAnnotation(Class<A> annotationType) {
 473         return null;
 474     }
 475 
 476 
 477     @Override @DefinedBy(Api.LANGUAGE_MODEL)
 478     public <A extends Annotation> A[] getAnnotationsByType(Class<A> annotationType) {
 479         @SuppressWarnings("unchecked")
 480         A[] tmp = (A[]) java.lang.reflect.Array.newInstance(annotationType, 0);
 481         return tmp;
 482     }
 483 
 484     /** Return the base types of a list of types.
 485      */
 486     public static List<Type> baseTypes(List<Type> ts) {
 487         if (ts.nonEmpty()) {
 488             Type t = ts.head.baseType();
 489             List<Type> baseTypes = baseTypes(ts.tail);
 490             if (t != ts.head || baseTypes != ts.tail)
 491                 return baseTypes.prepend(t);
 492         }
 493         return ts;
 494     }
 495 
 496     protected void appendAnnotationsString(StringBuilder sb,
 497                                          boolean prefix) {
 498         if (isAnnotated()) {
 499             if (prefix) {
 500                 sb.append(" ");
 501             }
 502             sb.append(getAnnotationMirrors());
 503             sb.append(" ");
 504         }
 505     }
 506 
 507     protected void appendAnnotationsString(StringBuilder sb) {
 508         appendAnnotationsString(sb, false);
 509     }
 510 
 511     /** The Java source which this type represents.
 512      */
 513     @DefinedBy(Api.LANGUAGE_MODEL)
 514     public String toString() {
 515         StringBuilder sb = new StringBuilder();
 516         appendAnnotationsString(sb);
 517         if (tsym == null || tsym.name == null) {
 518             sb.append("<none>");
 519         } else {
 520             sb.append(tsym.name.toString());
 521         }
 522         if (moreInfo && hasTag(TYPEVAR)) {
 523             sb.append(hashCode());
 524         }
 525         return sb.toString();
 526     }
 527 
 528     /**
 529      * The Java source which this type list represents.  A List is
 530      * represented as a comma-separated listing of the elements in
 531      * that list.
 532      */
 533     public static String toString(List<Type> ts) {
 534         if (ts.isEmpty()) {
 535             return "";
 536         } else {
 537             StringBuilder buf = new StringBuilder();
 538             buf.append(ts.head.toString());
 539             for (List<Type> l = ts.tail; l.nonEmpty(); l = l.tail)
 540                 buf.append(",").append(l.head.toString());
 541             return buf.toString();
 542         }
 543     }
 544 
 545     /**
 546      * The constant value of this type, converted to String
 547      */
 548     public String stringValue() {
 549         Object cv = Assert.checkNonNull(constValue());
 550         return cv.toString();
 551     }
 552 
 553     /**
 554      * Override this method with care. For most Type instances this should behave as ==.
 555      */
 556     @Override @DefinedBy(Api.LANGUAGE_MODEL)
 557     public boolean equals(Object t) {
 558         return this == t;
 559     }
 560 
 561     public boolean equalsIgnoreMetadata(Type t) {
 562         return typeNoMetadata().equals(t.typeNoMetadata());
 563     }
 564 
 565     @Override @DefinedBy(Api.LANGUAGE_MODEL)
 566     public int hashCode() {
 567         return super.hashCode();
 568     }
 569 
 570     public String argtypes(boolean varargs) {
 571         List<Type> args = getParameterTypes();
 572         if (!varargs) return args.toString();
 573         StringBuilder buf = new StringBuilder();
 574         while (args.tail.nonEmpty()) {
 575             buf.append(args.head);
 576             args = args.tail;
 577             buf.append(',');
 578         }
 579         if (args.head.hasTag(ARRAY)) {
 580             buf.append(((ArrayType)args.head).elemtype);
 581             if (args.head.getAnnotationMirrors().nonEmpty()) {
 582                 buf.append(args.head.getAnnotationMirrors());
 583             }
 584             buf.append("...");
 585         } else {
 586             buf.append(args.head);
 587         }
 588         return buf.toString();
 589     }
 590 
 591     /** Access methods.
 592      */
 593     public List<Type>        getTypeArguments()  { return List.nil(); }
 594     public Type              getEnclosingType()  { return null; }
 595     public List<Type>        getParameterTypes() { return List.nil(); }
 596     public Type              getReturnType()     { return null; }
 597     public Type              getReceiverType()   { return null; }
 598     public List<Type>        getThrownTypes()    { return List.nil(); }
 599     public Type              getUpperBound()     { return null; }
 600     public Type              getLowerBound()     { return null; }
 601 
 602     /** Navigation methods, these will work for classes, type variables,
 603      *  foralls, but will return null for arrays and methods.
 604      */
 605 
 606    /** Return all parameters of this type and all its outer types in order
 607     *  outer (first) to inner (last).
 608     */
 609     public List<Type> allparams() { return List.nil(); }
 610 
 611     /** Does this type contain "error" elements?
 612      */
 613     public boolean isErroneous() {
 614         return false;
 615     }
 616 
 617     public static boolean isErroneous(List<Type> ts) {
 618         for (List<Type> l = ts; l.nonEmpty(); l = l.tail)
 619             if (l.head.isErroneous()) return true;
 620         return false;
 621     }
 622 
 623     /** Is this type parameterized?
 624      *  A class type is parameterized if it has some parameters.
 625      *  An array type is parameterized if its element type is parameterized.
 626      *  All other types are not parameterized.
 627      */
 628     public boolean isParameterized() {
 629         return false;
 630     }
 631 
 632     /** Is this type a raw type?
 633      *  A class type is a raw type if it misses some of its parameters.
 634      *  An array type is a raw type if its element type is raw.
 635      *  All other types are not raw.
 636      *  Type validation will ensure that the only raw types
 637      *  in a program are types that miss all their type variables.
 638      */
 639     public boolean isRaw() {
 640         return false;
 641     }
 642 
 643     /**
 644      * A compound type is a special class type whose supertypes are used to store a list
 645      * of component types. There are two kinds of compound types: (i) intersection types
 646      * {@see IntersectionClassType} and (ii) union types {@see UnionClassType}.
 647      */
 648     public boolean isCompound() {
 649         return false;
 650     }
 651 
 652     public boolean isIntersection() {
 653         return false;
 654     }
 655 
 656     public boolean isUnion() {
 657         return false;
 658     }
 659 
 660     public boolean isInterface() {
 661         return (tsym.flags() & INTERFACE) != 0;
 662     }
 663 
 664     public boolean isFinal() {
 665         return (tsym.flags() & FINAL) != 0;
 666     }
 667 
 668     /**
 669      * Does this type contain occurrences of type t?
 670      */
 671     public boolean contains(Type t) {
 672         return t.equalsIgnoreMetadata(this);
 673     }
 674 
 675     public static boolean contains(List<Type> ts, Type t) {
 676         for (List<Type> l = ts;
 677              l.tail != null /*inlined: l.nonEmpty()*/;
 678              l = l.tail)
 679             if (l.head.contains(t)) return true;
 680         return false;
 681     }
 682 
 683     /** Does this type contain an occurrence of some type in 'ts'?
 684      */
 685     public boolean containsAny(List<Type> ts) {
 686         for (Type t : ts)
 687             if (this.contains(t)) return true;
 688         return false;
 689     }
 690 
 691     public static boolean containsAny(List<Type> ts1, List<Type> ts2) {
 692         for (Type t : ts1)
 693             if (t.containsAny(ts2)) return true;
 694         return false;
 695     }
 696 
 697     public static List<Type> filter(List<Type> ts, Predicate<Type> tf) {
 698         ListBuffer<Type> buf = new ListBuffer<>();
 699         for (Type t : ts) {
 700             if (tf.test(t)) {
 701                 buf.append(t);
 702             }
 703         }
 704         return buf.toList();
 705     }
 706 
 707     public boolean isSuperBound() { return false; }
 708     public boolean isExtendsBound() { return false; }
 709     public boolean isUnbound() { return false; }
 710     public Type withTypeVar(Type t) { return this; }
 711 
 712     /** The underlying method type of this type.
 713      */
 714     public MethodType asMethodType() { throw new AssertionError(); }
 715 
 716     /** Complete loading all classes in this type.
 717      */
 718     public void complete() {}
 719 
 720     public TypeSymbol asElement() {
 721         return tsym;
 722     }
 723 
 724     @Override @DefinedBy(Api.LANGUAGE_MODEL)
 725     public TypeKind getKind() {
 726         return TypeKind.OTHER;
 727     }
 728 
 729     @Override @DefinedBy(Api.LANGUAGE_MODEL)
 730     public <R, P> R accept(TypeVisitor<R, P> v, P p) {
 731         throw new AssertionError();
 732     }
 733 
 734     public static class JCPrimitiveType extends Type
 735             implements javax.lang.model.type.PrimitiveType {
 736 
 737         TypeTag tag;
 738 
 739         public JCPrimitiveType(TypeTag tag, TypeSymbol tsym) {
 740             this(tag, tsym, TypeMetadata.EMPTY);
 741         }
 742 
 743         private JCPrimitiveType(TypeTag tag, TypeSymbol tsym, TypeMetadata metadata) {
 744             super(tsym, metadata);
 745             this.tag = tag;
 746             Assert.check(tag.isPrimitive);
 747         }
 748 
 749         @Override
 750         public JCPrimitiveType cloneWithMetadata(TypeMetadata md) {
 751             return new JCPrimitiveType(tag, tsym, md) {
 752                 @Override
 753                 public Type baseType() { return JCPrimitiveType.this.baseType(); }
 754             };
 755         }
 756 
 757         @Override
 758         public boolean isNumeric() {
 759             return tag != BOOLEAN;
 760         }
 761 
 762         @Override
 763         public boolean isIntegral() {
 764             switch (tag) {
 765                 case CHAR:
 766                 case BYTE:
 767                 case SHORT:
 768                 case INT:
 769                 case LONG:
 770                     return true;
 771                 default:
 772                     return false;
 773             }
 774         }
 775 
 776         @Override
 777         public boolean isPrimitive() {
 778             return true;
 779         }
 780 
 781         @Override
 782         public TypeTag getTag() {
 783             return tag;
 784         }
 785 
 786         @Override
 787         public boolean isPrimitiveOrVoid() {
 788             return true;
 789         }
 790 
 791         /** Define a constant type, of the same kind as this type
 792          *  and with given constant value
 793          */
 794         @Override
 795         public Type constType(Object constValue) {
 796             final Object value = constValue;
 797             return new JCPrimitiveType(tag, tsym, metadata) {
 798                     @Override
 799                     public Object constValue() {
 800                         return value;
 801                     }
 802                     @Override
 803                     public Type baseType() {
 804                         return tsym.type;
 805                     }
 806                 };
 807         }
 808 
 809         /**
 810          * The constant value of this type, converted to String
 811          */
 812         @Override
 813         public String stringValue() {
 814             Object cv = Assert.checkNonNull(constValue());
 815             if (tag == BOOLEAN) {
 816                 return ((Integer) cv).intValue() == 0 ? "false" : "true";
 817             }
 818             else if (tag == CHAR) {
 819                 return String.valueOf((char) ((Integer) cv).intValue());
 820             }
 821             else {
 822                 return cv.toString();
 823             }
 824         }
 825 
 826         /** Is this a constant type whose value is false?
 827          */
 828         @Override
 829         public boolean isFalse() {
 830             return
 831                 tag == BOOLEAN &&
 832                 constValue() != null &&
 833                 ((Integer)constValue()).intValue() == 0;
 834         }
 835 
 836         /** Is this a constant type whose value is true?
 837          */
 838         @Override
 839         public boolean isTrue() {
 840             return
 841                 tag == BOOLEAN &&
 842                 constValue() != null &&
 843                 ((Integer)constValue()).intValue() != 0;
 844         }
 845 
 846         @Override @DefinedBy(Api.LANGUAGE_MODEL)
 847         public <R, P> R accept(TypeVisitor<R, P> v, P p) {
 848             return v.visitPrimitive(this, p);
 849         }
 850 
 851         @Override @DefinedBy(Api.LANGUAGE_MODEL)
 852         public TypeKind getKind() {
 853             switch (tag) {
 854                 case BYTE:      return TypeKind.BYTE;
 855                 case CHAR:      return TypeKind.CHAR;
 856                 case SHORT:     return TypeKind.SHORT;
 857                 case INT:       return TypeKind.INT;
 858                 case LONG:      return TypeKind.LONG;
 859                 case FLOAT:     return TypeKind.FLOAT;
 860                 case DOUBLE:    return TypeKind.DOUBLE;
 861                 case BOOLEAN:   return TypeKind.BOOLEAN;
 862             }
 863             throw new AssertionError();
 864         }
 865 
 866     }
 867 
 868     public static class WildcardType extends Type
 869             implements javax.lang.model.type.WildcardType {
 870 
 871         public Type type;
 872         public BoundKind kind;
 873         public TypeVar bound;
 874 
 875         @Override
 876         public <R,S> R accept(Type.Visitor<R,S> v, S s) {
 877             return v.visitWildcardType(this, s);
 878         }
 879 
 880         public WildcardType(Type type, BoundKind kind, TypeSymbol tsym) {
 881             this(type, kind, tsym, null, TypeMetadata.EMPTY);
 882         }
 883 
 884         public WildcardType(Type type, BoundKind kind, TypeSymbol tsym,
 885                             TypeMetadata metadata) {
 886             this(type, kind, tsym, null, metadata);
 887         }
 888 
 889         public WildcardType(Type type, BoundKind kind, TypeSymbol tsym,
 890                             TypeVar bound) {
 891             this(type, kind, tsym, bound, TypeMetadata.EMPTY);
 892         }
 893 
 894         public WildcardType(Type type, BoundKind kind, TypeSymbol tsym,
 895                             TypeVar bound, TypeMetadata metadata) {
 896             super(tsym, metadata);
 897             this.type = Assert.checkNonNull(type);
 898             this.kind = kind;
 899             this.bound = bound;
 900         }
 901 
 902         @Override
 903         public WildcardType cloneWithMetadata(TypeMetadata md) {
 904             return new WildcardType(type, kind, tsym, bound, md) {
 905                 @Override
 906                 public Type baseType() { return WildcardType.this.baseType(); }
 907             };
 908         }
 909 
 910         @Override
 911         public TypeTag getTag() {
 912             return WILDCARD;
 913         }
 914 
 915         @Override
 916         public boolean contains(Type t) {
 917             return kind != UNBOUND && type.contains(t);
 918         }
 919 
 920         public boolean isSuperBound() {
 921             return kind == SUPER ||
 922                 kind == UNBOUND;
 923         }
 924         public boolean isExtendsBound() {
 925             return kind == EXTENDS ||
 926                 kind == UNBOUND;
 927         }
 928         public boolean isUnbound() {
 929             // is it `?` or `? extends Object`?
 930             return kind == UNBOUND ||
 931                     (kind == EXTENDS && type.tsym.flatName() == type.tsym.name.table.names.java_lang_Object);
 932         }
 933 
 934         @Override
 935         public boolean isReference() {
 936             return true;
 937         }
 938 
 939         @Override
 940         public boolean isNullOrReference() {
 941             return true;
 942         }
 943 
 944         @Override
 945         public Type withTypeVar(Type t) {
 946             //-System.err.println(this+".withTypeVar("+t+");");//DEBUG
 947             if (bound == t)
 948                 return this;
 949             bound = (TypeVar)t;
 950             return this;
 951         }
 952 
 953         boolean isPrintingBound = false;
 954         @DefinedBy(Api.LANGUAGE_MODEL)
 955         public String toString() {
 956             StringBuilder s = new StringBuilder();
 957             appendAnnotationsString(s);
 958             s.append(kind.toString());
 959             if (kind != UNBOUND)
 960                 s.append(type);
 961             if (moreInfo && bound != null && !isPrintingBound)
 962                 try {
 963                     isPrintingBound = true;
 964                     s.append("{:").append(bound.getUpperBound()).append(":}");
 965                 } finally {
 966                     isPrintingBound = false;
 967                 }
 968             return s.toString();
 969         }
 970 
 971         @DefinedBy(Api.LANGUAGE_MODEL)
 972         public Type getExtendsBound() {
 973             if (kind == EXTENDS)
 974                 return type;
 975             else
 976                 return null;
 977         }
 978 
 979         @DefinedBy(Api.LANGUAGE_MODEL)
 980         public Type getSuperBound() {
 981             if (kind == SUPER)
 982                 return type;
 983             else
 984                 return null;
 985         }
 986 
 987         @DefinedBy(Api.LANGUAGE_MODEL)
 988         public TypeKind getKind() {
 989             return TypeKind.WILDCARD;
 990         }
 991 
 992         @DefinedBy(Api.LANGUAGE_MODEL)
 993         public <R, P> R accept(TypeVisitor<R, P> v, P p) {
 994             return v.visitWildcard(this, p);
 995         }
 996     }
 997 
 998     public static class ConstantPoolQType implements PoolConstant {
 999 
1000         public final Type type;
1001         final Types types;
1002 
1003         public ConstantPoolQType(Type type, Types types) {
1004             this.type = type;
1005             this.types = types;
1006         }
1007 
1008         @Override
1009         public Object poolKey(Types types) {
1010             return this;
1011         }
1012 
1013         @Override
1014         public int poolTag() {
1015             return ClassFile.CONSTANT_Class;
1016         }
1017 
1018         public int hashCode() {
1019             return types.hashCode(type);
1020         }
1021 
1022         public boolean equals(Object obj) {
1023             return (obj instanceof ConstantPoolQType) &&
1024                     types.isSameType(type, ((ConstantPoolQType)obj).type);
1025         }
1026 
1027         public String toString() {
1028             return type.toString();
1029         }
1030     }
1031 
1032     public static class ClassType extends Type implements DeclaredType, LoadableConstant,
1033                                                           javax.lang.model.type.ErrorType {
1034 
1035         /**
1036          * The 'flavor' of a ClassType indicates its reference/primitive projectionness
1037          * viewed against the default nature of the associated class.
1038          */
1039         public enum Flavor {
1040 
1041             /**
1042              * Classic reference type. Also reference projection type of a reference-favoring aka
1043              * reference-default primitive class type
1044              */
1045             L_TypeOf_L,
1046 
1047             /**
1048              * Reference projection type of a primitive-favoring aka primitive-default
1049              * plain vanilla primitive class type,
1050              */
1051             L_TypeOf_Q,
1052 
1053             /**
1054              * Value projection type of a primitive-favoring aka primitive-default
1055              * plain vanilla primitive class type,
1056              */
1057             Q_TypeOf_Q,
1058 
1059             /**
1060              * Value projection type of a reference-favoring aka
1061              * reference-default primitive class type
1062              */
1063             Q_TypeOf_L,
1064 
1065             /**
1066              * Reference projection type of a class type of an as yet unknown default provenance, 'X' will be
1067              * discovered to be 'L' or 'Q' in "due course" and mutated suitably.
1068              */
1069             L_TypeOf_X,
1070 
1071             /**
1072              * Value projection type of a class type of an as yet unknown default provenance, 'X' will be
1073              * discovered to be 'L' or 'Q' in "due course" and mutated suitably.
1074              */
1075             Q_TypeOf_X,
1076 
1077             /**
1078              *  As yet unknown projection type of an as yet unknown default provenance class.
1079              */
1080             X_Typeof_X,
1081 
1082             /**
1083              *  An error type - we don't care to discriminate them any further.
1084              */
1085              E_Typeof_X;
1086 
1087             // We don't seem to need X_Typeof_L or X_Typeof_Q so far.
1088 
1089             // Transform a larval form into a more evolved form
1090             public Flavor metamorphose(boolean isPrimtiveClass) {
1091 
1092                 switch (this) {
1093 
1094                     case E_Typeof_X:  // stunted form
1095                     case L_TypeOf_L:
1096                     case L_TypeOf_Q:
1097                     case Q_TypeOf_L:
1098                     case Q_TypeOf_Q:
1099                             // These are fully evolved sealed forms or stunted - no futher transformation
1100                             return this;
1101                     case L_TypeOf_X:
1102                             return isPrimtiveClass ? L_TypeOf_Q : L_TypeOf_L;
1103                     case Q_TypeOf_X:
1104                             return isPrimtiveClass ? Q_TypeOf_Q : Q_TypeOf_L;
1105                     case X_Typeof_X:
1106                             return isPrimtiveClass ? Q_TypeOf_Q : L_TypeOf_L;
1107                     default:
1108                             throw new AssertionError("Unexpected class type flavor");
1109                 }
1110             }
1111         }
1112 
1113         /** The enclosing type of this type. If this is the type of an inner
1114          *  class, outer_field refers to the type of its enclosing
1115          *  instance class, in all other cases it refers to noType.
1116          */
1117         private Type outer_field;
1118 
1119         /** The type parameters of this type (to be set once class is loaded).
1120          */
1121         public List<Type> typarams_field;
1122 
1123         /** A cache variable for the type parameters of this type,
1124          *  appended to all parameters of its enclosing class.
1125          *  @see #allparams
1126          */
1127         public List<Type> allparams_field;
1128 
1129         /** The supertype of this class (to be set once class is loaded).
1130          */
1131         public Type supertype_field;
1132 
1133         /** The interfaces of this class (to be set once class is loaded).
1134          */
1135         public List<Type> interfaces_field;
1136 
1137         /** All the interfaces of this class, including missing ones.
1138          */
1139         public List<Type> all_interfaces_field;
1140 
1141         /** The 'other' projection: If 'this' is type of a primitive class, then 'projection' is the
1142          *  reference projection type and vice versa. Lazily initialized, not to be accessed directly.
1143         */
1144         public ClassType projection;
1145 
1146         /** Is this L of default {L, Q, X} or Q of default {L, Q, X} ?
1147          */
1148         public Flavor flavor;
1149 
1150         /*
1151          * Use of this constructor is kinda sorta deprecated, use the other constructor
1152          * that forces the call site to consider and include the class type flavor.
1153          */
1154         public ClassType(Type outer, List<Type> typarams, TypeSymbol tsym) {
1155             this(outer, typarams, tsym, TypeMetadata.EMPTY, Flavor.L_TypeOf_L);
1156         }
1157 
1158         public ClassType(Type outer, List<Type> typarams, TypeSymbol tsym,
1159                          TypeMetadata metadata, Flavor flavor) {
1160             super(tsym, metadata);
1161             this.outer_field = outer;
1162             this.typarams_field = typarams;
1163             this.allparams_field = null;
1164             this.supertype_field = null;
1165             this.interfaces_field = null;
1166             this.flavor = flavor;
1167         }
1168 
1169         public int poolTag() {
1170             return ClassFile.CONSTANT_Class;
1171         }
1172 
1173         @Override
1174         public ClassType cloneWithMetadata(TypeMetadata md) {
1175             return new ClassType(outer_field, typarams_field, tsym, md, flavor) {
1176                 @Override
1177                 public Type baseType() { return ClassType.this.baseType(); }
1178             };
1179         }
1180 
1181         @Override
1182         public TypeTag getTag() {
1183             return CLASS;
1184         }
1185 
1186         @Override
1187         public <R,S> R accept(Type.Visitor<R,S> v, S s) {
1188             return v.visitClassType(this, s);
1189         }
1190 
1191         public Type constType(Object constValue) {
1192             final Object value = constValue;
1193             return new ClassType(getEnclosingType(), typarams_field, tsym, metadata, flavor) {
1194                     @Override
1195                     public Object constValue() {
1196                         return value;
1197                     }
1198                     @Override
1199                     public Type baseType() {
1200                         return tsym.type;
1201                     }
1202                 };
1203         }
1204 
1205         /** The Java source which this type represents.
1206          */
1207         @DefinedBy(Api.LANGUAGE_MODEL)
1208         public String toString() {
1209             StringBuilder buf = new StringBuilder();
1210             if (getEnclosingType().hasTag(CLASS) && tsym.owner.kind == TYP) {
1211                 buf.append(getEnclosingType().toString());
1212                 buf.append(".");
1213                 appendAnnotationsString(buf);
1214                 buf.append(className(tsym, false));
1215             } else {
1216                 appendAnnotationsString(buf);
1217                 buf.append(className(tsym, true));
1218             }
1219 
1220             boolean isReferenceProjection;
1221             try {
1222                 isReferenceProjection = isReferenceProjection();
1223             } catch (CompletionFailure cf) {
1224                 isReferenceProjection = false; // handle missing types gracefully.
1225             }
1226             if (isReferenceProjection) {
1227                 buf.append('.');
1228                 buf.append(tsym.name.table.names.ref);
1229             }
1230 
1231             if (getTypeArguments().nonEmpty()) {
1232                 buf.append('<');
1233                 buf.append(getTypeArguments().toString());
1234                 buf.append(">");
1235             }
1236             return buf.toString();
1237         }
1238 //where
1239             private String className(Symbol sym, boolean longform) {
1240                 if (sym.name.isEmpty() && (sym.flags() & COMPOUND) != 0) {
1241                     StringBuilder s = new StringBuilder(supertype_field.toString());
1242                     for (List<Type> is=interfaces_field; is.nonEmpty(); is = is.tail) {
1243                         s.append("&");
1244                         s.append(is.head.toString());
1245                     }
1246                     return s.toString();
1247                 } else if (sym.name.isEmpty()) {
1248                     String s;
1249                     ClassType norm = (ClassType) tsym.type;
1250                     if (norm == null) {
1251                         s = Log.getLocalizedString("anonymous.class", (Object)null);
1252                     } else if (norm.interfaces_field != null && norm.interfaces_field.nonEmpty()) {
1253                         s = Log.getLocalizedString("anonymous.class",
1254                                                    norm.interfaces_field.head);
1255                     } else {
1256                         s = Log.getLocalizedString("anonymous.class",
1257                                                    norm.supertype_field);
1258                     }
1259                     if (moreInfo)
1260                         s += String.valueOf(sym.hashCode());
1261                     return s;
1262                 }
1263                 String s;
1264                 if (longform) {
1265                     s =  sym.getQualifiedName().toString();
1266                 } else {
1267                     s = sym.name.toString();
1268                 }
1269                 return s;
1270             }
1271 
1272         public Flavor getFlavor() {
1273             return flavor;
1274         }
1275 
1276         @DefinedBy(Api.LANGUAGE_MODEL)
1277         public List<Type> getTypeArguments() {
1278             if (typarams_field == null) {
1279                 complete();
1280                 if (typarams_field == null)
1281                     typarams_field = List.nil();
1282             }
1283             return typarams_field;
1284         }
1285 
1286         public boolean hasErasedSupertypes() {
1287             return isRaw();
1288         }
1289 
1290         @DefinedBy(Api.LANGUAGE_MODEL)
1291         public Type getEnclosingType() {
1292             if (outer_field != null && outer_field.isReferenceProjection()) {
1293                 outer_field = outer_field.valueProjection();
1294             }
1295             return outer_field;
1296         }
1297 
1298         public void setEnclosingType(Type outer) {
1299             outer_field = outer;
1300         }
1301 
1302         public List<Type> allparams() {
1303             if (allparams_field == null) {
1304                 allparams_field = getTypeArguments().prependList(getEnclosingType().allparams());
1305             }
1306             return allparams_field;
1307         }
1308 
1309         public boolean isErroneous() {
1310             return
1311                 getEnclosingType().isErroneous() ||
1312                 isErroneous(getTypeArguments()) ||
1313                 this != tsym.type && tsym.type.isErroneous();
1314         }
1315 
1316         public boolean isParameterized() {
1317             return allparams().tail != null;
1318             // optimization, was: allparams().nonEmpty();
1319         }
1320 
1321         @Override
1322         public boolean isReference() {
1323             return true;
1324         }
1325 
1326         @Override
1327         public boolean isPrimitiveClass() {
1328             return !isReferenceProjection() && tsym != null && tsym.isPrimitiveClass();
1329         }
1330 
1331         @Override
1332         public boolean isValueClass() {
1333             return !isReferenceProjection() && tsym != null && tsym.isValueClass();
1334         }
1335 
1336         @Override
1337         public boolean isReferenceProjection() {
1338             // gaurd against over-eager and/or inopportune completion
1339             if (tsym != null) {
1340                 if (flavor == Flavor.L_TypeOf_X || tsym.isCompleted()) {
1341                     flavor = flavor.metamorphose(tsym.isPrimitiveClass());
1342                 }
1343             }
1344             return flavor == Flavor.L_TypeOf_Q;
1345         }
1346 
1347         @Override
1348         public Type valueProjection() {
1349             if (!isReferenceProjection())
1350                 return null;
1351 
1352             if (projection !=  null)
1353                 return projection;
1354 
1355             projection = new ClassType(outer_field, typarams_field, tsym, getMetadata(), Flavor.Q_TypeOf_Q);
1356             projection.allparams_field = allparams_field;
1357             projection.supertype_field = supertype_field;
1358 
1359             projection.interfaces_field = interfaces_field;
1360             projection.all_interfaces_field = all_interfaces_field;
1361             projection.projection = this;
1362             return projection;
1363         }
1364 
1365         // return the reference projection type preserving parameterizations
1366         @Override
1367         public ClassType referenceProjection() {
1368 
1369             if (!isPrimitiveClass())
1370                 return null;
1371 
1372             if (projection != null)
1373                 return projection;
1374 
1375             projection = new ClassType(outer_field, typarams_field, tsym, getMetadata(), Flavor.L_TypeOf_Q);
1376             projection.allparams_field = allparams_field;
1377             projection.supertype_field = supertype_field;
1378 
1379             projection.interfaces_field = interfaces_field;
1380             projection.all_interfaces_field = all_interfaces_field;
1381             projection.projection = this;
1382             return projection;
1383         }
1384 
1385         @Override
1386         public boolean isNullOrReference() {
1387             return true;
1388         }
1389 
1390         /** A cache for the rank. */
1391         int rank_field = -1;
1392 
1393         /** A class type is raw if it misses some
1394          *  of its type parameter sections.
1395          *  After validation, this is equivalent to:
1396          *  {@code allparams.isEmpty() && tsym.type.allparams.nonEmpty(); }
1397          */
1398         public boolean isRaw() {
1399             return
1400                 this != tsym.type && // necessary, but not sufficient condition
1401                 tsym.type.allparams().nonEmpty() &&
1402                 allparams().isEmpty();
1403         }
1404 
1405         public boolean contains(Type elem) {
1406             return
1407                 elem.equalsIgnoreMetadata(this)
1408                 || (isParameterized()
1409                     && (getEnclosingType().contains(elem) || contains(getTypeArguments(), elem)))
1410                 || (isCompound()
1411                     && (supertype_field.contains(elem) || contains(interfaces_field, elem)));
1412         }
1413 
1414         public void complete() {
1415             tsym.complete();
1416         }
1417 
1418         @DefinedBy(Api.LANGUAGE_MODEL)
1419         public TypeKind getKind() {
1420             tsym.apiComplete();
1421             return tsym.kind == TYP ? TypeKind.DECLARED : TypeKind.ERROR;
1422         }
1423 
1424         @DefinedBy(Api.LANGUAGE_MODEL)
1425         public <R, P> R accept(TypeVisitor<R, P> v, P p) {
1426             return v.visitDeclared(this, p);
1427         }
1428     }
1429 
1430     public static class ErasedClassType extends ClassType {
1431         public ErasedClassType(Type outer, TypeSymbol tsym,
1432                                TypeMetadata metadata) {
1433             super(outer, List.nil(), tsym, metadata, tsym.type.getFlavor());
1434         }
1435 
1436         @Override
1437         public boolean hasErasedSupertypes() {
1438             return true;
1439         }
1440     }
1441 
1442     // a clone of a ClassType that knows about the alternatives of a union type.
1443     public static class UnionClassType extends ClassType implements UnionType {
1444         final List<? extends Type> alternatives_field;
1445 
1446         public UnionClassType(ClassType ct, List<? extends Type> alternatives) {
1447             // Presently no way to refer to this type directly, so we
1448             // cannot put annotations directly on it.
1449             super(ct.outer_field, ct.typarams_field, ct.tsym);
1450             allparams_field = ct.allparams_field;
1451             supertype_field = ct.supertype_field;
1452             interfaces_field = ct.interfaces_field;
1453             all_interfaces_field = ct.interfaces_field;
1454             alternatives_field = alternatives;
1455         }
1456 
1457         @Override
1458         public UnionClassType cloneWithMetadata(TypeMetadata md) {
1459             throw new AssertionError("Cannot add metadata to a union type");
1460         }
1461 
1462         public Type getLub() {
1463             return tsym.type;
1464         }
1465 
1466         @DefinedBy(Api.LANGUAGE_MODEL)
1467         public java.util.List<? extends TypeMirror> getAlternatives() {
1468             return Collections.unmodifiableList(alternatives_field);
1469         }
1470 
1471         @Override
1472         public boolean isUnion() {
1473             return true;
1474         }
1475 
1476         @Override
1477         public boolean isCompound() {
1478             return getLub().isCompound();
1479         }
1480 
1481         @Override @DefinedBy(Api.LANGUAGE_MODEL)
1482         public TypeKind getKind() {
1483             return TypeKind.UNION;
1484         }
1485 
1486         @Override @DefinedBy(Api.LANGUAGE_MODEL)
1487         public <R, P> R accept(TypeVisitor<R, P> v, P p) {
1488             return v.visitUnion(this, p);
1489         }
1490 
1491         public Iterable<? extends Type> getAlternativeTypes() {
1492             return alternatives_field;
1493         }
1494     }
1495 
1496     // a clone of a ClassType that knows about the bounds of an intersection type.
1497     public static class IntersectionClassType extends ClassType implements IntersectionType {
1498 
1499         public boolean allInterfaces;
1500 
1501         public IntersectionClassType(List<Type> bounds, ClassSymbol csym, boolean allInterfaces) {
1502             // Presently no way to refer to this type directly, so we
1503             // cannot put annotations directly on it.
1504             super(Type.noType, List.nil(), csym);
1505             this.allInterfaces = allInterfaces;
1506             Assert.check((csym.flags() & COMPOUND) != 0);
1507             supertype_field = bounds.head;
1508             interfaces_field = bounds.tail;
1509             Assert.check(!supertype_field.tsym.isCompleted() ||
1510                     !supertype_field.isInterface(), supertype_field);
1511         }
1512 
1513         @Override
1514         public IntersectionClassType cloneWithMetadata(TypeMetadata md) {
1515             throw new AssertionError("Cannot add metadata to an intersection type");
1516         }
1517 
1518         @DefinedBy(Api.LANGUAGE_MODEL)
1519         public java.util.List<? extends TypeMirror> getBounds() {
1520             return Collections.unmodifiableList(getExplicitComponents());
1521         }
1522 
1523         @Override
1524         public boolean isCompound() {
1525             return true;
1526         }
1527 
1528         public List<Type> getComponents() {
1529             return interfaces_field.prepend(supertype_field);
1530         }
1531 
1532         @Override
1533         public boolean isIntersection() {
1534             return true;
1535         }
1536 
1537         public List<Type> getExplicitComponents() {
1538             return allInterfaces ?
1539                     interfaces_field :
1540                     getComponents();
1541         }
1542 
1543         @Override @DefinedBy(Api.LANGUAGE_MODEL)
1544         public TypeKind getKind() {
1545             return TypeKind.INTERSECTION;
1546         }
1547 
1548         @Override @DefinedBy(Api.LANGUAGE_MODEL)
1549         public <R, P> R accept(TypeVisitor<R, P> v, P p) {
1550             return v.visitIntersection(this, p);
1551         }
1552     }
1553 
1554     public static class ArrayType extends Type
1555             implements LoadableConstant, javax.lang.model.type.ArrayType {
1556 
1557         public Type elemtype;
1558 
1559         public ArrayType(Type elemtype, TypeSymbol arrayClass) {
1560             this(elemtype, arrayClass, TypeMetadata.EMPTY);
1561         }
1562 
1563         public ArrayType(Type elemtype, TypeSymbol arrayClass,
1564                          TypeMetadata metadata) {
1565             super(arrayClass, metadata);
1566             this.elemtype = elemtype;
1567         }
1568 
1569         public ArrayType(ArrayType that) {
1570             //note: type metadata is deliberately shared here, as we want side-effects from annotation
1571             //processing to flow from original array to the cloned array.
1572             this(that.elemtype, that.tsym, that.getMetadata());
1573         }
1574 
1575         public int poolTag() {
1576             return ClassFile.CONSTANT_Class;
1577         }
1578 
1579         @Override
1580         public ArrayType cloneWithMetadata(TypeMetadata md) {
1581             return new ArrayType(elemtype, tsym, md) {
1582                 @Override
1583                 public Type baseType() { return ArrayType.this.baseType(); }
1584             };
1585         }
1586 
1587         @Override
1588         public TypeTag getTag() {
1589             return ARRAY;
1590         }
1591 
1592         public <R,S> R accept(Type.Visitor<R,S> v, S s) {
1593             return v.visitArrayType(this, s);
1594         }
1595 
1596         @DefinedBy(Api.LANGUAGE_MODEL)
1597         public String toString() {
1598             StringBuilder sb = new StringBuilder();
1599 
1600             // First append root component type
1601             Type t = elemtype;
1602             while (t.getKind() == TypeKind.ARRAY)
1603                 t = ((ArrayType) t).getComponentType();
1604             sb.append(t);
1605 
1606             // then append @Anno[] @Anno[] ... @Anno[]
1607             t = this;
1608             do {
1609                 t.appendAnnotationsString(sb, true);
1610                 sb.append("[]");
1611                 t = ((ArrayType) t).getComponentType();
1612             } while (t.getKind() == TypeKind.ARRAY);
1613 
1614             return sb.toString();
1615         }
1616 
1617         @Override @DefinedBy(Api.LANGUAGE_MODEL)
1618         public boolean equals(Object obj) {
1619             return (obj instanceof ArrayType arrayType)
1620                     && (this == arrayType || elemtype.equals(arrayType.elemtype));
1621         }
1622 
1623         @DefinedBy(Api.LANGUAGE_MODEL)
1624         public int hashCode() {
1625             return (ARRAY.ordinal() << 5) + elemtype.hashCode();
1626         }
1627 
1628         public boolean isVarargs() {
1629             return false;
1630         }
1631 
1632         public List<Type> allparams() { return elemtype.allparams(); }
1633 
1634         public boolean isErroneous() {
1635             return elemtype.isErroneous();
1636         }
1637 
1638         public boolean isParameterized() {
1639             return elemtype.isParameterized();
1640         }
1641 
1642         @Override
1643         public boolean isReference() {
1644             return true;
1645         }
1646 
1647         @Override
1648         public boolean isNullOrReference() {
1649             return true;
1650         }
1651 
1652         public boolean isRaw() {
1653             return elemtype.isRaw();
1654         }
1655 
1656         public ArrayType makeVarargs() {
1657             return new ArrayType(elemtype, tsym, metadata) {
1658                 @Override
1659                 public boolean isVarargs() {
1660                     return true;
1661                 }
1662             };
1663         }
1664 
1665         public boolean contains(Type elem) {
1666             return elem.equalsIgnoreMetadata(this) || elemtype.contains(elem);
1667         }
1668 
1669         public void complete() {
1670             elemtype.complete();
1671         }
1672 
1673         @DefinedBy(Api.LANGUAGE_MODEL)
1674         public Type getComponentType() {
1675             return elemtype;
1676         }
1677 
1678         @DefinedBy(Api.LANGUAGE_MODEL)
1679         public TypeKind getKind() {
1680             return TypeKind.ARRAY;
1681         }
1682 
1683         @DefinedBy(Api.LANGUAGE_MODEL)
1684         public <R, P> R accept(TypeVisitor<R, P> v, P p) {
1685             return v.visitArray(this, p);
1686         }
1687     }
1688 
1689     public static class MethodType extends Type implements ExecutableType, LoadableConstant {
1690 
1691         public List<Type> argtypes;
1692         public Type restype;
1693         public List<Type> thrown;
1694 
1695         /** The type annotations on the method receiver.
1696          */
1697         public Type recvtype;
1698 
1699         public MethodType(List<Type> argtypes,
1700                           Type restype,
1701                           List<Type> thrown,
1702                           TypeSymbol methodClass) {
1703             // Presently no way to refer to a method type directly, so
1704             // we cannot put type annotations on it.
1705             super(methodClass, TypeMetadata.EMPTY);
1706             this.argtypes = argtypes;
1707             this.restype = restype;
1708             this.thrown = thrown;
1709         }
1710 
1711         @Override
1712         public MethodType cloneWithMetadata(TypeMetadata md) {
1713             throw new AssertionError("Cannot add metadata to a method type");
1714         }
1715 
1716         @Override
1717         public TypeTag getTag() {
1718             return METHOD;
1719         }
1720 
1721         public <R,S> R accept(Type.Visitor<R,S> v, S s) {
1722             return v.visitMethodType(this, s);
1723         }
1724 
1725         /** The Java source which this type represents.
1726          *
1727          *  XXX 06/09/99 iris This isn't correct Java syntax, but it probably
1728          *  should be.
1729          */
1730         @DefinedBy(Api.LANGUAGE_MODEL)
1731         public String toString() {
1732             StringBuilder sb = new StringBuilder();
1733             appendAnnotationsString(sb);
1734             sb.append('(');
1735             sb.append(argtypes);
1736             sb.append(')');
1737             sb.append(restype);
1738             return sb.toString();
1739         }
1740 
1741         @DefinedBy(Api.LANGUAGE_MODEL)
1742         public List<Type>        getParameterTypes() { return argtypes; }
1743         @DefinedBy(Api.LANGUAGE_MODEL)
1744         public Type              getReturnType()     { return restype; }
1745         @DefinedBy(Api.LANGUAGE_MODEL)
1746         public Type              getReceiverType()   {
1747             return (recvtype == null) ? Type.noType : recvtype;
1748         }
1749         @DefinedBy(Api.LANGUAGE_MODEL)
1750         public List<Type>        getThrownTypes()    { return thrown; }
1751 
1752         public boolean isErroneous() {
1753             return
1754                 isErroneous(argtypes) ||
1755                 restype != null && restype.isErroneous();
1756         }
1757 
1758         @Override
1759         public int poolTag() {
1760             return ClassFile.CONSTANT_MethodType;
1761         }
1762 
1763         public boolean contains(Type elem) {
1764             return elem.equalsIgnoreMetadata(this) || contains(argtypes, elem) || restype.contains(elem) || contains(thrown, elem);
1765         }
1766 
1767         public MethodType asMethodType() { return this; }
1768 
1769         public void complete() {
1770             for (List<Type> l = argtypes; l.nonEmpty(); l = l.tail)
1771                 l.head.complete();
1772             restype.complete();
1773             recvtype.complete();
1774             for (List<Type> l = thrown; l.nonEmpty(); l = l.tail)
1775                 l.head.complete();
1776         }
1777 
1778         @DefinedBy(Api.LANGUAGE_MODEL)
1779         public List<TypeVar> getTypeVariables() {
1780             return List.nil();
1781         }
1782 
1783         public TypeSymbol asElement() {
1784             return null;
1785         }
1786 
1787         @DefinedBy(Api.LANGUAGE_MODEL)
1788         public TypeKind getKind() {
1789             return TypeKind.EXECUTABLE;
1790         }
1791 
1792         @DefinedBy(Api.LANGUAGE_MODEL)
1793         public <R, P> R accept(TypeVisitor<R, P> v, P p) {
1794             return v.visitExecutable(this, p);
1795         }
1796     }
1797 
1798     public static class PackageType extends Type implements NoType {
1799 
1800         PackageType(PackageSymbol tsym) {
1801             // Package types cannot be annotated
1802             super(tsym, TypeMetadata.EMPTY);
1803         }
1804 
1805         @Override
1806         public PackageType cloneWithMetadata(TypeMetadata md) {
1807             throw new AssertionError("Cannot add metadata to a package type");
1808         }
1809 
1810         @Override
1811         public TypeTag getTag() {
1812             return PACKAGE;
1813         }
1814 
1815         @Override
1816         public <R,S> R accept(Type.Visitor<R,S> v, S s) {
1817             return v.visitPackageType(this, s);
1818         }
1819 
1820         @DefinedBy(Api.LANGUAGE_MODEL)
1821         public String toString() {
1822             return tsym.getQualifiedName().toString();
1823         }
1824 
1825         @DefinedBy(Api.LANGUAGE_MODEL)
1826         public TypeKind getKind() {
1827             return TypeKind.PACKAGE;
1828         }
1829 
1830         @DefinedBy(Api.LANGUAGE_MODEL)
1831         public <R, P> R accept(TypeVisitor<R, P> v, P p) {
1832             return v.visitNoType(this, p);
1833         }
1834     }
1835 
1836     public static class ModuleType extends Type implements NoType {
1837 
1838         ModuleType(ModuleSymbol tsym) {
1839             // Module types cannot be annotated
1840             super(tsym, TypeMetadata.EMPTY);
1841         }
1842 
1843         @Override
1844         public ModuleType cloneWithMetadata(TypeMetadata md) {
1845             throw new AssertionError("Cannot add metadata to a module type");
1846         }
1847 
1848         @Override
1849         public ModuleType annotatedType(List<Attribute.TypeCompound> annos) {
1850             throw new AssertionError("Cannot annotate a module type");
1851         }
1852 
1853         @Override
1854         public TypeTag getTag() {
1855             return TypeTag.MODULE;
1856         }
1857 
1858         @Override
1859         public <R,S> R accept(Type.Visitor<R,S> v, S s) {
1860             return v.visitModuleType(this, s);
1861         }
1862 
1863         @Override @DefinedBy(Api.LANGUAGE_MODEL)
1864         public String toString() {
1865             return tsym.getQualifiedName().toString();
1866         }
1867 
1868         @Override @DefinedBy(Api.LANGUAGE_MODEL)
1869         public TypeKind getKind() {
1870             return TypeKind.MODULE;
1871         }
1872 
1873         @Override @DefinedBy(Api.LANGUAGE_MODEL)
1874         public <R, P> R accept(TypeVisitor<R, P> v, P p) {
1875             return v.visitNoType(this, p);
1876         }
1877     }
1878 
1879     public static class TypeVar extends Type implements TypeVariable {
1880 
1881         /** The upper bound of this type variable; set from outside.
1882          *  Must be nonempty once it is set.
1883          *  For a bound, `bound' is the bound type itself.
1884          *  Multiple bounds are expressed as a single class type which has the
1885          *  individual bounds as superclass, respectively interfaces.
1886          *  The class type then has as `tsym' a compiler generated class `c',
1887          *  which has a flag COMPOUND and whose owner is the type variable
1888          *  itself. Furthermore, the erasure_field of the class
1889          *  points to the first class or interface bound.
1890          */
1891         private Type _bound = null;
1892 
1893         /** The lower bound of this type variable.
1894          *  TypeVars don't normally have a lower bound, so it is normally set
1895          *  to syms.botType.
1896          *  Subtypes, such as CapturedType, may provide a different value.
1897          */
1898         public Type lower;
1899 
1900         public TypeVar(Name name, Symbol owner, Type lower) {
1901             super(null, TypeMetadata.EMPTY);
1902             Assert.checkNonNull(lower);
1903             tsym = new TypeVariableSymbol(0, name, this, owner);
1904             this.setUpperBound(null);
1905             this.lower = lower;
1906         }
1907 
1908         public TypeVar(TypeSymbol tsym, Type bound, Type lower) {
1909             this(tsym, bound, lower, TypeMetadata.EMPTY);
1910         }
1911 
1912         public TypeVar(TypeSymbol tsym, Type bound, Type lower,
1913                        TypeMetadata metadata) {
1914             super(tsym, metadata);
1915             Assert.checkNonNull(lower);
1916             this.setUpperBound(bound);
1917             this.lower = lower;
1918         }
1919 
1920         @Override
1921         public TypeVar cloneWithMetadata(TypeMetadata md) {
1922             return new TypeVar(tsym, getUpperBound(), lower, md) {
1923                 @Override
1924                 public Type baseType() { return TypeVar.this.baseType(); }
1925 
1926                 @Override @DefinedBy(Api.LANGUAGE_MODEL)
1927                 public Type getUpperBound() { return TypeVar.this.getUpperBound(); }
1928 
1929                 public void setUpperBound(Type bound) { TypeVar.this.setUpperBound(bound); }
1930             };
1931         }
1932 
1933         @Override
1934         public TypeTag getTag() {
1935             return TYPEVAR;
1936         }
1937 
1938         @Override
1939         public <R,S> R accept(Type.Visitor<R,S> v, S s) {
1940             return v.visitTypeVar(this, s);
1941         }
1942 
1943         @Override @DefinedBy(Api.LANGUAGE_MODEL)
1944         public Type getUpperBound() { return _bound; }
1945 
1946         public void setUpperBound(Type bound) { this._bound = bound; }
1947 
1948         int rank_field = -1;
1949 
1950         @Override @DefinedBy(Api.LANGUAGE_MODEL)
1951         public Type getLowerBound() {
1952             return lower;
1953         }
1954 
1955         @DefinedBy(Api.LANGUAGE_MODEL)
1956         public TypeKind getKind() {
1957             return TypeKind.TYPEVAR;
1958         }
1959 
1960         public boolean isCaptured() {
1961             return false;
1962         }
1963 
1964         @Override
1965         public boolean isReference() {
1966             return true;
1967         }
1968 
1969         @Override
1970         public boolean isNullOrReference() {
1971             return true;
1972         }
1973 
1974         @Override @DefinedBy(Api.LANGUAGE_MODEL)
1975         public <R, P> R accept(TypeVisitor<R, P> v, P p) {
1976             return v.visitTypeVariable(this, p);
1977         }
1978     }
1979 
1980     /** A captured type variable comes from wildcards which can have
1981      *  both upper and lower bound.  CapturedType extends TypeVar with
1982      *  a lower bound.
1983      */
1984     public static class CapturedType extends TypeVar {
1985 
1986         public WildcardType wildcard;
1987 
1988         public CapturedType(Name name,
1989                             Symbol owner,
1990                             Type upper,
1991                             Type lower,
1992                             WildcardType wildcard) {
1993             super(name, owner, lower);
1994             this.lower = Assert.checkNonNull(lower);
1995             this.setUpperBound(upper);
1996             this.wildcard = wildcard;
1997         }
1998 
1999         public CapturedType(TypeSymbol tsym,
2000                             Type bound,
2001                             Type upper,
2002                             Type lower,
2003                             WildcardType wildcard,
2004                             TypeMetadata metadata) {
2005             super(tsym, bound, lower, metadata);
2006             this.wildcard = wildcard;
2007         }
2008 
2009         @Override
2010         public CapturedType cloneWithMetadata(TypeMetadata md) {
2011             return new CapturedType(tsym, getUpperBound(), getUpperBound(), lower, wildcard, md) {
2012                 @Override
2013                 public Type baseType() { return CapturedType.this.baseType(); }
2014 
2015                 @Override @DefinedBy(Api.LANGUAGE_MODEL)
2016                 public Type getUpperBound() { return CapturedType.this.getUpperBound(); }
2017 
2018                 public void setUpperBound(Type bound) { CapturedType.this.setUpperBound(bound); }
2019             };
2020         }
2021 
2022         @Override
2023         public <R,S> R accept(Type.Visitor<R,S> v, S s) {
2024             return v.visitCapturedType(this, s);
2025         }
2026 
2027         @Override
2028         public boolean isCaptured() {
2029             return true;
2030         }
2031 
2032         @Override @DefinedBy(Api.LANGUAGE_MODEL)
2033         public String toString() {
2034             StringBuilder sb = new StringBuilder();
2035             appendAnnotationsString(sb);
2036             sb.append("capture#");
2037             sb.append((hashCode() & 0xFFFFFFFFL) % Printer.PRIME);
2038             sb.append(" of ");
2039             sb.append(wildcard);
2040             return sb.toString();
2041         }
2042     }
2043 
2044     public abstract static class DelegatedType extends Type {
2045         public Type qtype;
2046         public TypeTag tag;
2047 
2048         public DelegatedType(TypeTag tag, Type qtype) {
2049             this(tag, qtype, TypeMetadata.EMPTY);
2050         }
2051 
2052         public DelegatedType(TypeTag tag, Type qtype,
2053                              TypeMetadata metadata) {
2054             super(qtype.tsym, metadata);
2055             this.tag = tag;
2056             this.qtype = qtype;
2057         }
2058 
2059         public TypeTag getTag() { return tag; }
2060         @DefinedBy(Api.LANGUAGE_MODEL)
2061         public String toString() { return qtype.toString(); }
2062         public List<Type> getTypeArguments() { return qtype.getTypeArguments(); }
2063         public Type getEnclosingType() { return qtype.getEnclosingType(); }
2064         public List<Type> getParameterTypes() { return qtype.getParameterTypes(); }
2065         public Type getReturnType() { return qtype.getReturnType(); }
2066         public Type getReceiverType() { return qtype.getReceiverType(); }
2067         public List<Type> getThrownTypes() { return qtype.getThrownTypes(); }
2068         public List<Type> allparams() { return qtype.allparams(); }
2069         public Type getUpperBound() { return qtype.getUpperBound(); }
2070         public boolean isErroneous() { return qtype.isErroneous(); }
2071     }
2072 
2073     /**
2074      * The type of a generic method type. It consists of a method type and
2075      * a list of method type-parameters that are used within the method
2076      * type.
2077      */
2078     public static class ForAll extends DelegatedType implements ExecutableType {
2079         public List<Type> tvars;
2080 
2081         public ForAll(List<Type> tvars, Type qtype) {
2082             super(FORALL, (MethodType)qtype);
2083             this.tvars = tvars;
2084         }
2085 
2086         @Override
2087         public ForAll cloneWithMetadata(TypeMetadata md) {
2088             throw new AssertionError("Cannot add metadata to a forall type");
2089         }
2090 
2091         @Override
2092         public <R,S> R accept(Type.Visitor<R,S> v, S s) {
2093             return v.visitForAll(this, s);
2094         }
2095 
2096         @DefinedBy(Api.LANGUAGE_MODEL)
2097         public String toString() {
2098             StringBuilder sb = new StringBuilder();
2099             appendAnnotationsString(sb);
2100             sb.append('<');
2101             sb.append(tvars);
2102             sb.append('>');
2103             sb.append(qtype);
2104             return sb.toString();
2105         }
2106 
2107         public List<Type> getTypeArguments()   { return tvars; }
2108 
2109         public boolean isErroneous()  {
2110             return qtype.isErroneous();
2111         }
2112 
2113         public boolean contains(Type elem) {
2114             return qtype.contains(elem);
2115         }
2116 
2117         public MethodType asMethodType() {
2118             return (MethodType)qtype;
2119         }
2120 
2121         public void complete() {
2122             for (List<Type> l = tvars; l.nonEmpty(); l = l.tail) {
2123                 ((TypeVar)l.head).getUpperBound().complete();
2124             }
2125             qtype.complete();
2126         }
2127 
2128         @DefinedBy(Api.LANGUAGE_MODEL)
2129         public List<TypeVar> getTypeVariables() {
2130             return List.convert(TypeVar.class, getTypeArguments());
2131         }
2132 
2133         @DefinedBy(Api.LANGUAGE_MODEL)
2134         public TypeKind getKind() {
2135             return TypeKind.EXECUTABLE;
2136         }
2137 
2138         @DefinedBy(Api.LANGUAGE_MODEL)
2139         public <R, P> R accept(TypeVisitor<R, P> v, P p) {
2140             return v.visitExecutable(this, p);
2141         }
2142     }
2143 
2144     /** A class for inference variables, for use during method/diamond type
2145      *  inference. An inference variable has upper/lower bounds and a set
2146      *  of equality constraints. Such bounds are set during subtyping, type-containment,
2147      *  type-equality checks, when the types being tested contain inference variables.
2148      *  A change listener can be attached to an inference variable, to receive notifications
2149      *  whenever the bounds of an inference variable change.
2150      */
2151     public static class UndetVar extends DelegatedType {
2152 
2153         enum Kind {
2154             NORMAL,
2155             CAPTURED,
2156             THROWS;
2157         }
2158 
2159         /** Inference variable change listener. The listener method is called
2160          *  whenever a change to the inference variable's bounds occurs
2161          */
2162         public interface UndetVarListener {
2163             /** called when some inference variable bounds (of given kinds ibs) change */
2164             void varBoundChanged(UndetVar uv, InferenceBound ib, Type bound, boolean update);
2165             /** called when the inferred type is set on some inference variable */
2166             default void varInstantiated(UndetVar uv) { Assert.error(); }
2167         }
2168 
2169         /**
2170          * Inference variable bound kinds
2171          */
2172         public enum InferenceBound {
2173             /** lower bounds */
2174             LOWER {
2175                 public InferenceBound complement() { return UPPER; }
2176             },
2177             /** equality constraints */
2178             EQ {
2179                 public InferenceBound complement() { return EQ; }
2180             },
2181             /** upper bounds */
2182             UPPER {
2183                 public InferenceBound complement() { return LOWER; }
2184             };
2185 
2186             public abstract InferenceBound complement();
2187 
2188             public boolean lessThan(InferenceBound that) {
2189                 if (that == this) {
2190                     return false;
2191                 } else {
2192                     switch (that) {
2193                         case UPPER: return true;
2194                         case LOWER: return false;
2195                         case EQ: return (this != UPPER);
2196                         default:
2197                             Assert.error("Cannot get here!");
2198                             return false;
2199                     }
2200                 }
2201             }
2202         }
2203 
2204         /** list of incorporation actions (used by the incorporation engine). */
2205         public ArrayDeque<IncorporationAction> incorporationActions = new ArrayDeque<>();
2206 
2207         /** inference variable bounds */
2208         protected Map<InferenceBound, List<Type>> bounds;
2209 
2210         /** inference variable's inferred type (set from Infer.java) */
2211         private Type inst = null;
2212 
2213         /** number of declared (upper) bounds */
2214         public int declaredCount;
2215 
2216         /** inference variable's change listener */
2217         public UndetVarListener listener = null;
2218 
2219         Kind kind;
2220 
2221         @Override
2222         public <R,S> R accept(Type.Visitor<R,S> v, S s) {
2223             return v.visitUndetVar(this, s);
2224         }
2225 
2226         public UndetVar(TypeVar origin, UndetVarListener listener, Types types) {
2227             // This is a synthesized internal type, so we cannot annotate it.
2228             super(UNDETVAR, origin);
2229             this.kind = origin.isCaptured() ?
2230                     Kind.CAPTURED :
2231                     Kind.NORMAL;
2232             this.listener = listener;
2233             bounds = new EnumMap<>(InferenceBound.class);
2234             List<Type> declaredBounds = types.getBounds(origin);
2235             declaredCount = declaredBounds.length();
2236             bounds.put(InferenceBound.UPPER, List.nil());
2237             bounds.put(InferenceBound.LOWER, List.nil());
2238             bounds.put(InferenceBound.EQ, List.nil());
2239             for (Type t : declaredBounds.reverse()) {
2240                 //add bound works in reverse order
2241                 addBound(InferenceBound.UPPER, t, types, true);
2242             }
2243             if (origin.isCaptured() && !origin.lower.hasTag(BOT)) {
2244                 //add lower bound if needed
2245                 addBound(InferenceBound.LOWER, origin.lower, types, true);
2246             }
2247         }
2248 
2249         @DefinedBy(Api.LANGUAGE_MODEL)
2250         public String toString() {
2251             StringBuilder sb = new StringBuilder();
2252             appendAnnotationsString(sb);
2253             if (inst == null) {
2254                 sb.append(qtype);
2255                 sb.append('?');
2256             } else {
2257                 sb.append(inst);
2258             }
2259             return sb.toString();
2260         }
2261 
2262         public String debugString() {
2263             String result = "inference var = " + qtype + "\n";
2264             if (inst != null) {
2265                 result += "inst = " + inst + '\n';
2266             }
2267             for (InferenceBound bound: InferenceBound.values()) {
2268                 List<Type> aboundList = bounds.get(bound);
2269                 if (aboundList != null && aboundList.size() > 0) {
2270                     result += bound + " = " + aboundList + '\n';
2271                 }
2272             }
2273             return result;
2274         }
2275 
2276         public void setThrow() {
2277             if (this.kind == Kind.CAPTURED) {
2278                 //invalid state transition
2279                 throw new IllegalStateException();
2280             }
2281             this.kind = Kind.THROWS;
2282         }
2283 
2284         /**
2285          * Returns a new copy of this undet var.
2286          */
2287         public UndetVar dup(Types types) {
2288             UndetVar uv2 = new UndetVar((TypeVar)qtype, listener, types);
2289             dupTo(uv2, types);
2290             return uv2;
2291         }
2292 
2293         /**
2294          * Dumps the contents of this undet var on another undet var.
2295          */
2296         public void dupTo(UndetVar uv2, Types types) {
2297             uv2.listener = null;
2298             uv2.bounds.clear();
2299             for (InferenceBound ib : InferenceBound.values()) {
2300                 uv2.bounds.put(ib, List.nil());
2301                 for (Type t : getBounds(ib)) {
2302                     uv2.addBound(ib, t, types, true);
2303                 }
2304             }
2305             uv2.inst = inst;
2306             uv2.listener = listener;
2307             uv2.incorporationActions = new ArrayDeque<>();
2308             for (IncorporationAction action : incorporationActions) {
2309                 uv2.incorporationActions.add(action.dup(uv2));
2310             }
2311             uv2.kind = kind;
2312         }
2313 
2314         @Override
2315         public UndetVar cloneWithMetadata(TypeMetadata md) {
2316             throw new AssertionError("Cannot add metadata to an UndetVar type");
2317         }
2318 
2319         @Override
2320         public boolean isPartial() {
2321             return true;
2322         }
2323 
2324         @Override
2325         public Type baseType() {
2326             return (inst == null) ? this : inst.baseType();
2327         }
2328 
2329         public Type getInst() {
2330             return inst;
2331         }
2332 
2333         public void setInst(Type inst) {
2334             this.inst = inst;
2335             if (listener != null) {
2336                 listener.varInstantiated(this);
2337             }
2338         }
2339 
2340         /** get all bounds of a given kind */
2341         public List<Type> getBounds(InferenceBound... ibs) {
2342             ListBuffer<Type> buf = new ListBuffer<>();
2343             for (InferenceBound ib : ibs) {
2344                 buf.appendList(bounds.get(ib));
2345             }
2346             return buf.toList();
2347         }
2348 
2349         /** get the list of declared (upper) bounds */
2350         public List<Type> getDeclaredBounds() {
2351             ListBuffer<Type> buf = new ListBuffer<>();
2352             int count = 0;
2353             for (Type b : getBounds(InferenceBound.UPPER)) {
2354                 if (count++ == declaredCount) break;
2355                 buf.append(b);
2356             }
2357             return buf.toList();
2358         }
2359 
2360         /** internal method used to override an undetvar bounds */
2361         public void setBounds(InferenceBound ib, List<Type> newBounds) {
2362             bounds.put(ib, newBounds);
2363         }
2364 
2365         /** add a bound of a given kind - this might trigger listener notification */
2366         public final void addBound(InferenceBound ib, Type bound, Types types) {
2367             // Per JDK-8075793: in pre-8 sources, follow legacy javac behavior
2368             // when capture variables are inferred as bounds: for lower bounds,
2369             // map to the capture variable's upper bound; for upper bounds,
2370             // if the capture variable has a lower bound, map to that type
2371             if (types.mapCapturesToBounds) {
2372                 switch (ib) {
2373                     case LOWER:
2374                         bound = types.cvarUpperBound(bound);
2375                         break;
2376                     case UPPER:
2377                         Type altBound = types.cvarLowerBound(bound);
2378                         if (!altBound.hasTag(TypeTag.BOT)) bound = altBound;
2379                         break;
2380                 }
2381             }
2382             addBound(ib, bound, types, false);
2383         }
2384 
2385         @SuppressWarnings("fallthrough")
2386         private void addBound(InferenceBound ib, Type bound, Types types, boolean update) {
2387             if (kind == Kind.CAPTURED && !update) {
2388                 //Captured inference variables bounds must not be updated during incorporation,
2389                 //except when some inference variable (beta) has been instantiated in the
2390                 //right-hand-side of a 'C<alpha> = capture(C<? extends/super beta>) constraint.
2391                 if (bound.hasTag(UNDETVAR) && !((UndetVar)bound).isCaptured()) {
2392                     //If the new incoming bound is itself a (regular) inference variable,
2393                     //then we are allowed to propagate this inference variable bounds to it.
2394                     ((UndetVar)bound).addBound(ib.complement(), this, types, false);
2395                 }
2396             } else {
2397                 Type bound2 = bound.map(toTypeVarMap).baseType();
2398                 List<Type> prevBounds = bounds.get(ib);
2399                 if (bound == qtype) return;
2400                 for (Type b : prevBounds) {
2401                     //check for redundancy - do not add same bound twice
2402                     if (types.isSameType(b, bound2)) return;
2403                 }
2404                 bounds.put(ib, prevBounds.prepend(bound2));
2405                 notifyBoundChange(ib, bound2, false);
2406             }
2407         }
2408         //where
2409             TypeMapping<Void> toTypeVarMap = new StructuralTypeMapping<Void>() {
2410                 @Override
2411                 public Type visitUndetVar(UndetVar uv, Void _unused) {
2412                     return uv.inst != null ? uv.inst : uv.qtype;
2413                 }
2414             };
2415 
2416         /** replace types in all bounds - this might trigger listener notification */
2417         public void substBounds(List<Type> from, List<Type> to, Types types) {
2418             final ListBuffer<Pair<InferenceBound, Type>>  boundsChanged = new ListBuffer<>();
2419             UndetVarListener prevListener = listener;
2420             try {
2421                 //setup new listener for keeping track of changed bounds
2422                 listener = (uv, ib, t, _ignored) -> {
2423                     Assert.check(uv == UndetVar.this);
2424                     boundsChanged.add(new Pair<>(ib, t));
2425                 };
2426                 for (Map.Entry<InferenceBound, List<Type>> _entry : bounds.entrySet()) {
2427                     InferenceBound ib = _entry.getKey();
2428                     List<Type> prevBounds = _entry.getValue();
2429                     ListBuffer<Type> newBounds = new ListBuffer<>();
2430                     ListBuffer<Type> deps = new ListBuffer<>();
2431                     //step 1 - re-add bounds that are not dependent on ivars
2432                     for (Type t : prevBounds) {
2433                         if (!t.containsAny(from)) {
2434                             newBounds.append(t);
2435                         } else {
2436                             deps.append(t);
2437                         }
2438                     }
2439                     //step 2 - replace bounds
2440                     bounds.put(ib, newBounds.toList());
2441                     //step 3 - for each dependency, add new replaced bound
2442                     for (Type dep : deps) {
2443                         addBound(ib, types.subst(dep, from, to), types, true);
2444                     }
2445                 }
2446             } finally {
2447                 listener = prevListener;
2448                 for (Pair<InferenceBound, Type> boundUpdate : boundsChanged) {
2449                     notifyBoundChange(boundUpdate.fst, boundUpdate.snd, true);
2450                 }
2451             }
2452         }
2453 
2454         private void notifyBoundChange(InferenceBound ib, Type bound, boolean update) {
2455             if (listener != null) {
2456                 listener.varBoundChanged(this, ib, bound, update);
2457             }
2458         }
2459 
2460         public final boolean isCaptured() {
2461             return kind == Kind.CAPTURED;
2462         }
2463 
2464         public final boolean isThrows() {
2465             return kind == Kind.THROWS;
2466         }
2467     }
2468 
2469     /** Represents NONE.
2470      */
2471     public static class JCNoType extends Type implements NoType {
2472         public JCNoType() {
2473             // Need to use List.nil(), because JCNoType constructor
2474             // gets called in static initializers in Type, where
2475             // noAnnotations is also defined.
2476             super(null, TypeMetadata.EMPTY);
2477         }
2478 
2479         @Override
2480         public JCNoType cloneWithMetadata(TypeMetadata md) {
2481             throw new AssertionError("Cannot add metadata to a JCNoType");
2482         }
2483 
2484         @Override
2485         public TypeTag getTag() {
2486             return NONE;
2487         }
2488 
2489         @Override @DefinedBy(Api.LANGUAGE_MODEL)
2490         public TypeKind getKind() {
2491             return TypeKind.NONE;
2492         }
2493 
2494         @Override @DefinedBy(Api.LANGUAGE_MODEL)
2495         public <R, P> R accept(TypeVisitor<R, P> v, P p) {
2496             return v.visitNoType(this, p);
2497         }
2498 
2499         @Override
2500         public boolean isCompound() { return false; }
2501     }
2502 
2503     /** Represents VOID.
2504      */
2505     public static class JCVoidType extends Type implements NoType {
2506 
2507         public JCVoidType() {
2508             // Void cannot be annotated
2509             super(null, TypeMetadata.EMPTY);
2510         }
2511 
2512         @Override
2513         public JCVoidType cloneWithMetadata(TypeMetadata md) {
2514             throw new AssertionError("Cannot add metadata to a void type");
2515         }
2516 
2517         @Override
2518         public TypeTag getTag() {
2519             return VOID;
2520         }
2521 
2522         @Override @DefinedBy(Api.LANGUAGE_MODEL)
2523         public TypeKind getKind() {
2524             return TypeKind.VOID;
2525         }
2526 
2527         @Override
2528         public boolean isCompound() { return false; }
2529 
2530         @Override @DefinedBy(Api.LANGUAGE_MODEL)
2531         public <R, P> R accept(TypeVisitor<R, P> v, P p) {
2532             return v.visitNoType(this, p);
2533         }
2534 
2535         @Override
2536         public boolean isPrimitiveOrVoid() {
2537             return true;
2538         }
2539     }
2540 
2541     static class BottomType extends Type implements NullType {
2542         public BottomType() {
2543             // Bottom is a synthesized internal type, so it cannot be annotated
2544             super(null, TypeMetadata.EMPTY);
2545         }
2546 
2547         @Override
2548         public BottomType cloneWithMetadata(TypeMetadata md) {
2549             throw new AssertionError("Cannot add metadata to a bottom type");
2550         }
2551 
2552         @Override
2553         public TypeTag getTag() {
2554             return BOT;
2555         }
2556 
2557         @Override @DefinedBy(Api.LANGUAGE_MODEL)
2558         public TypeKind getKind() {
2559             return TypeKind.NULL;
2560         }
2561 
2562         @Override
2563         public boolean isCompound() { return false; }
2564 
2565         @Override @DefinedBy(Api.LANGUAGE_MODEL)
2566         public <R, P> R accept(TypeVisitor<R, P> v, P p) {
2567             return v.visitNull(this, p);
2568         }
2569 
2570         @Override
2571         public Type constType(Object value) {
2572             return this;
2573         }
2574 
2575         @Override
2576         public String stringValue() {
2577             return "null";
2578         }
2579 
2580         @Override
2581         public boolean isNullOrReference() {
2582             return true;
2583         }
2584 
2585     }
2586 
2587     public static class ErrorType extends ClassType
2588             implements javax.lang.model.type.ErrorType {
2589 
2590         private Type originalType = null;
2591 
2592         public ErrorType(ClassSymbol c, Type originalType) {
2593             this(originalType, c);
2594             c.type = this;
2595             c.kind = ERR;
2596             c.members_field = new Scope.ErrorScope(c);
2597         }
2598 
2599         public ErrorType(Type originalType, TypeSymbol tsym) {
2600             super(noType, List.nil(), tsym, TypeMetadata.EMPTY, Flavor.E_Typeof_X);
2601             this.originalType = (originalType == null ? noType : originalType);
2602         }
2603 
2604         private ErrorType(Type originalType, TypeSymbol tsym,
2605                           TypeMetadata metadata, Flavor flavor) {
2606             super(noType, List.nil(), null, metadata, flavor);
2607             this.tsym = tsym;
2608             this.originalType = (originalType == null ? noType : originalType);
2609         }
2610 
2611         @Override
2612         public ErrorType cloneWithMetadata(TypeMetadata md) {
2613             return new ErrorType(originalType, tsym, md, getFlavor()) {
2614                 @Override
2615                 public Type baseType() { return ErrorType.this.baseType(); }
2616             };
2617         }
2618 
2619         @Override
2620         public TypeTag getTag() {
2621             return ERROR;
2622         }
2623 
2624         @Override
2625         public boolean isPartial() {
2626             return true;
2627         }
2628 
2629         @Override
2630         public boolean isReference() {
2631             return true;
2632         }
2633 
2634         @Override
2635         public boolean isNullOrReference() {
2636             return true;
2637         }
2638 
2639         public ErrorType(Name name, TypeSymbol container, Type originalType) {
2640             this(new ClassSymbol(PUBLIC|STATIC|ACYCLIC, name, null, container), originalType);
2641         }
2642 
2643         @Override
2644         public <R,S> R accept(Type.Visitor<R,S> v, S s) {
2645             return v.visitErrorType(this, s);
2646         }
2647 
2648         public Type constType(Object constValue) { return this; }
2649         @DefinedBy(Api.LANGUAGE_MODEL)
2650         public Type getEnclosingType()           { return Type.noType; }
2651         public Type getReturnType()              { return this; }
2652         public Type asSub(Symbol sym)            { return this; }
2653 
2654         public boolean isGenType(Type t)         { return true; }
2655         public boolean isErroneous()             { return true; }
2656         public boolean isCompound()              { return false; }
2657         public boolean isInterface()             { return false; }
2658 
2659         public List<Type> allparams()            { return List.nil(); }
2660         @DefinedBy(Api.LANGUAGE_MODEL)
2661         public List<Type> getTypeArguments()     { return List.nil(); }
2662 
2663         @DefinedBy(Api.LANGUAGE_MODEL)
2664         public TypeKind getKind() {
2665             return TypeKind.ERROR;
2666         }
2667 
2668         public Type getOriginalType() {
2669             return originalType;
2670         }
2671 
2672         @DefinedBy(Api.LANGUAGE_MODEL)
2673         public <R, P> R accept(TypeVisitor<R, P> v, P p) {
2674             return v.visitError(this, p);
2675         }
2676     }
2677 
2678     public static class UnknownType extends Type {
2679 
2680         public UnknownType() {
2681             // Unknown is a synthesized internal type, so it cannot be
2682             // annotated.
2683             super(null, TypeMetadata.EMPTY);
2684         }
2685 
2686         @Override
2687         public UnknownType cloneWithMetadata(TypeMetadata md) {
2688             throw new AssertionError("Cannot add metadata to an unknown type");
2689         }
2690 
2691         @Override
2692         public TypeTag getTag() {
2693             return UNKNOWN;
2694         }
2695 
2696         @Override @DefinedBy(Api.LANGUAGE_MODEL)
2697         public <R, P> R accept(TypeVisitor<R, P> v, P p) {
2698             return v.visitUnknown(this, p);
2699         }
2700 
2701         @Override
2702         public boolean isPartial() {
2703             return true;
2704         }
2705     }
2706 
2707     /**
2708      * A visitor for types.  A visitor is used to implement operations
2709      * (or relations) on types.  Most common operations on types are
2710      * binary relations and this interface is designed for binary
2711      * relations, that is, operations of the form
2712      * Type&nbsp;&times;&nbsp;S&nbsp;&rarr;&nbsp;R.
2713      * <!-- In plain text: Type x S -> R -->
2714      *
2715      * @param <R> the return type of the operation implemented by this
2716      * visitor; use Void if no return type is needed.
2717      * @param <S> the type of the second argument (the first being the
2718      * type itself) of the operation implemented by this visitor; use
2719      * Void if a second argument is not needed.
2720      */
2721     public interface Visitor<R,S> {
2722         R visitClassType(ClassType t, S s);
2723         R visitWildcardType(WildcardType t, S s);
2724         R visitArrayType(ArrayType t, S s);
2725         R visitMethodType(MethodType t, S s);
2726         R visitPackageType(PackageType t, S s);
2727         R visitModuleType(ModuleType t, S s);
2728         R visitTypeVar(TypeVar t, S s);
2729         R visitCapturedType(CapturedType t, S s);
2730         R visitForAll(ForAll t, S s);
2731         R visitUndetVar(UndetVar t, S s);
2732         R visitErrorType(ErrorType t, S s);
2733         R visitType(Type t, S s);
2734     }
2735 }