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