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