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