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