1 /*
   2  * Copyright (c) 1999, 2019, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package com.sun.tools.javac.code;
  27 
  28 import java.lang.annotation.Annotation;
  29 import java.lang.annotation.Inherited;
  30 import java.util.Collections;
  31 import java.util.EnumSet;
  32 import java.util.Map;
  33 import java.util.Set;
  34 import java.util.concurrent.Callable;
  35 import java.util.function.Supplier;
  36 
  37 import javax.lang.model.element.Element;
  38 import javax.lang.model.element.ElementKind;
  39 import javax.lang.model.element.ElementVisitor;
  40 import javax.lang.model.element.ExecutableElement;
  41 import javax.lang.model.element.Modifier;
  42 import javax.lang.model.element.ModuleElement;
  43 import javax.lang.model.element.NestingKind;
  44 import javax.lang.model.element.PackageElement;
  45 import javax.lang.model.element.TypeElement;
  46 import javax.lang.model.element.TypeParameterElement;
  47 import javax.lang.model.element.VariableElement;
  48 import javax.tools.JavaFileManager;
  49 import javax.tools.JavaFileObject;
  50 
  51 import com.sun.tools.javac.code.Kinds.Kind;
  52 import com.sun.tools.javac.comp.Annotate.AnnotationTypeMetadata;
  53 import com.sun.tools.javac.code.Type.*;
  54 import com.sun.tools.javac.comp.Attr;
  55 import com.sun.tools.javac.comp.AttrContext;
  56 import com.sun.tools.javac.comp.Env;
  57 import com.sun.tools.javac.jvm.*;
  58 import com.sun.tools.javac.jvm.PoolConstant;
  59 import com.sun.tools.javac.tree.JCTree.JCFieldAccess;
  60 import com.sun.tools.javac.tree.JCTree.JCVariableDecl;
  61 import com.sun.tools.javac.tree.JCTree.Tag;
  62 import com.sun.tools.javac.util.*;
  63 import com.sun.tools.javac.util.DefinedBy.Api;
  64 import com.sun.tools.javac.util.Name;
  65 
  66 import static com.sun.tools.javac.code.Flags.*;
  67 import static com.sun.tools.javac.code.Kinds.*;
  68 import static com.sun.tools.javac.code.Kinds.Kind.*;
  69 import com.sun.tools.javac.code.MissingInfoHandler;
  70 import static com.sun.tools.javac.code.Scope.LookupKind.NON_RECURSIVE;
  71 import com.sun.tools.javac.code.Scope.WriteableScope;
  72 import com.sun.tools.javac.code.Symbol;
  73 import static com.sun.tools.javac.code.Symbol.OperatorSymbol.AccessCode.FIRSTASGOP;
  74 import com.sun.tools.javac.code.Type;
  75 import static com.sun.tools.javac.code.TypeTag.CLASS;
  76 import static com.sun.tools.javac.code.TypeTag.FORALL;
  77 import static com.sun.tools.javac.code.TypeTag.TYPEVAR;
  78 import static com.sun.tools.javac.jvm.ByteCodes.iadd;
  79 import static com.sun.tools.javac.jvm.ByteCodes.ishll;
  80 import static com.sun.tools.javac.jvm.ByteCodes.lushrl;
  81 import static com.sun.tools.javac.jvm.ByteCodes.lxor;
  82 import static com.sun.tools.javac.jvm.ByteCodes.string_add;
  83 import com.sun.tools.javac.util.Name;
  84 
  85 /** Root class for Java symbols. It contains subclasses
  86  *  for specific sorts of symbols, such as variables, methods and operators,
  87  *  types, packages. Each subclass is represented as a static inner class
  88  *  inside Symbol.
  89  *
  90  *  <p><b>This is NOT part of any supported API.
  91  *  If you write code that depends on this, you do so at your own risk.
  92  *  This code and its internal interfaces are subject to change or
  93  *  deletion without notice.</b>
  94  */
  95 public abstract class Symbol extends AnnoConstruct implements PoolConstant, Element {
  96 
  97     /** The kind of this symbol.
  98      *  @see Kinds
  99      */
 100     public Kind kind;
 101 
 102     /** The flags of this symbol.
 103      */
 104     public long flags_field;
 105 
 106     /** An accessor method for the flags of this symbol.
 107      *  Flags of class symbols should be accessed through the accessor
 108      *  method to make sure that the class symbol is loaded.
 109      */
 110     public long flags() { return flags_field; }
 111 
 112     /** The name of this symbol in Utf8 representation.
 113      */
 114     public Name name;
 115 
 116     /** The type of this symbol.
 117      */
 118     public Type type;
 119 
 120     /** The owner of this symbol.
 121      */
 122     public Symbol owner;
 123 
 124     /** The completer of this symbol.
 125      * This should never equal null (NULL_COMPLETER should be used instead).
 126      */
 127     public Completer completer;
 128 
 129     /** A cache for the type erasure of this symbol.
 130      */
 131     public Type erasure_field;
 132 
 133     // <editor-fold defaultstate="collapsed" desc="annotations">
 134 
 135     /** The attributes of this symbol are contained in this
 136      * SymbolMetadata. The SymbolMetadata instance is NOT immutable.
 137      */
 138     protected SymbolMetadata metadata;
 139 
 140 
 141     /** An accessor method for the attributes of this symbol.
 142      *  Attributes of class symbols should be accessed through the accessor
 143      *  method to make sure that the class symbol is loaded.
 144      */
 145     public List<Attribute.Compound> getRawAttributes() {
 146         return (metadata == null)
 147                 ? List.nil()
 148                 : metadata.getDeclarationAttributes();
 149     }
 150 
 151     /** An accessor method for the type attributes of this symbol.
 152      *  Attributes of class symbols should be accessed through the accessor
 153      *  method to make sure that the class symbol is loaded.
 154      */
 155     public List<Attribute.TypeCompound> getRawTypeAttributes() {
 156         return (metadata == null)
 157                 ? List.nil()
 158                 : metadata.getTypeAttributes();
 159     }
 160 
 161     /** Fetch a particular annotation from a symbol. */
 162     public Attribute.Compound attribute(Symbol anno) {
 163         for (Attribute.Compound a : getRawAttributes()) {
 164             if (a.type.tsym == anno) return a;
 165         }
 166         return null;
 167     }
 168 
 169     public boolean annotationsPendingCompletion() {
 170         return metadata == null ? false : metadata.pendingCompletion();
 171     }
 172 
 173     public void appendAttributes(List<Attribute.Compound> l) {
 174         if (l.nonEmpty()) {
 175             initedMetadata().append(l);
 176         }
 177     }
 178 
 179     public void appendClassInitTypeAttributes(List<Attribute.TypeCompound> l) {
 180         if (l.nonEmpty()) {
 181             initedMetadata().appendClassInitTypeAttributes(l);
 182         }
 183     }
 184 
 185     public void appendInitTypeAttributes(List<Attribute.TypeCompound> l) {
 186         if (l.nonEmpty()) {
 187             initedMetadata().appendInitTypeAttributes(l);
 188         }
 189     }
 190 
 191     public void appendUniqueTypeAttributes(List<Attribute.TypeCompound> l) {
 192         if (l.nonEmpty()) {
 193             initedMetadata().appendUniqueTypes(l);
 194         }
 195     }
 196 
 197     public List<Attribute.TypeCompound> getClassInitTypeAttributes() {
 198         return (metadata == null)
 199                 ? List.nil()
 200                 : metadata.getClassInitTypeAttributes();
 201     }
 202 
 203     public List<Attribute.TypeCompound> getInitTypeAttributes() {
 204         return (metadata == null)
 205                 ? List.nil()
 206                 : metadata.getInitTypeAttributes();
 207     }
 208 
 209     public void setInitTypeAttributes(List<Attribute.TypeCompound> l) {
 210         initedMetadata().setInitTypeAttributes(l);
 211     }
 212 
 213     public void setClassInitTypeAttributes(List<Attribute.TypeCompound> l) {
 214         initedMetadata().setClassInitTypeAttributes(l);
 215     }
 216 
 217     public List<Attribute.Compound> getDeclarationAttributes() {
 218         return (metadata == null)
 219                 ? List.nil()
 220                 : metadata.getDeclarationAttributes();
 221     }
 222 
 223     public boolean hasAnnotations() {
 224         return (metadata != null && !metadata.isEmpty());
 225     }
 226 
 227     public boolean hasTypeAnnotations() {
 228         return (metadata != null && !metadata.isTypesEmpty());
 229     }
 230 
 231     public boolean isCompleted() {
 232         return completer.isTerminal();
 233     }
 234 
 235     public void prependAttributes(List<Attribute.Compound> l) {
 236         if (l.nonEmpty()) {
 237             initedMetadata().prepend(l);
 238         }
 239     }
 240 
 241     public void resetAnnotations() {
 242         initedMetadata().reset();
 243     }
 244 
 245     public void setAttributes(Symbol other) {
 246         if (metadata != null || other.metadata != null) {
 247             initedMetadata().setAttributes(other.metadata);
 248         }
 249     }
 250 
 251     public void setDeclarationAttributes(List<Attribute.Compound> a) {
 252         if (metadata != null || a.nonEmpty()) {
 253             initedMetadata().setDeclarationAttributes(a);
 254         }
 255     }
 256 
 257     public void setTypeAttributes(List<Attribute.TypeCompound> a) {
 258         if (metadata != null || a.nonEmpty()) {
 259             if (metadata == null)
 260                 metadata = new SymbolMetadata(this);
 261             metadata.setTypeAttributes(a);
 262         }
 263     }
 264 
 265     private SymbolMetadata initedMetadata() {
 266         if (metadata == null)
 267             metadata = new SymbolMetadata(this);
 268         return metadata;
 269     }
 270 
 271     /** This method is intended for debugging only. */
 272     public SymbolMetadata getMetadata() {
 273         return metadata;
 274     }
 275 
 276     // </editor-fold>
 277 
 278     /** Construct a symbol with given kind, flags, name, type and owner.
 279      */
 280     public Symbol(Kind kind, long flags, Name name, Type type, Symbol owner) {
 281         this.kind = kind;
 282         this.flags_field = flags;
 283         this.type = type;
 284         this.owner = owner;
 285         this.completer = Completer.NULL_COMPLETER;
 286         this.erasure_field = null;
 287         this.name = name;
 288     }
 289 
 290     @Override
 291     public int poolTag() {
 292         throw new AssertionError("Invalid pool entry");
 293     }
 294 
 295     /** Clone this symbol with new owner.
 296      *  Legal only for fields and methods.
 297      */
 298     public Symbol clone(Symbol newOwner) {
 299         throw new AssertionError();
 300     }
 301 
 302     public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
 303         return v.visitSymbol(this, p);
 304     }
 305 
 306     /** The Java source which this symbol represents.
 307      *  A description of this symbol; overrides Object.
 308      */
 309     public String toString() {
 310         return name.toString();
 311     }
 312 
 313     /** A Java source description of the location of this symbol; used for
 314      *  error reporting.
 315      *
 316      * @return null if the symbol is a package or a toplevel class defined in
 317      * the default package; otherwise, the owner symbol is returned
 318      */
 319     public Symbol location() {
 320         if (owner.name == null || (owner.name.isEmpty() &&
 321                                    (owner.flags() & BLOCK) == 0 &&
 322                                    owner.kind != PCK &&
 323                                    owner.kind != TYP)) {
 324             return null;
 325         }
 326         return owner;
 327     }
 328 
 329     public Symbol location(Type site, Types types) {
 330         if (owner.name == null || owner.name.isEmpty()) {
 331             return location();
 332         }
 333         if (owner.type.hasTag(CLASS)) {
 334             Type ownertype = types.asOuterSuper(site, owner);
 335             if (ownertype != null) return ownertype.tsym;
 336         }
 337         return owner;
 338     }
 339 
 340     public Symbol baseSymbol() {
 341         return this;
 342     }
 343 
 344     /** The symbol's erased type.
 345      */
 346     public Type erasure(Types types) {
 347         if (erasure_field == null)
 348             erasure_field = types.erasure(type);
 349         return erasure_field;
 350     }
 351 
 352     /** The external type of a symbol. This is the symbol's erased type
 353      *  except for constructors of inner classes which get the enclosing
 354      *  instance class added as first argument.
 355      */
 356     public Type externalType(Types types) {
 357         Type t = erasure(types);
 358         if (name == name.table.names.init && owner.hasOuterInstance()) {
 359             Type outerThisType = types.erasure(owner.type.getEnclosingType());
 360             return new MethodType(t.getParameterTypes().prepend(outerThisType),
 361                                   t.getReturnType(),
 362                                   t.getThrownTypes(),
 363                                   t.tsym);
 364         } else {
 365             return t;
 366         }
 367     }
 368 
 369     public boolean isDeprecated() {
 370         return (flags_field & DEPRECATED) != 0;
 371     }
 372 
 373     public boolean isRecord() {
 374         return (flags_field & RECORD) != 0;
 375     }
 376 
 377     public boolean hasDeprecatedAnnotation() {
 378         return (flags_field & DEPRECATED_ANNOTATION) != 0;
 379     }
 380 
 381     public boolean isDeprecatedForRemoval() {
 382         return (flags_field & DEPRECATED_REMOVAL) != 0;
 383     }
 384 
 385     public boolean isDeprecatableViaAnnotation() {
 386         switch (getKind()) {
 387             case LOCAL_VARIABLE:
 388             case PACKAGE:
 389             case PARAMETER:
 390             case RESOURCE_VARIABLE:
 391             case EXCEPTION_PARAMETER:
 392                 return false;
 393             default:
 394                 return true;
 395         }
 396     }
 397 
 398     public boolean isStatic() {
 399         return
 400             (flags() & STATIC) != 0 ||
 401             (owner.flags() & INTERFACE) != 0 && kind != MTH &&
 402              name != name.table.names._this;
 403     }
 404 
 405     public boolean isInterface() {
 406         return (flags() & INTERFACE) != 0;
 407     }
 408 
 409     public boolean isAbstract() {
 410         return (flags() & ABSTRACT) != 0;
 411     }
 412 
 413     public boolean isPrivate() {
 414         return (flags_field & Flags.AccessFlags) == PRIVATE;
 415     }
 416 
 417     public boolean isEnum() {
 418         return (flags() & ENUM) != 0;
 419     }
 420 
 421     public boolean isSealed() {
 422         return (flags_field & SEALED) != 0;
 423     }
 424 
 425     public boolean isFinal() {
 426         return (flags_field & FINAL) != 0;
 427     }
 428 
 429     /** Is this symbol declared (directly or indirectly) local
 430      *  to a method or variable initializer?
 431      *  Also includes fields of inner classes which are in
 432      *  turn local to a method or variable initializer.
 433      */
 434     public boolean isLocal() {
 435         return
 436             (owner.kind.matches(KindSelector.VAL_MTH) ||
 437              (owner.kind == TYP && owner.isLocal()));
 438     }
 439 
 440     /** Has this symbol an empty name? This includes anonymous
 441      *  inner classes.
 442      */
 443     public boolean isAnonymous() {
 444         return name.isEmpty();
 445     }
 446 
 447     /** Is this symbol a constructor?
 448      */
 449     public boolean isConstructor() {
 450         return name == name.table.names.init;
 451     }
 452 
 453     public boolean isDynamic() {
 454         return false;
 455     }
 456 
 457     /** The fully qualified name of this symbol.
 458      *  This is the same as the symbol's name except for class symbols,
 459      *  which are handled separately.
 460      */
 461     public Name getQualifiedName() {
 462         return name;
 463     }
 464 
 465     /** The fully qualified name of this symbol after converting to flat
 466      *  representation. This is the same as the symbol's name except for
 467      *  class symbols, which are handled separately.
 468      */
 469     public Name flatName() {
 470         return getQualifiedName();
 471     }
 472 
 473     /** If this is a class or package, its members, otherwise null.
 474      */
 475     public WriteableScope members() {
 476         return null;
 477     }
 478 
 479     /** A class is an inner class if it it has an enclosing instance class.
 480      */
 481     public boolean isInner() {
 482         return kind == TYP && type.getEnclosingType().hasTag(CLASS);
 483     }
 484 
 485     /** An inner class has an outer instance if it is not an interface
 486      *  it has an enclosing instance class which might be referenced from the class.
 487      *  Nested classes can see instance members of their enclosing class.
 488      *  Their constructors carry an additional this$n parameter, inserted
 489      *  implicitly by the compiler.
 490      *
 491      *  @see #isInner
 492      */
 493     public boolean hasOuterInstance() {
 494         return
 495             type.getEnclosingType().hasTag(CLASS) && (flags() & (INTERFACE | NOOUTERTHIS)) == 0;
 496     }
 497 
 498     /** The closest enclosing class of this symbol's declaration.
 499      *  Warning: this (misnamed) method returns the receiver itself
 500      *  when the receiver is a class (as opposed to its enclosing
 501      *  class as one may be misled to believe.)
 502      */
 503     public ClassSymbol enclClass() {
 504         Symbol c = this;
 505         while (c != null &&
 506                (!c.kind.matches(KindSelector.TYP) || !c.type.hasTag(CLASS))) {
 507             c = c.owner;
 508         }
 509         return (ClassSymbol)c;
 510     }
 511 
 512     /** The outermost class which indirectly owns this symbol.
 513      */
 514     public ClassSymbol outermostClass() {
 515         Symbol sym = this;
 516         Symbol prev = null;
 517         while (sym.kind != PCK) {
 518             prev = sym;
 519             sym = sym.owner;
 520         }
 521         return (ClassSymbol) prev;
 522     }
 523 
 524     /** The package which indirectly owns this symbol.
 525      */
 526     public PackageSymbol packge() {
 527         Symbol sym = this;
 528         while (sym.kind != PCK) {
 529             sym = sym.owner;
 530         }
 531         return (PackageSymbol) sym;
 532     }
 533 
 534     /** Is this symbol a subclass of `base'? Only defined for ClassSymbols.
 535      */
 536     public boolean isSubClass(Symbol base, Types types) {
 537         throw new AssertionError("isSubClass " + this);
 538     }
 539 
 540     /** Fully check membership: hierarchy, protection, and hiding.
 541      *  Does not exclude methods not inherited due to overriding.
 542      */
 543     public boolean isMemberOf(TypeSymbol clazz, Types types) {
 544         return
 545             owner == clazz ||
 546             clazz.isSubClass(owner, types) &&
 547             isInheritedIn(clazz, types) &&
 548             !hiddenIn((ClassSymbol)clazz, types);
 549     }
 550 
 551     /** Is this symbol the same as or enclosed by the given class? */
 552     public boolean isEnclosedBy(ClassSymbol clazz) {
 553         for (Symbol sym = this; sym.kind != PCK; sym = sym.owner)
 554             if (sym == clazz) return true;
 555         return false;
 556     }
 557 
 558     private boolean hiddenIn(ClassSymbol clazz, Types types) {
 559         Symbol sym = hiddenInInternal(clazz, types);
 560         Assert.check(sym != null, "the result of hiddenInInternal() can't be null");
 561         /* If we find the current symbol then there is no symbol hiding it
 562          */
 563         return sym != this;
 564     }
 565 
 566     /** This method looks in the supertypes graph that has the current class as the
 567      * initial node, till it finds the current symbol or another symbol that hides it.
 568      * If the current class has more than one supertype (extends one class and
 569      * implements one or more interfaces) then null can be returned, meaning that
 570      * a wrong path in the supertypes graph was selected. Null can only be returned
 571      * as a temporary value, as a result of the recursive call.
 572      */
 573     private Symbol hiddenInInternal(ClassSymbol currentClass, Types types) {
 574         if (currentClass == owner) {
 575             return this;
 576         }
 577         for (Symbol sym : currentClass.members().getSymbolsByName(name)) {
 578             if (sym.kind == kind &&
 579                     (kind != MTH ||
 580                     (sym.flags() & STATIC) != 0 &&
 581                     types.isSubSignature(sym.type, type))) {
 582                 return sym;
 583             }
 584         }
 585         Symbol hiddenSym = null;
 586         for (Type st : types.interfaces(currentClass.type)
 587                 .prepend(types.supertype(currentClass.type))) {
 588             if (st != null && (st.hasTag(CLASS))) {
 589                 Symbol sym = hiddenInInternal((ClassSymbol)st.tsym, types);
 590                 if (sym == this) {
 591                     return this;
 592                 } else if (sym != null) {
 593                     hiddenSym = sym;
 594                 }
 595             }
 596         }
 597         return hiddenSym;
 598     }
 599 
 600     /** Is this symbol accessible in a given class?
 601      *  PRE: If symbol's owner is a interface,
 602      *       it is already assumed that the interface is a superinterface
 603      *       the given class.
 604      *  @param clazz  The class for which we want to establish membership.
 605      *                This must be a subclass of the member's owner.
 606      */
 607     public final boolean isAccessibleIn(Symbol clazz, Types types) {
 608         switch ((int)(flags_field & Flags.AccessFlags)) {
 609         default: // error recovery
 610         case PUBLIC:
 611             return true;
 612         case PRIVATE:
 613             return this.owner == clazz;
 614         case PROTECTED:
 615             // we model interfaces as extending Object
 616             return (clazz.flags() & INTERFACE) == 0;
 617         case 0:
 618             PackageSymbol thisPackage = this.packge();
 619             for (Symbol sup = clazz;
 620                  sup != null && sup != this.owner;
 621                  sup = types.supertype(sup.type).tsym) {
 622                 while (sup.type.hasTag(TYPEVAR))
 623                     sup = sup.type.getUpperBound().tsym;
 624                 if (sup.type.isErroneous())
 625                     return true; // error recovery
 626                 if ((sup.flags() & COMPOUND) != 0)
 627                     continue;
 628                 if (sup.packge() != thisPackage)
 629                     return false;
 630             }
 631             return (clazz.flags() & INTERFACE) == 0;
 632         }
 633     }
 634 
 635     /** Is this symbol inherited into a given class?
 636      *  PRE: If symbol's owner is a interface,
 637      *       it is already assumed that the interface is a superinterface
 638      *       of the given class.
 639      *  @param clazz  The class for which we want to establish membership.
 640      *                This must be a subclass of the member's owner.
 641      */
 642     public boolean isInheritedIn(Symbol clazz, Types types) {
 643         return isAccessibleIn(clazz, types);
 644     }
 645 
 646     /** The (variable or method) symbol seen as a member of given
 647      *  class type`site' (this might change the symbol's type).
 648      *  This is used exclusively for producing diagnostics.
 649      */
 650     public Symbol asMemberOf(Type site, Types types) {
 651         throw new AssertionError();
 652     }
 653 
 654     /** Does this method symbol override `other' symbol, when both are seen as
 655      *  members of class `origin'?  It is assumed that _other is a member
 656      *  of origin.
 657      *
 658      *  It is assumed that both symbols have the same name.  The static
 659      *  modifier is ignored for this test.
 660      *
 661      *  See JLS 8.4.6.1 (without transitivity) and 8.4.6.4
 662      */
 663     public boolean overrides(Symbol _other, TypeSymbol origin, Types types, boolean checkResult) {
 664         return false;
 665     }
 666 
 667     /** Complete the elaboration of this symbol's definition.
 668      */
 669     public void complete() throws CompletionFailure {
 670         if (completer != Completer.NULL_COMPLETER) {
 671             Completer c = completer;
 672             completer = Completer.NULL_COMPLETER;
 673             c.complete(this);
 674         }
 675     }
 676 
 677     public void apiComplete() throws CompletionFailure {
 678         try {
 679             complete();
 680         } catch (CompletionFailure cf) {
 681             cf.dcfh.handleAPICompletionFailure(cf);
 682         }
 683     }
 684 
 685     /** True if the symbol represents an entity that exists.
 686      */
 687     public boolean exists() {
 688         return true;
 689     }
 690 
 691     @DefinedBy(Api.LANGUAGE_MODEL)
 692     public Type asType() {
 693         return type;
 694     }
 695 
 696     @DefinedBy(Api.LANGUAGE_MODEL)
 697     public Symbol getEnclosingElement() {
 698         return owner;
 699     }
 700 
 701     @DefinedBy(Api.LANGUAGE_MODEL)
 702     public ElementKind getKind() {
 703         return ElementKind.OTHER;       // most unkind
 704     }
 705 
 706     @DefinedBy(Api.LANGUAGE_MODEL)
 707     public Set<Modifier> getModifiers() {
 708         apiComplete();
 709         return Flags.asModifierSet(flags());
 710     }
 711 
 712     @DefinedBy(Api.LANGUAGE_MODEL)
 713     public Name getSimpleName() {
 714         return name;
 715     }
 716 
 717     /**
 718      * This is the implementation for {@code
 719      * javax.lang.model.element.Element.getAnnotationMirrors()}.
 720      */
 721     @Override @DefinedBy(Api.LANGUAGE_MODEL)
 722     public List<Attribute.Compound> getAnnotationMirrors() {
 723         apiComplete();
 724         return getRawAttributes();
 725     }
 726 
 727 
 728     // TODO: getEnclosedElements should return a javac List, fix in FilteredMemberList
 729     @DefinedBy(Api.LANGUAGE_MODEL)
 730     public java.util.List<Symbol> getEnclosedElements() {
 731         return List.nil();
 732     }
 733 
 734     public List<TypeVariableSymbol> getTypeParameters() {
 735         ListBuffer<TypeVariableSymbol> l = new ListBuffer<>();
 736         for (Type t : type.getTypeArguments()) {
 737             Assert.check(t.tsym.getKind() == ElementKind.TYPE_PARAMETER);
 738             l.append((TypeVariableSymbol)t.tsym);
 739         }
 740         return l.toList();
 741     }
 742 
 743     public static class DelegatedSymbol<T extends Symbol> extends Symbol {
 744         protected T other;
 745         public DelegatedSymbol(T other) {
 746             super(other.kind, other.flags_field, other.name, other.type, other.owner);
 747             this.other = other;
 748         }
 749         public String toString() { return other.toString(); }
 750         public Symbol location() { return other.location(); }
 751         public Symbol location(Type site, Types types) { return other.location(site, types); }
 752         public Symbol baseSymbol() { return other; }
 753         public Type erasure(Types types) { return other.erasure(types); }
 754         public Type externalType(Types types) { return other.externalType(types); }
 755         public boolean isLocal() { return other.isLocal(); }
 756         public boolean isConstructor() { return other.isConstructor(); }
 757         public Name getQualifiedName() { return other.getQualifiedName(); }
 758         public Name flatName() { return other.flatName(); }
 759         public WriteableScope members() { return other.members(); }
 760         public boolean isInner() { return other.isInner(); }
 761         public boolean hasOuterInstance() { return other.hasOuterInstance(); }
 762         public ClassSymbol enclClass() { return other.enclClass(); }
 763         public ClassSymbol outermostClass() { return other.outermostClass(); }
 764         public PackageSymbol packge() { return other.packge(); }
 765         public boolean isSubClass(Symbol base, Types types) { return other.isSubClass(base, types); }
 766         public boolean isMemberOf(TypeSymbol clazz, Types types) { return other.isMemberOf(clazz, types); }
 767         public boolean isEnclosedBy(ClassSymbol clazz) { return other.isEnclosedBy(clazz); }
 768         public boolean isInheritedIn(Symbol clazz, Types types) { return other.isInheritedIn(clazz, types); }
 769         public Symbol asMemberOf(Type site, Types types) { return other.asMemberOf(site, types); }
 770         public void complete() throws CompletionFailure { other.complete(); }
 771 
 772         @DefinedBy(Api.LANGUAGE_MODEL)
 773         public <R, P> R accept(ElementVisitor<R, P> v, P p) {
 774             return other.accept(v, p);
 775         }
 776 
 777         public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
 778             return v.visitSymbol(other, p);
 779         }
 780 
 781         public T getUnderlyingSymbol() {
 782             return other;
 783         }
 784     }
 785 
 786     /** A base class for Symbols representing types.
 787      */
 788     public static abstract class TypeSymbol extends Symbol {
 789         public TypeSymbol(Kind kind, long flags, Name name, Type type, Symbol owner) {
 790             super(kind, flags, name, type, owner);
 791         }
 792         /** form a fully qualified name from a name and an owner
 793          */
 794         static public Name formFullName(Name name, Symbol owner) {
 795             if (owner == null) return name;
 796             if ((owner.kind != ERR) &&
 797                 (owner.kind.matches(KindSelector.VAL_MTH) ||
 798                  (owner.kind == TYP && owner.type.hasTag(TYPEVAR))
 799                  )) return name;
 800             Name prefix = owner.getQualifiedName();
 801             if (prefix == null || prefix == prefix.table.names.empty)
 802                 return name;
 803             else return prefix.append('.', name);
 804         }
 805 
 806         /** form a fully qualified name from a name and an owner, after
 807          *  converting to flat representation
 808          */
 809         static public Name formFlatName(Name name, Symbol owner) {
 810             if (owner == null || owner.kind.matches(KindSelector.VAL_MTH) ||
 811                 (owner.kind == TYP && owner.type.hasTag(TYPEVAR))
 812                 ) return name;
 813             char sep = owner.kind == TYP ? '$' : '.';
 814             Name prefix = owner.flatName();
 815             if (prefix == null || prefix == prefix.table.names.empty)
 816                 return name;
 817             else return prefix.append(sep, name);
 818         }
 819 
 820         /**
 821          * A partial ordering between type symbols that refines the
 822          * class inheritance graph.
 823          *
 824          * Type variables always precede other kinds of symbols.
 825          */
 826         public final boolean precedes(TypeSymbol that, Types types) {
 827             if (this == that)
 828                 return false;
 829             if (type.hasTag(that.type.getTag())) {
 830                 if (type.hasTag(CLASS)) {
 831                     return
 832                         types.rank(that.type) < types.rank(this.type) ||
 833                         types.rank(that.type) == types.rank(this.type) &&
 834                         that.getQualifiedName().compareTo(this.getQualifiedName()) < 0;
 835                 } else if (type.hasTag(TYPEVAR)) {
 836                     return types.isSubtype(this.type, that.type);
 837                 }
 838             }
 839             return type.hasTag(TYPEVAR);
 840         }
 841 
 842         @Override @DefinedBy(Api.LANGUAGE_MODEL)
 843         public java.util.List<Symbol> getEnclosedElements() {
 844             List<Symbol> list = List.nil();
 845             if (kind == TYP && type.hasTag(TYPEVAR)) {
 846                 return list;
 847             }
 848             apiComplete();
 849             for (Symbol sym : members().getSymbols(NON_RECURSIVE)) {
 850                 sym.apiComplete();
 851                 if ((sym.flags() & SYNTHETIC) == 0 && sym.owner == this && sym.kind != ERR) {
 852                     list = list.prepend(sym);
 853                 }
 854             }
 855             return list;
 856         }
 857 
 858         public AnnotationTypeMetadata getAnnotationTypeMetadata() {
 859             Assert.error("Only on ClassSymbol");
 860             return null; //unreachable
 861         }
 862 
 863         public boolean isAnnotationType() { return false; }
 864 
 865         @Override
 866         public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
 867             return v.visitTypeSymbol(this, p);
 868         }
 869     }
 870 
 871     /**
 872      * Type variables are represented by instances of this class.
 873      */
 874     public static class TypeVariableSymbol
 875             extends TypeSymbol implements TypeParameterElement {
 876 
 877         public TypeVariableSymbol(long flags, Name name, Type type, Symbol owner) {
 878             super(TYP, flags, name, type, owner);
 879         }
 880 
 881         @DefinedBy(Api.LANGUAGE_MODEL)
 882         public ElementKind getKind() {
 883             return ElementKind.TYPE_PARAMETER;
 884         }
 885 
 886         @Override @DefinedBy(Api.LANGUAGE_MODEL)
 887         public Symbol getGenericElement() {
 888             return owner;
 889         }
 890 
 891         @DefinedBy(Api.LANGUAGE_MODEL)
 892         public List<Type> getBounds() {
 893             TypeVar t = (TypeVar)type;
 894             Type bound = t.getUpperBound();
 895             if (!bound.isCompound())
 896                 return List.of(bound);
 897             ClassType ct = (ClassType)bound;
 898             if (!ct.tsym.erasure_field.isInterface()) {
 899                 return ct.interfaces_field.prepend(ct.supertype_field);
 900             } else {
 901                 // No superclass was given in bounds.
 902                 // In this case, supertype is Object, erasure is first interface.
 903                 return ct.interfaces_field;
 904             }
 905         }
 906 
 907         @Override @DefinedBy(Api.LANGUAGE_MODEL)
 908         public List<Attribute.Compound> getAnnotationMirrors() {
 909             // Declaration annotations on type variables are stored in type attributes
 910             // on the owner of the TypeVariableSymbol
 911             List<Attribute.TypeCompound> candidates = owner.getRawTypeAttributes();
 912             int index = owner.getTypeParameters().indexOf(this);
 913             List<Attribute.Compound> res = List.nil();
 914             for (Attribute.TypeCompound a : candidates) {
 915                 if (isCurrentSymbolsAnnotation(a, index))
 916                     res = res.prepend(a);
 917             }
 918 
 919             return res.reverse();
 920         }
 921 
 922         // Helper to getAnnotation[s]
 923         @Override
 924         public <A extends Annotation> Attribute.Compound getAttribute(Class<A> annoType) {
 925             String name = annoType.getName();
 926 
 927             // Declaration annotations on type variables are stored in type attributes
 928             // on the owner of the TypeVariableSymbol
 929             List<Attribute.TypeCompound> candidates = owner.getRawTypeAttributes();
 930             int index = owner.getTypeParameters().indexOf(this);
 931             for (Attribute.TypeCompound anno : candidates)
 932                 if (isCurrentSymbolsAnnotation(anno, index) &&
 933                     name.contentEquals(anno.type.tsym.flatName()))
 934                     return anno;
 935 
 936             return null;
 937         }
 938             //where:
 939             boolean isCurrentSymbolsAnnotation(Attribute.TypeCompound anno, int index) {
 940                 return (anno.position.type == TargetType.CLASS_TYPE_PARAMETER ||
 941                         anno.position.type == TargetType.METHOD_TYPE_PARAMETER) &&
 942                         anno.position.parameter_index == index;
 943             }
 944 
 945 
 946         @Override @DefinedBy(Api.LANGUAGE_MODEL)
 947         public <R, P> R accept(ElementVisitor<R, P> v, P p) {
 948             return v.visitTypeParameter(this, p);
 949         }
 950     }
 951     /** A class for module symbols.
 952      */
 953     public static class ModuleSymbol extends TypeSymbol
 954             implements ModuleElement {
 955 
 956         public Name version;
 957         public JavaFileManager.Location sourceLocation;
 958         public JavaFileManager.Location classLocation;
 959         public JavaFileManager.Location patchLocation;
 960         public JavaFileManager.Location patchOutputLocation;
 961 
 962         /** All directives, in natural order. */
 963         public List<com.sun.tools.javac.code.Directive> directives;
 964         public List<com.sun.tools.javac.code.Directive.RequiresDirective> requires;
 965         public List<com.sun.tools.javac.code.Directive.ExportsDirective> exports;
 966         public List<com.sun.tools.javac.code.Directive.OpensDirective> opens;
 967         public List<com.sun.tools.javac.code.Directive.ProvidesDirective> provides;
 968         public List<com.sun.tools.javac.code.Directive.UsesDirective> uses;
 969 
 970         public ClassSymbol module_info;
 971 
 972         public PackageSymbol unnamedPackage;
 973         public Map<Name, PackageSymbol> visiblePackages;
 974         public Set<ModuleSymbol> readModules;
 975         public List<Symbol> enclosedPackages = List.nil();
 976 
 977         public Completer usesProvidesCompleter = Completer.NULL_COMPLETER;
 978         public final Set<ModuleFlags> flags = EnumSet.noneOf(ModuleFlags.class);
 979         public final Set<ModuleResolutionFlags> resolutionFlags = EnumSet.noneOf(ModuleResolutionFlags.class);
 980 
 981         /**
 982          * Create a ModuleSymbol with an associated module-info ClassSymbol.
 983          */
 984         public static ModuleSymbol create(Name name, Name module_info) {
 985             ModuleSymbol msym = new ModuleSymbol(name, null);
 986             ClassSymbol info = new ClassSymbol(Flags.MODULE, module_info, msym);
 987             info.fullname = formFullName(module_info, msym);
 988             info.flatname = info.fullname;
 989             info.members_field = WriteableScope.create(info);
 990             msym.module_info = info;
 991             return msym;
 992         }
 993 
 994         public ModuleSymbol(Name name, Symbol owner) {
 995             super(MDL, 0, name, null, owner);
 996             Assert.checkNonNull(name);
 997             this.type = new ModuleType(this);
 998         }
 999 
1000         @Override
1001         public int poolTag() {
1002             return ClassFile.CONSTANT_Module;
1003         }
1004 
1005         @Override @DefinedBy(Api.LANGUAGE_MODEL)
1006         public Name getSimpleName() {
1007             return Convert.shortName(name);
1008         }
1009 
1010         @Override @DefinedBy(Api.LANGUAGE_MODEL)
1011         public boolean isOpen() {
1012             return flags.contains(ModuleFlags.OPEN);
1013         }
1014 
1015         @Override @DefinedBy(Api.LANGUAGE_MODEL)
1016         public boolean isUnnamed() {
1017             return name.isEmpty() && owner == null;
1018         }
1019 
1020         @Override
1021         public boolean isDeprecated() {
1022             return hasDeprecatedAnnotation();
1023         }
1024 
1025         public boolean isNoModule() {
1026             return false;
1027         }
1028 
1029         @Override @DefinedBy(Api.LANGUAGE_MODEL)
1030         public ElementKind getKind() {
1031             return ElementKind.MODULE;
1032         }
1033 
1034         @Override @DefinedBy(Api.LANGUAGE_MODEL)
1035         public java.util.List<Directive> getDirectives() {
1036             apiComplete();
1037             completeUsesProvides();
1038             return Collections.unmodifiableList(directives);
1039         }
1040 
1041         public void completeUsesProvides() {
1042             if (usesProvidesCompleter != Completer.NULL_COMPLETER) {
1043                 Completer c = usesProvidesCompleter;
1044                 usesProvidesCompleter = Completer.NULL_COMPLETER;
1045                 c.complete(this);
1046             }
1047         }
1048 
1049         @Override
1050         public ClassSymbol outermostClass() {
1051             return null;
1052         }
1053 
1054         @Override
1055         public String toString() {
1056             // TODO: the following strings should be localized
1057             // Do this with custom anon subtypes in Symtab
1058             String n = (name == null) ? "<unknown>"
1059                     : (name.isEmpty()) ? "<unnamed>"
1060                     : String.valueOf(name);
1061             return n;
1062         }
1063 
1064         @Override @DefinedBy(Api.LANGUAGE_MODEL)
1065         public <R, P> R accept(ElementVisitor<R, P> v, P p) {
1066             return v.visitModule(this, p);
1067         }
1068 
1069         @Override @DefinedBy(Api.LANGUAGE_MODEL)
1070         public List<Symbol> getEnclosedElements() {
1071             List<Symbol> list = List.nil();
1072             for (Symbol sym : enclosedPackages) {
1073                 if (sym.members().anyMatch(m -> m.kind == TYP))
1074                     list = list.prepend(sym);
1075             }
1076             return list;
1077         }
1078 
1079         public void reset() {
1080             this.directives = null;
1081             this.requires = null;
1082             this.exports = null;
1083             this.provides = null;
1084             this.uses = null;
1085             this.visiblePackages = null;
1086         }
1087 
1088     }
1089 
1090     public enum ModuleFlags {
1091         OPEN(0x0020),
1092         SYNTHETIC(0x1000),
1093         MANDATED(0x8000);
1094 
1095         public static int value(Set<ModuleFlags> s) {
1096             int v = 0;
1097             for (ModuleFlags f: s)
1098                 v |= f.value;
1099             return v;
1100         }
1101 
1102         private ModuleFlags(int value) {
1103             this.value = value;
1104         }
1105 
1106         public final int value;
1107     }
1108 
1109     public enum ModuleResolutionFlags {
1110         DO_NOT_RESOLVE_BY_DEFAULT(0x0001),
1111         WARN_DEPRECATED(0x0002),
1112         WARN_DEPRECATED_REMOVAL(0x0004),
1113         WARN_INCUBATING(0x0008);
1114 
1115         public static int value(Set<ModuleResolutionFlags> s) {
1116             int v = 0;
1117             for (ModuleResolutionFlags f: s)
1118                 v |= f.value;
1119             return v;
1120         }
1121 
1122         private ModuleResolutionFlags(int value) {
1123             this.value = value;
1124         }
1125 
1126         public final int value;
1127     }
1128 
1129     /** A class for package symbols
1130      */
1131     public static class PackageSymbol extends TypeSymbol
1132         implements PackageElement {
1133 
1134         public WriteableScope members_field;
1135         public Name fullname;
1136         public ClassSymbol package_info; // see bug 6443073
1137         public ModuleSymbol modle;
1138         // the file containing the documentation comments for the package
1139         public JavaFileObject sourcefile;
1140 
1141         public PackageSymbol(Name name, Type type, Symbol owner) {
1142             super(PCK, 0, name, type, owner);
1143             this.members_field = null;
1144             this.fullname = formFullName(name, owner);
1145         }
1146 
1147         public PackageSymbol(Name name, Symbol owner) {
1148             this(name, null, owner);
1149             this.type = new PackageType(this);
1150         }
1151 
1152         public String toString() {
1153             return fullname.toString();
1154         }
1155 
1156         @DefinedBy(Api.LANGUAGE_MODEL)
1157         public Name getQualifiedName() {
1158             return fullname;
1159         }
1160 
1161         @DefinedBy(Api.LANGUAGE_MODEL)
1162         public boolean isUnnamed() {
1163             return name.isEmpty() && owner != null;
1164         }
1165 
1166         public WriteableScope members() {
1167             complete();
1168             return members_field;
1169         }
1170 
1171         @Override
1172         public int poolTag() {
1173             return ClassFile.CONSTANT_Package;
1174         }
1175 
1176         public long flags() {
1177             complete();
1178             return flags_field;
1179         }
1180 
1181         @Override
1182         public List<Attribute.Compound> getRawAttributes() {
1183             complete();
1184             if (package_info != null) {
1185                 package_info.complete();
1186                 mergeAttributes();
1187             }
1188             return super.getRawAttributes();
1189         }
1190 
1191         private void mergeAttributes() {
1192             if (metadata == null &&
1193                 package_info.metadata != null) {
1194                 metadata = new SymbolMetadata(this);
1195                 metadata.setAttributes(package_info.metadata);
1196             }
1197         }
1198 
1199         /** A package "exists" if a type or package that exists has
1200          *  been seen within it.
1201          */
1202         public boolean exists() {
1203             return (flags_field & EXISTS) != 0;
1204         }
1205 
1206         @DefinedBy(Api.LANGUAGE_MODEL)
1207         public ElementKind getKind() {
1208             return ElementKind.PACKAGE;
1209         }
1210 
1211         @DefinedBy(Api.LANGUAGE_MODEL)
1212         public Symbol getEnclosingElement() {
1213             return modle != null && !modle.isNoModule() ? modle : null;
1214         }
1215 
1216         @DefinedBy(Api.LANGUAGE_MODEL)
1217         public <R, P> R accept(ElementVisitor<R, P> v, P p) {
1218             return v.visitPackage(this, p);
1219         }
1220 
1221         public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
1222             return v.visitPackageSymbol(this, p);
1223         }
1224 
1225         /**Resets the Symbol into the state good for next round of annotation processing.*/
1226         public void reset() {
1227             metadata = null;
1228         }
1229 
1230     }
1231 
1232     public static class RootPackageSymbol extends PackageSymbol {
1233         public final MissingInfoHandler missingInfoHandler;
1234 
1235         public RootPackageSymbol(Name name, Symbol owner, MissingInfoHandler missingInfoHandler) {
1236             super(name, owner);
1237             this.missingInfoHandler = missingInfoHandler;
1238         }
1239 
1240     }
1241 
1242     /** A class for class symbols
1243      */
1244     public static class ClassSymbol extends TypeSymbol implements TypeElement {
1245 
1246         /** a scope for all class members; variables, methods and inner classes
1247          *  type parameters are not part of this scope
1248          */
1249         public WriteableScope members_field;
1250 
1251         /** the fully qualified name of the class, i.e. pck.outer.inner.
1252          *  null for anonymous classes
1253          */
1254         public Name fullname;
1255 
1256         /** the fully qualified name of the class after converting to flat
1257          *  representation, i.e. pck.outer$inner,
1258          *  set externally for local and anonymous classes
1259          */
1260         public Name flatname;
1261 
1262         /** the sourcefile where the class came from
1263          */
1264         public JavaFileObject sourcefile;
1265 
1266         /** the classfile from where to load this class
1267          *  this will have extension .class or .java
1268          */
1269         public JavaFileObject classfile;
1270 
1271         /** the list of translated local classes (used for generating
1272          * InnerClasses attribute)
1273          */
1274         public List<ClassSymbol> trans_local;
1275 
1276         /** the annotation metadata attached to this class */
1277         private AnnotationTypeMetadata annotationTypeMetadata;
1278 
1279         public ClassSymbol(long flags, Name name, Type type, Symbol owner) {
1280             super(TYP, flags, name, type, owner);
1281             this.members_field = null;
1282             this.fullname = formFullName(name, owner);
1283             this.flatname = formFlatName(name, owner);
1284             this.sourcefile = null;
1285             this.classfile = null;
1286             this.annotationTypeMetadata = AnnotationTypeMetadata.notAnAnnotationType();
1287         }
1288 
1289         public ClassSymbol(long flags, Name name, Symbol owner) {
1290             this(
1291                 flags,
1292                 name,
1293                 new ClassType(Type.noType, null, null),
1294                 owner);
1295             this.type.tsym = this;
1296         }
1297 
1298         /** The Java source which this symbol represents.
1299          */
1300         public String toString() {
1301             return className();
1302         }
1303 
1304         public long flags() {
1305             complete();
1306             return flags_field;
1307         }
1308 
1309         public WriteableScope members() {
1310             complete();
1311             return members_field;
1312         }
1313 
1314         @Override
1315         public List<Attribute.Compound> getRawAttributes() {
1316             complete();
1317             return super.getRawAttributes();
1318         }
1319 
1320         @Override
1321         public List<Attribute.TypeCompound> getRawTypeAttributes() {
1322             complete();
1323             return super.getRawTypeAttributes();
1324         }
1325 
1326         public Type erasure(Types types) {
1327             if (erasure_field == null)
1328                 erasure_field = new ClassType(types.erasure(type.getEnclosingType()),
1329                                               List.nil(), this,
1330                                               type.getMetadata());
1331             return erasure_field;
1332         }
1333 
1334         public String className() {
1335             if (name.isEmpty())
1336                 return
1337                     Log.getLocalizedString("anonymous.class", flatname);
1338             else
1339                 return fullname.toString();
1340         }
1341 
1342         @DefinedBy(Api.LANGUAGE_MODEL)
1343         public Name getQualifiedName() {
1344             return fullname;
1345         }
1346 
1347         public Name flatName() {
1348             return flatname;
1349         }
1350 
1351         public boolean isSubClass(Symbol base, Types types) {
1352             if (this == base) {
1353                 return true;
1354             } else if ((base.flags() & INTERFACE) != 0) {
1355                 for (Type t = type; t.hasTag(CLASS); t = types.supertype(t))
1356                     for (List<Type> is = types.interfaces(t);
1357                          is.nonEmpty();
1358                          is = is.tail)
1359                         if (is.head.tsym.isSubClass(base, types)) return true;
1360             } else {
1361                 for (Type t = type; t.hasTag(CLASS); t = types.supertype(t))
1362                     if (t.tsym == base) return true;
1363             }
1364             return false;
1365         }
1366 
1367         /** Complete the elaboration of this symbol's definition.
1368          */
1369         public void complete() throws CompletionFailure {
1370             Completer origCompleter = completer;
1371             try {
1372                 super.complete();
1373             } catch (CompletionFailure ex) {
1374                 ex.dcfh.classSymbolCompleteFailed(this, origCompleter);
1375                 // quiet error recovery
1376                 flags_field |= (PUBLIC|STATIC);
1377                 this.type = new ErrorType(this, Type.noType);
1378                 throw ex;
1379             }
1380         }
1381 
1382         @DefinedBy(Api.LANGUAGE_MODEL)
1383         public List<Type> getInterfaces() {
1384             apiComplete();
1385             if (type instanceof ClassType) {
1386                 ClassType t = (ClassType)type;
1387                 if (t.interfaces_field == null) // FIXME: shouldn't be null
1388                     t.interfaces_field = List.nil();
1389                 if (t.all_interfaces_field != null)
1390                     return Type.getModelTypes(t.all_interfaces_field);
1391                 return t.interfaces_field;
1392             } else {
1393                 return List.nil();
1394             }
1395         }
1396 
1397         @DefinedBy(Api.LANGUAGE_MODEL)
1398         public Type getSuperclass() {
1399             apiComplete();
1400             if (type instanceof ClassType) {
1401                 ClassType t = (ClassType)type;
1402                 if (t.supertype_field == null) // FIXME: shouldn't be null
1403                     t.supertype_field = Type.noType;
1404                 // An interface has no superclass; its supertype is Object.
1405                 return t.isInterface()
1406                     ? Type.noType
1407                     : t.supertype_field.getModelType();
1408             } else {
1409                 return Type.noType;
1410             }
1411         }
1412 
1413         /**
1414          * Returns the next class to search for inherited annotations or {@code null}
1415          * if the next class can't be found.
1416          */
1417         private ClassSymbol getSuperClassToSearchForAnnotations() {
1418 
1419             Type sup = getSuperclass();
1420 
1421             if (!sup.hasTag(CLASS) || sup.isErroneous())
1422                 return null;
1423 
1424             return (ClassSymbol) sup.tsym;
1425         }
1426 
1427 
1428         @Override
1429         protected <A extends Annotation> A[] getInheritedAnnotations(Class<A> annoType) {
1430 
1431             ClassSymbol sup = getSuperClassToSearchForAnnotations();
1432 
1433             return sup == null ? super.getInheritedAnnotations(annoType)
1434                                : sup.getAnnotationsByType(annoType);
1435         }
1436 
1437 
1438         @DefinedBy(Api.LANGUAGE_MODEL)
1439         public ElementKind getKind() {
1440             apiComplete();
1441             long flags = flags();
1442             if ((flags & ANNOTATION) != 0)
1443                 return ElementKind.ANNOTATION_TYPE;
1444             else if ((flags & INTERFACE) != 0)
1445                 return ElementKind.INTERFACE;
1446             else if ((flags & ENUM) != 0)
1447                 return ElementKind.ENUM;
1448             else if ((flags & RECORD) != 0)
1449                 return ElementKind.RECORD;
1450             else
1451                 return ElementKind.CLASS;
1452         }
1453 
1454         @Override @DefinedBy(Api.LANGUAGE_MODEL)
1455         public Set<Modifier> getModifiers() {
1456             apiComplete();
1457             long flags = flags();
1458             return Flags.asModifierSet(flags & ~DEFAULT);
1459         }
1460 
1461         @Override @DefinedBy(Api.LANGUAGE_MODEL)
1462         public java.util.List<VariableElement> getStateComponents() {
1463             apiComplete();
1464             // Inital implementation
1465             return javax.lang.model.util.ElementFilter.stateComponentsIn(getEnclosedElements());
1466         }
1467 
1468         @DefinedBy(Api.LANGUAGE_MODEL)
1469         public NestingKind getNestingKind() {
1470             apiComplete();
1471             if (owner.kind == PCK)
1472                 return NestingKind.TOP_LEVEL;
1473             else if (name.isEmpty())
1474                 return NestingKind.ANONYMOUS;
1475             else if (owner.kind == MTH)
1476                 return NestingKind.LOCAL;
1477             else
1478                 return NestingKind.MEMBER;
1479         }
1480 
1481 
1482         @Override
1483         protected <A extends Annotation> Attribute.Compound getAttribute(final Class<A> annoType) {
1484 
1485             Attribute.Compound attrib = super.getAttribute(annoType);
1486 
1487             boolean inherited = annoType.isAnnotationPresent(Inherited.class);
1488             if (attrib != null || !inherited)
1489                 return attrib;
1490 
1491             // Search supertypes
1492             ClassSymbol superType = getSuperClassToSearchForAnnotations();
1493             return superType == null ? null
1494                                      : superType.getAttribute(annoType);
1495         }
1496 
1497 
1498 
1499 
1500         @DefinedBy(Api.LANGUAGE_MODEL)
1501         public <R, P> R accept(ElementVisitor<R, P> v, P p) {
1502             return v.visitType(this, p);
1503         }
1504 
1505         public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
1506             return v.visitClassSymbol(this, p);
1507         }
1508 
1509         public void markAbstractIfNeeded(Types types) {
1510             if (types.enter.getEnv(this) != null &&
1511                 (flags() & ENUM) != 0 && types.supertype(type).tsym == types.syms.enumSym &&
1512                 (flags() & (FINAL | ABSTRACT)) == 0) {
1513                 if (types.firstUnimplementedAbstract(this) != null)
1514                     // add the ABSTRACT flag to an enum
1515                     flags_field |= ABSTRACT;
1516             }
1517         }
1518 
1519         /**Resets the Symbol into the state good for next round of annotation processing.*/
1520         public void reset() {
1521             kind = TYP;
1522             erasure_field = null;
1523             members_field = null;
1524             flags_field = 0;
1525             if (type instanceof ClassType) {
1526                 ClassType t = (ClassType)type;
1527                 t.setEnclosingType(Type.noType);
1528                 t.rank_field = -1;
1529                 t.typarams_field = null;
1530                 t.allparams_field = null;
1531                 t.supertype_field = null;
1532                 t.interfaces_field = null;
1533                 t.all_interfaces_field = null;
1534             }
1535             clearAnnotationMetadata();
1536         }
1537 
1538         public void clearAnnotationMetadata() {
1539             metadata = null;
1540             annotationTypeMetadata = AnnotationTypeMetadata.notAnAnnotationType();
1541         }
1542 
1543         @Override
1544         public AnnotationTypeMetadata getAnnotationTypeMetadata() {
1545             return annotationTypeMetadata;
1546         }
1547 
1548         @Override
1549         public boolean isAnnotationType() {
1550             return (flags_field & Flags.ANNOTATION) != 0;
1551         }
1552 
1553         public void setAnnotationTypeMetadata(AnnotationTypeMetadata a) {
1554             Assert.checkNonNull(a);
1555             Assert.check(!annotationTypeMetadata.isMetadataForAnnotationType());
1556             this.annotationTypeMetadata = a;
1557         }
1558 
1559         @DefinedBy(Api.LANGUAGE_MODEL)
1560         public List<Type> getPermittedSubtypes() {
1561             return ((ClassType)type).permitted;
1562         }
1563     }
1564 
1565 
1566     /** A class for variable symbols
1567      */
1568     public static class VarSymbol extends Symbol implements VariableElement {
1569 
1570         /** The variable's declaration position.
1571          */
1572         public int pos = Position.NOPOS;
1573 
1574         /** The variable's address. Used for different purposes during
1575          *  flow analysis, translation and code generation.
1576          *  Flow analysis:
1577          *    If this is a blank final or local variable, its sequence number.
1578          *  Translation:
1579          *    If this is a private field, its access number.
1580          *  Code generation:
1581          *    If this is a local variable, its logical slot number.
1582          */
1583         public int adr = -1;
1584 
1585         public List<Pair<Accessors.Kind, MethodSymbol>> accessors = List.nil();
1586 
1587         /** Construct a variable symbol, given its flags, name, type and owner.
1588          */
1589         public VarSymbol(long flags, Name name, Type type, Symbol owner) {
1590             super(VAR, flags, name, type, owner);
1591         }
1592 
1593         @Override
1594         public int poolTag() {
1595             return ClassFile.CONSTANT_Fieldref;
1596         }
1597 
1598         public MethodHandleSymbol asMethodHandle(boolean getter) {
1599             return new MethodHandleSymbol(this, getter);
1600         }
1601 
1602         /** Clone this symbol with new owner.
1603          */
1604         public VarSymbol clone(Symbol newOwner) {
1605             VarSymbol v = new VarSymbol(flags_field, name, type, newOwner) {
1606                 @Override
1607                 public Symbol baseSymbol() {
1608                     return VarSymbol.this;
1609                 }
1610 
1611                 @Override
1612                 public Object poolKey(Types types) {
1613                     return new Pair<>(newOwner, baseSymbol());
1614                 }
1615             };
1616             v.pos = pos;
1617             v.adr = adr;
1618             v.data = data;
1619 //          System.out.println("clone " + v + " in " + newOwner);//DEBUG
1620             return v;
1621         }
1622 
1623         public String toString() {
1624             return name.toString();
1625         }
1626 
1627         public Symbol asMemberOf(Type site, Types types) {
1628             return new VarSymbol(flags_field, name, types.memberType(site, this), owner);
1629         }
1630 
1631         @Override
1632         public Type erasure(Types types) {
1633             if (erasure_field == null) {
1634                 erasure_field = types.erasure(type);
1635             }
1636             return erasure_field;
1637         }
1638 
1639         @DefinedBy(Api.LANGUAGE_MODEL)
1640         public ElementKind getKind() {
1641             long flags = flags();
1642             if ((flags & PARAMETER) != 0) {
1643                 if (isExceptionParameter())
1644                     return ElementKind.EXCEPTION_PARAMETER;
1645                 else
1646                     return ElementKind.PARAMETER;
1647             } else if ((flags & ENUM) != 0) {
1648                 return ElementKind.ENUM_CONSTANT;
1649             } else if (owner.kind == TYP || owner.kind == ERR) {
1650                 return ElementKind.FIELD;
1651             } else if (isResourceVariable()) {
1652                 return ElementKind.RESOURCE_VARIABLE;
1653             } else {
1654                 return ElementKind.LOCAL_VARIABLE;
1655             }
1656         }
1657 
1658         @DefinedBy(Api.LANGUAGE_MODEL)
1659         public <R, P> R accept(ElementVisitor<R, P> v, P p) {
1660             return v.visitVariable(this, p);
1661         }
1662 
1663         @DefinedBy(Api.LANGUAGE_MODEL)
1664         public Object getConstantValue() { // Mirror API
1665             return Constants.decode(getConstValue(), type);
1666         }
1667 
1668         public void setLazyConstValue(final Env<AttrContext> env,
1669                                       final Attr attr,
1670                                       final JCVariableDecl variable)
1671         {
1672             setData((Callable<Object>)() -> attr.attribLazyConstantValue(env, variable, type));
1673         }
1674 
1675         /**
1676          * The variable's constant value, if this is a constant.
1677          * Before the constant value is evaluated, it points to an
1678          * initializer environment.  If this is not a constant, it can
1679          * be used for other stuff.
1680          */
1681         private Object data;
1682 
1683         public boolean isExceptionParameter() {
1684             return data == ElementKind.EXCEPTION_PARAMETER;
1685         }
1686 
1687         public boolean isResourceVariable() {
1688             return data == ElementKind.RESOURCE_VARIABLE;
1689         }
1690 
1691         public Object getConstValue() {
1692             // TODO: Consider if getConstValue and getConstantValue can be collapsed
1693             if (data == ElementKind.EXCEPTION_PARAMETER ||
1694                 data == ElementKind.RESOURCE_VARIABLE) {
1695                 return null;
1696             } else if (data instanceof Callable<?>) {
1697                 // In this case, this is a final variable, with an as
1698                 // yet unevaluated initializer.
1699                 Callable<?> eval = (Callable<?>)data;
1700                 data = null; // to make sure we don't evaluate this twice.
1701                 try {
1702                     data = eval.call();
1703                 } catch (Exception ex) {
1704                     throw new AssertionError(ex);
1705                 }
1706             }
1707             return data;
1708         }
1709 
1710         public void setData(Object data) {
1711             Assert.check(!(data instanceof Env<?>), this);
1712             this.data = data;
1713         }
1714 
1715         public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
1716             return v.visitVarSymbol(this, p);
1717         }
1718     }
1719 
1720     public static class ParamSymbol extends VarSymbol {
1721         public ParamSymbol(long flags, Name name, Type type, Symbol owner) {
1722             super(flags, name, type, owner);
1723         }
1724 
1725         @Override
1726         public Name getSimpleName() {
1727             if ((flags_field & NAME_FILLED) == 0) {
1728                 flags_field |= NAME_FILLED;
1729                 Symbol rootPack = this;
1730                 while (rootPack != null && !(rootPack instanceof RootPackageSymbol)) {
1731                     rootPack = rootPack.owner;
1732                 }
1733                 if (rootPack != null) {
1734                     Name inferredName =
1735                             ((RootPackageSymbol) rootPack).missingInfoHandler.getParameterName(this);
1736                     if (inferredName != null) {
1737                         this.name = inferredName;
1738                     }
1739                 }
1740             }
1741             return super.getSimpleName();
1742         }
1743 
1744     }
1745 
1746     /** A class for method symbols.
1747      */
1748     public static class MethodSymbol extends Symbol implements ExecutableElement {
1749 
1750         /** The code of the method. */
1751         public Code code = null;
1752 
1753         /** The extra (synthetic/mandated) parameters of the method. */
1754         public List<VarSymbol> extraParams = List.nil();
1755 
1756         /** The captured local variables in an anonymous class */
1757         public List<VarSymbol> capturedLocals = List.nil();
1758 
1759         /** The parameters of the method. */
1760         public List<VarSymbol> params = null;
1761 
1762         /** For an annotation type element, its default value if any.
1763          *  The value is null if none appeared in the method
1764          *  declaration.
1765          */
1766         public Attribute defaultValue = null;
1767 
1768         /** Construct a method symbol, given its flags, name, type and owner.
1769          */
1770         public MethodSymbol(long flags, Name name, Type type, Symbol owner) {
1771             super(MTH, flags, name, type, owner);
1772             if (owner.type.hasTag(TYPEVAR)) Assert.error(owner + "." + name);
1773         }
1774 
1775         /** Clone this symbol with new owner.
1776          */
1777         public MethodSymbol clone(Symbol newOwner) {
1778             MethodSymbol m = new MethodSymbol(flags_field, name, type, newOwner) {
1779                 @Override
1780                 public Symbol baseSymbol() {
1781                     return MethodSymbol.this;
1782                 }
1783 
1784                 @Override
1785                 public Object poolKey(Types types) {
1786                     return new Pair<>(newOwner, baseSymbol());
1787                 }
1788             };
1789             m.code = code;
1790             return m;
1791         }
1792 
1793         @Override @DefinedBy(Api.LANGUAGE_MODEL)
1794         public Set<Modifier> getModifiers() {
1795             long flags = flags();
1796             return Flags.asModifierSet((flags & DEFAULT) != 0 ? flags & ~ABSTRACT : flags);
1797         }
1798 
1799         /** The Java source which this symbol represents.
1800          */
1801         public String toString() {
1802             if ((flags() & BLOCK) != 0) {
1803                 return owner.name.toString();
1804             } else {
1805                 String s = (name == name.table.names.init)
1806                     ? owner.name.toString()
1807                     : name.toString();
1808                 if (type != null) {
1809                     if (type.hasTag(FORALL))
1810                         s = "<" + ((ForAll)type).getTypeArguments() + ">" + s;
1811                     s += "(" + type.argtypes((flags() & VARARGS) != 0) + ")";
1812                 }
1813                 return s;
1814             }
1815         }
1816 
1817         @Override
1818         public int poolTag() {
1819             return owner.isInterface() ?
1820                     ClassFile.CONSTANT_InterfaceMethodref : ClassFile.CONSTANT_Methodref;
1821         }
1822 
1823         public boolean isDynamic() {
1824             return false;
1825         }
1826 
1827         public boolean isHandle() {
1828             return false;
1829         }
1830 
1831 
1832         public MethodHandleSymbol asHandle() {
1833             return new MethodHandleSymbol(this);
1834         }
1835 
1836         /** find a symbol that this (proxy method) symbol implements.
1837          *  @param    c       The class whose members are searched for
1838          *                    implementations
1839          */
1840         public Symbol implemented(TypeSymbol c, Types types) {
1841             Symbol impl = null;
1842             for (List<Type> is = types.interfaces(c.type);
1843                  impl == null && is.nonEmpty();
1844                  is = is.tail) {
1845                 TypeSymbol i = is.head.tsym;
1846                 impl = implementedIn(i, types);
1847                 if (impl == null)
1848                     impl = implemented(i, types);
1849             }
1850             return impl;
1851         }
1852 
1853         public Symbol implementedIn(TypeSymbol c, Types types) {
1854             Symbol impl = null;
1855             for (Symbol sym : c.members().getSymbolsByName(name)) {
1856                 if (this.overrides(sym, (TypeSymbol)owner, types, true) &&
1857                     // FIXME: I suspect the following requires a
1858                     // subst() for a parametric return type.
1859                     types.isSameType(type.getReturnType(),
1860                                      types.memberType(owner.type, sym).getReturnType())) {
1861                     impl = sym;
1862                 }
1863             }
1864             return impl;
1865         }
1866 
1867         /** Will the erasure of this method be considered by the VM to
1868          *  override the erasure of the other when seen from class `origin'?
1869          */
1870         public boolean binaryOverrides(Symbol _other, TypeSymbol origin, Types types) {
1871             if (isConstructor() || _other.kind != MTH) return false;
1872 
1873             if (this == _other) return true;
1874             MethodSymbol other = (MethodSymbol)_other;
1875 
1876             // check for a direct implementation
1877             if (other.isOverridableIn((TypeSymbol)owner) &&
1878                 types.asSuper(owner.type, other.owner) != null &&
1879                 types.isSameType(erasure(types), other.erasure(types)))
1880                 return true;
1881 
1882             // check for an inherited implementation
1883             return
1884                 (flags() & ABSTRACT) == 0 &&
1885                 other.isOverridableIn(origin) &&
1886                 this.isMemberOf(origin, types) &&
1887                 types.isSameType(erasure(types), other.erasure(types));
1888         }
1889 
1890         /** The implementation of this (abstract) symbol in class origin,
1891          *  from the VM's point of view, null if method does not have an
1892          *  implementation in class.
1893          *  @param origin   The class of which the implementation is a member.
1894          */
1895         public MethodSymbol binaryImplementation(ClassSymbol origin, Types types) {
1896             for (TypeSymbol c = origin; c != null; c = types.supertype(c.type).tsym) {
1897                 for (Symbol sym : c.members().getSymbolsByName(name)) {
1898                     if (sym.kind == MTH &&
1899                         ((MethodSymbol)sym).binaryOverrides(this, origin, types))
1900                         return (MethodSymbol)sym;
1901                 }
1902             }
1903             return null;
1904         }
1905 
1906         /** Does this symbol override `other' symbol, when both are seen as
1907          *  members of class `origin'?  It is assumed that _other is a member
1908          *  of origin.
1909          *
1910          *  It is assumed that both symbols have the same name.  The static
1911          *  modifier is ignored for this test.
1912          *
1913          *  A quirk in the works is that if the receiver is a method symbol for
1914          *  an inherited abstract method we answer false summarily all else being
1915          *  immaterial. Abstract "own" methods (i.e `this' is a direct member of
1916          *  origin) don't get rejected as summarily and are put to test against the
1917          *  suitable criteria.
1918          *
1919          *  See JLS 8.4.6.1 (without transitivity) and 8.4.6.4
1920          */
1921         public boolean overrides(Symbol _other, TypeSymbol origin, Types types, boolean checkResult) {
1922             return overrides(_other, origin, types, checkResult, true);
1923         }
1924 
1925         /** Does this symbol override `other' symbol, when both are seen as
1926          *  members of class `origin'?  It is assumed that _other is a member
1927          *  of origin.
1928          *
1929          *  Caveat: If `this' is an abstract inherited member of origin, it is
1930          *  deemed to override `other' only when `requireConcreteIfInherited'
1931          *  is false.
1932          *
1933          *  It is assumed that both symbols have the same name.  The static
1934          *  modifier is ignored for this test.
1935          *
1936          *  See JLS 8.4.6.1 (without transitivity) and 8.4.6.4
1937          */
1938         public boolean overrides(Symbol _other, TypeSymbol origin, Types types, boolean checkResult,
1939                                             boolean requireConcreteIfInherited) {
1940             if (isConstructor() || _other.kind != MTH) return false;
1941 
1942             if (this == _other) return true;
1943             MethodSymbol other = (MethodSymbol)_other;
1944 
1945             // check for a direct implementation
1946             if (other.isOverridableIn((TypeSymbol)owner) &&
1947                 types.asSuper(owner.type, other.owner) != null) {
1948                 Type mt = types.memberType(owner.type, this);
1949                 Type ot = types.memberType(owner.type, other);
1950                 if (types.isSubSignature(mt, ot)) {
1951                     if (!checkResult)
1952                         return true;
1953                     if (types.returnTypeSubstitutable(mt, ot))
1954                         return true;
1955                 }
1956             }
1957 
1958             // check for an inherited implementation
1959             if (((flags() & ABSTRACT) != 0 && requireConcreteIfInherited) ||
1960                     ((other.flags() & ABSTRACT) == 0 && (other.flags() & DEFAULT) == 0) ||
1961                     !other.isOverridableIn(origin) ||
1962                     !this.isMemberOf(origin, types))
1963                 return false;
1964 
1965             // assert types.asSuper(origin.type, other.owner) != null;
1966             Type mt = types.memberType(origin.type, this);
1967             Type ot = types.memberType(origin.type, other);
1968             return
1969                 types.isSubSignature(mt, ot) &&
1970                 (!checkResult || types.resultSubtype(mt, ot, types.noWarnings));
1971         }
1972 
1973         private boolean isOverridableIn(TypeSymbol origin) {
1974             // JLS 8.4.6.1
1975             switch ((int)(flags_field & Flags.AccessFlags)) {
1976             case Flags.PRIVATE:
1977                 return false;
1978             case Flags.PUBLIC:
1979                 return !this.owner.isInterface() ||
1980                         (flags_field & STATIC) == 0;
1981             case Flags.PROTECTED:
1982                 return (origin.flags() & INTERFACE) == 0;
1983             case 0:
1984                 // for package private: can only override in the same
1985                 // package
1986                 return
1987                     this.packge() == origin.packge() &&
1988                     (origin.flags() & INTERFACE) == 0;
1989             default:
1990                 return false;
1991             }
1992         }
1993 
1994         @Override
1995         public boolean isInheritedIn(Symbol clazz, Types types) {
1996             switch ((int)(flags_field & Flags.AccessFlags)) {
1997                 case PUBLIC:
1998                     return !this.owner.isInterface() ||
1999                             clazz == owner ||
2000                             (flags_field & STATIC) == 0;
2001                 default:
2002                     return super.isInheritedIn(clazz, types);
2003             }
2004         }
2005 
2006         public boolean isLambdaMethod() {
2007             return (flags() & LAMBDA_METHOD) == LAMBDA_METHOD;
2008         }
2009 
2010         /** override this method to point to the original enclosing method if this method symbol represents a synthetic
2011          *  lambda method
2012          */
2013         public MethodSymbol originalEnclosingMethod() {
2014             return this;
2015         }
2016 
2017         /** The implementation of this (abstract) symbol in class origin;
2018          *  null if none exists. Synthetic methods are not considered
2019          *  as possible implementations.
2020          */
2021         public MethodSymbol implementation(TypeSymbol origin, Types types, boolean checkResult) {
2022             return implementation(origin, types, checkResult, implementation_filter);
2023         }
2024         // where
2025             public static final Filter<Symbol> implementation_filter = s ->
2026                     s.kind == MTH && (s.flags() & SYNTHETIC) == 0;
2027 
2028         public MethodSymbol implementation(TypeSymbol origin, Types types, boolean checkResult, Filter<Symbol> implFilter) {
2029             MethodSymbol res = types.implementation(this, origin, checkResult, implFilter);
2030             if (res != null)
2031                 return res;
2032             // if origin is derived from a raw type, we might have missed
2033             // an implementation because we do not know enough about instantiations.
2034             // in this case continue with the supertype as origin.
2035             if (types.isDerivedRaw(origin.type) && !origin.isInterface())
2036                 return implementation(types.supertype(origin.type).tsym, types, checkResult);
2037             else
2038                 return null;
2039         }
2040 
2041         public List<VarSymbol> params() {
2042             owner.complete();
2043             if (params == null) {
2044                 ListBuffer<VarSymbol> newParams = new ListBuffer<>();
2045                 int i = 0;
2046                 for (Type t : type.getParameterTypes()) {
2047                     Name paramName = name.table.fromString("arg" + i);
2048                     VarSymbol param = new VarSymbol(PARAMETER, paramName, t, this);
2049                     newParams.append(param);
2050                     i++;
2051                 }
2052                 params = newParams.toList();
2053             }
2054             Assert.checkNonNull(params);
2055             return params;
2056         }
2057 
2058         public Symbol asMemberOf(Type site, Types types) {
2059             return new MethodSymbol(flags_field, name, types.memberType(site, this), owner);
2060         }
2061 
2062         @DefinedBy(Api.LANGUAGE_MODEL)
2063         public ElementKind getKind() {
2064             if (name == name.table.names.init)
2065                 return ElementKind.CONSTRUCTOR;
2066             else if (name == name.table.names.clinit)
2067                 return ElementKind.STATIC_INIT;
2068             else if ((flags() & BLOCK) != 0)
2069                 return isStatic() ? ElementKind.STATIC_INIT : ElementKind.INSTANCE_INIT;
2070             else
2071                 return ElementKind.METHOD;
2072         }
2073 
2074         public boolean isStaticOrInstanceInit() {
2075             return getKind() == ElementKind.STATIC_INIT ||
2076                     getKind() == ElementKind.INSTANCE_INIT;
2077         }
2078 
2079         @DefinedBy(Api.LANGUAGE_MODEL)
2080         public Attribute getDefaultValue() {
2081             return defaultValue;
2082         }
2083 
2084         @DefinedBy(Api.LANGUAGE_MODEL)
2085         public List<VarSymbol> getParameters() {
2086             return params();
2087         }
2088 
2089         @DefinedBy(Api.LANGUAGE_MODEL)
2090         public boolean isVarArgs() {
2091             return (flags() & VARARGS) != 0;
2092         }
2093 
2094         @DefinedBy(Api.LANGUAGE_MODEL)
2095         public boolean isDefault() {
2096             return (flags() & DEFAULT) != 0;
2097         }
2098 
2099         @DefinedBy(Api.LANGUAGE_MODEL)
2100         public <R, P> R accept(ElementVisitor<R, P> v, P p) {
2101             return v.visitExecutable(this, p);
2102         }
2103 
2104         public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
2105             return v.visitMethodSymbol(this, p);
2106         }
2107 
2108         @DefinedBy(Api.LANGUAGE_MODEL)
2109         public Type getReceiverType() {
2110             Type result = asType().getReceiverType();
2111             return (result == null) ? Type.noType : result;
2112         }
2113 
2114         @DefinedBy(Api.LANGUAGE_MODEL)
2115         public Type getReturnType() {
2116             return asType().getReturnType();
2117         }
2118 
2119         @DefinedBy(Api.LANGUAGE_MODEL)
2120         public List<Type> getThrownTypes() {
2121             return asType().getThrownTypes();
2122         }
2123     }
2124 
2125     /** A class for invokedynamic method calls.
2126      */
2127     public static class DynamicMethodSymbol extends MethodSymbol implements Dynamic {
2128 
2129         public LoadableConstant[] staticArgs;
2130         public MethodHandleSymbol bsm;
2131 
2132         public DynamicMethodSymbol(Name name, Symbol owner, MethodHandleSymbol bsm, Type type, LoadableConstant[] staticArgs) {
2133             super(0, name, type, owner);
2134             this.bsm = bsm;
2135             this.staticArgs = staticArgs;
2136         }
2137 
2138         @Override
2139         public boolean isDynamic() {
2140             return true;
2141         }
2142 
2143         @Override
2144         public LoadableConstant[] staticArgs() {
2145             return staticArgs;
2146         }
2147 
2148         @Override
2149         public MethodHandleSymbol bootstrapMethod() {
2150             return bsm;
2151         }
2152 
2153         @Override
2154         public int poolTag() {
2155             return ClassFile.CONSTANT_InvokeDynamic;
2156         }
2157 
2158         @Override
2159         public Type dynamicType() {
2160             return type;
2161         }
2162     }
2163 
2164     /** A class for condy.
2165      */
2166     public static class DynamicVarSymbol extends VarSymbol implements Dynamic, LoadableConstant {
2167         public LoadableConstant[] staticArgs;
2168         public MethodHandleSymbol bsm;
2169 
2170         public DynamicVarSymbol(Name name, Symbol owner, MethodHandleSymbol bsm, Type type, LoadableConstant[] staticArgs) {
2171             super(0, name, type, owner);
2172             this.bsm = bsm;
2173             this.staticArgs = staticArgs;
2174         }
2175 
2176         @Override
2177         public boolean isDynamic() {
2178             return true;
2179         }
2180 
2181         @Override
2182         public PoolConstant dynamicType() {
2183             return type;
2184         }
2185 
2186         @Override
2187         public LoadableConstant[] staticArgs() {
2188             return staticArgs;
2189         }
2190 
2191         @Override
2192         public LoadableConstant bootstrapMethod() {
2193             return bsm;
2194         }
2195 
2196         @Override
2197         public int poolTag() {
2198             return ClassFile.CONSTANT_Dynamic;
2199         }
2200     }
2201 
2202     /** A class for method handles.
2203      */
2204     public static class MethodHandleSymbol extends MethodSymbol implements LoadableConstant {
2205 
2206         private Symbol refSym;
2207         // in case the simbol is a variable
2208         private boolean getter;
2209 
2210         public MethodHandleSymbol(Symbol msym) {
2211             this(msym, false);
2212         }
2213 
2214         public MethodHandleSymbol(Symbol msym, boolean getter) {
2215             super(msym.flags_field, msym.name, msym.type, msym.owner);
2216             this.refSym = msym;
2217             this.getter = getter;
2218         }
2219 
2220         /**
2221          * Returns the kind associated with this method handle.
2222          */
2223         public int referenceKind() {
2224             if (refSym.kind == VAR) {
2225                 return getter ?
2226                         refSym.isStatic() ? ClassFile.REF_getStatic : ClassFile.REF_getField :
2227                         refSym.isStatic() ? ClassFile.REF_putStatic : ClassFile.REF_putField;
2228             } else {
2229                 if (refSym.isConstructor()) {
2230                     return ClassFile.REF_newInvokeSpecial;
2231                 } else {
2232                     if (refSym.isStatic()) {
2233                         return ClassFile.REF_invokeStatic;
2234                     } else if ((refSym.flags() & PRIVATE) != 0) {
2235                         return ClassFile.REF_invokeSpecial;
2236                     } else if (refSym.enclClass().isInterface()) {
2237                         return ClassFile.REF_invokeInterface;
2238                     } else {
2239                         return ClassFile.REF_invokeVirtual;
2240                     }
2241                 }
2242             }
2243         }
2244 
2245         @Override
2246         public int poolTag() {
2247             return ClassFile.CONSTANT_MethodHandle;
2248         }
2249 
2250         @Override
2251         public Object poolKey(Types types) {
2252             return new Pair<>(baseSymbol(), referenceKind());
2253         }
2254 
2255         @Override
2256         public MethodHandleSymbol asHandle() {
2257             return this;
2258         }
2259 
2260         @Override
2261         public Symbol baseSymbol() {
2262             return refSym;
2263         }
2264 
2265 
2266         @Override
2267         public boolean isHandle() {
2268             return true;
2269         }
2270     }
2271 
2272     /** A class for predefined operators.
2273      */
2274     public static class OperatorSymbol extends MethodSymbol {
2275 
2276         public int opcode;
2277         private int accessCode = Integer.MIN_VALUE;
2278 
2279         public OperatorSymbol(Name name, Type type, int opcode, Symbol owner) {
2280             super(PUBLIC | STATIC, name, type, owner);
2281             this.opcode = opcode;
2282         }
2283 
2284         @Override
2285         public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
2286             return v.visitOperatorSymbol(this, p);
2287         }
2288 
2289         public int getAccessCode(Tag tag) {
2290             if (accessCode != Integer.MIN_VALUE && !tag.isIncOrDecUnaryOp()) {
2291                 return accessCode;
2292             }
2293             accessCode = AccessCode.from(tag, opcode);
2294             return accessCode;
2295         }
2296 
2297         /** Access codes for dereferencing, assignment,
2298          *  and pre/post increment/decrement.
2299 
2300          *  All access codes for accesses to the current class are even.
2301          *  If a member of the superclass should be accessed instead (because
2302          *  access was via a qualified super), add one to the corresponding code
2303          *  for the current class, making the number odd.
2304          *  This numbering scheme is used by the backend to decide whether
2305          *  to issue an invokevirtual or invokespecial call.
2306          *
2307          *  @see Gen#visitSelect(JCFieldAccess tree)
2308          */
2309         public enum AccessCode {
2310             UNKNOWN(-1, Tag.NO_TAG),
2311             DEREF(0, Tag.NO_TAG),
2312             ASSIGN(2, Tag.ASSIGN),
2313             PREINC(4, Tag.PREINC),
2314             PREDEC(6, Tag.PREDEC),
2315             POSTINC(8, Tag.POSTINC),
2316             POSTDEC(10, Tag.POSTDEC),
2317             FIRSTASGOP(12, Tag.NO_TAG);
2318 
2319             public final int code;
2320             public final Tag tag;
2321             public static final int numberOfAccessCodes = (lushrl - ishll + lxor + 2 - iadd) * 2 + FIRSTASGOP.code + 2;
2322 
2323             AccessCode(int code, Tag tag) {
2324                 this.code = code;
2325                 this.tag = tag;
2326             }
2327 
2328             static public AccessCode getFromCode(int code) {
2329                 for (AccessCode aCodes : AccessCode.values()) {
2330                     if (aCodes.code == code) {
2331                         return aCodes;
2332                     }
2333                 }
2334                 return UNKNOWN;
2335             }
2336 
2337             static int from(Tag tag, int opcode) {
2338                 /** Map bytecode of binary operation to access code of corresponding
2339                 *  assignment operation. This is always an even number.
2340                 */
2341                 switch (tag) {
2342                     case PREINC:
2343                         return AccessCode.PREINC.code;
2344                     case PREDEC:
2345                         return AccessCode.PREDEC.code;
2346                     case POSTINC:
2347                         return AccessCode.POSTINC.code;
2348                     case POSTDEC:
2349                         return AccessCode.POSTDEC.code;
2350                 }
2351                 if (iadd <= opcode && opcode <= lxor) {
2352                     return (opcode - iadd) * 2 + FIRSTASGOP.code;
2353                 } else if (opcode == string_add) {
2354                     return (lxor + 1 - iadd) * 2 + FIRSTASGOP.code;
2355                 } else if (ishll <= opcode && opcode <= lushrl) {
2356                     return (opcode - ishll + lxor + 2 - iadd) * 2 + FIRSTASGOP.code;
2357                 }
2358                 return -1;
2359             }
2360         }
2361     }
2362 
2363     /** Symbol completer interface.
2364      */
2365     public static interface Completer {
2366 
2367         /** Dummy completer to be used when the symbol has been completed or
2368          * does not need completion.
2369          */
2370         public final static Completer NULL_COMPLETER = new Completer() {
2371             public void complete(Symbol sym) { }
2372             public boolean isTerminal() { return true; }
2373         };
2374 
2375         void complete(Symbol sym) throws CompletionFailure;
2376 
2377         /** Returns true if this completer is <em>terminal</em>. A terminal
2378          * completer is used as a place holder when the symbol is completed.
2379          * Calling complete on a terminal completer will not affect the symbol.
2380          *
2381          * The dummy NULL_COMPLETER and the GraphDependencies completer are
2382          * examples of terminal completers.
2383          *
2384          * @return true iff this completer is terminal
2385          */
2386         default boolean isTerminal() {
2387             return false;
2388         }
2389     }
2390 
2391     public static class CompletionFailure extends RuntimeException {
2392         private static final long serialVersionUID = 0;
2393         public final DeferredCompletionFailureHandler dcfh;
2394         public Symbol sym;
2395 
2396         /** A diagnostic object describing the failure
2397          */
2398         private JCDiagnostic diag;
2399 
2400         private Supplier<JCDiagnostic> diagSupplier;
2401 
2402         public CompletionFailure(Symbol sym, Supplier<JCDiagnostic> diagSupplier, DeferredCompletionFailureHandler dcfh) {
2403             this.dcfh = dcfh;
2404             this.sym = sym;
2405             this.diagSupplier = diagSupplier;
2406 //          this.printStackTrace();//DEBUG
2407         }
2408 
2409         public JCDiagnostic getDiagnostic() {
2410             if (diag == null && diagSupplier != null) {
2411                 diag = diagSupplier.get();
2412             }
2413             return diag;
2414         }
2415 
2416         @Override
2417         public String getMessage() {
2418             return getDiagnostic().getMessage(null);
2419         }
2420 
2421         public JCDiagnostic getDetailValue() {
2422             return getDiagnostic();
2423         }
2424 
2425         @Override
2426         public CompletionFailure initCause(Throwable cause) {
2427             super.initCause(cause);
2428             return this;
2429         }
2430 
2431         public void resetDiagnostic(Supplier<JCDiagnostic> diagSupplier) {
2432             this.diagSupplier = diagSupplier;
2433             this.diag = null;
2434         }
2435 
2436     }
2437 
2438     /**
2439      * A visitor for symbols.  A visitor is used to implement operations
2440      * (or relations) on symbols.  Most common operations on types are
2441      * binary relations and this interface is designed for binary
2442      * relations, that is, operations on the form
2443      * Symbol&nbsp;&times;&nbsp;P&nbsp;&rarr;&nbsp;R.
2444      * <!-- In plain text: Type x P -> R -->
2445      *
2446      * @param <R> the return type of the operation implemented by this
2447      * visitor; use Void if no return type is needed.
2448      * @param <P> the type of the second argument (the first being the
2449      * symbol itself) of the operation implemented by this visitor; use
2450      * Void if a second argument is not needed.
2451      */
2452     public interface Visitor<R,P> {
2453         R visitClassSymbol(ClassSymbol s, P arg);
2454         R visitMethodSymbol(MethodSymbol s, P arg);
2455         R visitPackageSymbol(PackageSymbol s, P arg);
2456         R visitOperatorSymbol(OperatorSymbol s, P arg);
2457         R visitVarSymbol(VarSymbol s, P arg);
2458         R visitTypeSymbol(TypeSymbol s, P arg);
2459         R visitSymbol(Symbol s, P arg);
2460     }
2461 }