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