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