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