1 /*
   2  * Copyright 1999-2008 Sun Microsystems, Inc.  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.  Sun designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  22  * CA 95054 USA or visit www.sun.com if you need additional information or
  23  * have any questions.
  24  */
  25 
  26 package com.sun.tools.javac.code;
  27 
  28 import java.util.Set;
  29 import java.util.concurrent.Callable;
  30 import javax.lang.model.element.*;
  31 import javax.tools.JavaFileObject;
  32 
  33 import com.sun.tools.javac.util.*;
  34 import com.sun.tools.javac.util.Name;
  35 import com.sun.tools.javac.code.Type.*;
  36 import com.sun.tools.javac.comp.Attr;
  37 import com.sun.tools.javac.comp.AttrContext;
  38 import com.sun.tools.javac.comp.Env;
  39 import com.sun.tools.javac.jvm.*;
  40 import com.sun.tools.javac.model.*;
  41 import com.sun.tools.javac.tree.JCTree;
  42 
  43 import static com.sun.tools.javac.code.Flags.*;
  44 import static com.sun.tools.javac.code.Kinds.*;
  45 import static com.sun.tools.javac.code.TypeTags.*;
  46 
  47 /** Root class for Java symbols. It contains subclasses
  48  *  for specific sorts of symbols, such as variables, methods and operators,
  49  *  types, packages. Each subclass is represented as a static inner class
  50  *  inside Symbol.
  51  *
  52  *  <p><b>This is NOT part of any API supported by Sun Microsystems.  If
  53  *  you write code that depends on this, you do so at your own risk.
  54  *  This code and its internal interfaces are subject to change or
  55  *  deletion without notice.</b>
  56  */
  57 public abstract class Symbol implements Element {
  58     // public Throwable debug = new Throwable();
  59 
  60     /** The kind of this symbol.
  61      *  @see Kinds
  62      */
  63     public int kind;
  64 
  65     /** The flags of this symbol.
  66      */
  67     public long flags_field;
  68 
  69     /** An accessor method for the flags of this symbol.
  70      *  Flags of class symbols should be accessed through the accessor
  71      *  method to make sure that the class symbol is loaded.
  72      */
  73     public long flags() { return flags_field; }
  74 
  75     /** The attributes of this symbol.
  76      */
  77     public List<Attribute.Compound> attributes_field;
  78 
  79     /** An accessor method for the attributes of this symbol.
  80      *  Attributes of class symbols should be accessed through the accessor
  81      *  method to make sure that the class symbol is loaded.
  82      */
  83     public List<Attribute.Compound> getAnnotationMirrors() {
  84         assert attributes_field != null;
  85         return attributes_field;
  86     }
  87 
  88     /** Fetch a particular annotation from a symbol. */
  89     public Attribute.Compound attribute(Symbol anno) {
  90         for (Attribute.Compound a : getAnnotationMirrors())
  91             if (a.type.tsym == anno) return a;
  92         return null;
  93     }
  94 
  95     /** The name of this symbol in Utf8 representation.
  96      */
  97     public Name name;
  98 
  99     /** The type of this symbol.
 100      */
 101     public Type type;
 102 
 103     /** The type annotations targeted to a tree directly owned by this symbol
 104      */
 105     // type annotations are stored here for two purposes:
 106     //  - convenient location to store annotations for generation after erasure
 107     //  - a private interface for accessing type annotations parsed from
 108     //    classfiles
 109     //  the field is populated for the following declaration only
 110     //  class, field, variable and type parameters
 111     //
 112     public List<Attribute.TypeCompound> typeAnnotations;
 113 
 114     /** The owner of this symbol.
 115      */
 116     public Symbol owner;
 117 
 118     /** The completer of this symbol.
 119      */
 120     public Completer completer;
 121 
 122     /** A cache for the type erasure of this symbol.
 123      */
 124     public Type erasure_field;
 125 
 126     /** Construct a symbol with given kind, flags, name, type and owner.
 127      */
 128     public Symbol(int kind, long flags, Name name, Type type, Symbol owner) {
 129         this.kind = kind;
 130         this.flags_field = flags;
 131         this.type = type;
 132         this.owner = owner;
 133         this.completer = null;
 134         this.erasure_field = null;
 135         this.attributes_field = List.nil();
 136         this.typeAnnotations = List.nil();
 137         this.name = name;
 138     }
 139 
 140     /** Clone this symbol with new owner.
 141      *  Legal only for fields and methods.
 142      */
 143     public Symbol clone(Symbol newOwner) {
 144         throw new AssertionError();
 145     }
 146 
 147     public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
 148         return v.visitSymbol(this, p);
 149     }
 150 
 151     /** The Java source which this symbol represents.
 152      *  A description of this symbol; overrides Object.
 153      */
 154     public String toString() {
 155         return name.toString();
 156     }
 157 
 158     /** A Java source description of the location of this symbol; used for
 159      *  error reporting.
 160      *
 161      * @return null if the symbol is a package or a toplevel class defined in
 162      * the default package; otherwise, the owner symbol is returned
 163      */
 164     public Symbol location() {
 165         if (owner.name == null || (owner.name.isEmpty() && owner.kind != PCK && owner.kind != TYP)) {
 166             return null;
 167         }
 168         return owner;
 169     }
 170 
 171     public Symbol location(Type site, Types types) {
 172         if (owner.name == null || owner.name.isEmpty()) {
 173             return location();
 174         }
 175         if (owner.type.tag == CLASS) {
 176             Type ownertype = types.asOuterSuper(site, owner);
 177             if (ownertype != null) return ownertype.tsym;
 178         }
 179         return owner;
 180     }
 181 
 182     /** The symbol's erased type.
 183      */
 184     public Type erasure(Types types) {
 185         if (erasure_field == null)
 186             erasure_field = types.erasure(type);
 187         return erasure_field;
 188     }
 189 
 190     /** The external type of a symbol. This is the symbol's erased type
 191      *  except for constructors of inner classes which get the enclosing
 192      *  instance class added as first argument.
 193      */
 194     public Type externalType(Types types) {
 195         Type t = erasure(types);
 196         if (name == name.table.names.init && owner.hasOuterInstance()) {
 197             Type outerThisType = types.erasure(owner.type.getEnclosingType());
 198             return new MethodType(t.getParameterTypes().prepend(outerThisType),
 199                                   t.getReturnType(),
 200                                   t.getThrownTypes(),
 201                                   t.tsym);
 202         } else {
 203             return t;
 204         }
 205     }
 206 
 207     public boolean isStatic() {
 208         return
 209             (flags() & STATIC) != 0 ||
 210             (owner.flags() & INTERFACE) != 0 && kind != MTH;
 211     }
 212 
 213     public boolean isInterface() {
 214         return (flags() & INTERFACE) != 0;
 215     }
 216 
 217     /** Is this symbol declared (directly or indirectly) local
 218      *  to a method or variable initializer?
 219      *  Also includes fields of inner classes which are in
 220      *  turn local to a method or variable initializer.
 221      */
 222     public boolean isLocal() {
 223         return
 224             (owner.kind & (VAR | MTH)) != 0 ||
 225             (owner.kind == TYP && owner.isLocal());
 226     }
 227 
 228     /** Is this symbol a constructor?
 229      */
 230     public boolean isConstructor() {
 231         return name == name.table.names.init;
 232     }
 233 
 234     /** The fully qualified name of this symbol.
 235      *  This is the same as the symbol's name except for class symbols,
 236      *  which are handled separately.
 237      */
 238     public Name getQualifiedName() {
 239         return name;
 240     }
 241 
 242     /** The fully qualified name of this symbol after converting to flat
 243      *  representation. This is the same as the symbol's name except for
 244      *  class symbols, which are handled separately.
 245      */
 246     public Name flatName() {
 247         return getQualifiedName();
 248     }
 249 
 250     /** If this is a class or package, its members, otherwise null.
 251      */
 252     public Scope members() {
 253         return null;
 254     }
 255 
 256     /** A class is an inner class if it it has an enclosing instance class.
 257      */
 258     public boolean isInner() {
 259         return type.getEnclosingType().tag == CLASS;
 260     }
 261 
 262     /** An inner class has an outer instance if it is not an interface
 263      *  it has an enclosing instance class which might be referenced from the class.
 264      *  Nested classes can see instance members of their enclosing class.
 265      *  Their constructors carry an additional this$n parameter, inserted
 266      *  implicitly by the compiler.
 267      *
 268      *  @see #isInner
 269      */
 270     public boolean hasOuterInstance() {
 271         return
 272             type.getEnclosingType().tag == CLASS && (flags() & (INTERFACE | NOOUTERTHIS)) == 0;
 273     }
 274 
 275     /** The closest enclosing class of this symbol's declaration.
 276      */
 277     public ClassSymbol enclClass() {
 278         Symbol c = this;
 279         while (c != null &&
 280                ((c.kind & TYP) == 0 || c.type.tag != CLASS)) {
 281             c = c.owner;
 282         }
 283         return (ClassSymbol)c;
 284     }
 285 
 286     /** The outermost class which indirectly owns this symbol.
 287      */
 288     public ClassSymbol outermostClass() {
 289         Symbol sym = this;
 290         Symbol prev = null;
 291         while (sym.kind != PCK) {
 292             prev = sym;
 293             sym = sym.owner;
 294         }
 295         return (ClassSymbol) prev;
 296     }
 297 
 298     /** The package which indirectly owns this symbol.
 299      */
 300     public PackageSymbol packge() {
 301         Symbol sym = this;
 302         while (sym.kind != PCK) {
 303             sym = sym.owner;
 304         }
 305         return (PackageSymbol) sym;
 306     }
 307 
 308     /** Is this symbol a subclass of `base'? Only defined for ClassSymbols.
 309      */
 310     public boolean isSubClass(Symbol base, Types types) {
 311         throw new AssertionError("isSubClass " + this);
 312     }
 313 
 314     /** Fully check membership: hierarchy, protection, and hiding.
 315      *  Does not exclude methods not inherited due to overriding.
 316      */
 317     public boolean isMemberOf(TypeSymbol clazz, Types types) {
 318         return
 319             owner == clazz ||
 320             clazz.isSubClass(owner, types) &&
 321             isInheritedIn(clazz, types) &&
 322             !hiddenIn((ClassSymbol)clazz, types);
 323     }
 324 
 325     /** Is this symbol the same as or enclosed by the given class? */
 326     public boolean isEnclosedBy(ClassSymbol clazz) {
 327         for (Symbol sym = this; sym.kind != PCK; sym = sym.owner)
 328             if (sym == clazz) return true;
 329         return false;
 330     }
 331 
 332     /** Check for hiding.  Note that this doesn't handle multiple
 333      *  (interface) inheritance. */
 334     private boolean hiddenIn(ClassSymbol clazz, Types types) {
 335         if (kind == MTH && (flags() & STATIC) == 0) return false;
 336         while (true) {
 337             if (owner == clazz) return false;
 338             Scope.Entry e = clazz.members().lookup(name);
 339             while (e.scope != null) {
 340                 if (e.sym == this) return false;
 341                 if (e.sym.kind == kind &&
 342                     (kind != MTH ||
 343                      (e.sym.flags() & STATIC) != 0 &&
 344                      types.isSubSignature(e.sym.type, type)))
 345                     return true;
 346                 e = e.next();
 347             }
 348             Type superType = types.supertype(clazz.type);
 349             if (superType.tag != TypeTags.CLASS) return false;
 350             clazz = (ClassSymbol)superType.tsym;
 351         }
 352     }
 353 
 354     /** Is this symbol inherited into a given class?
 355      *  PRE: If symbol's owner is a interface,
 356      *       it is already assumed that the interface is a superinterface
 357      *       of given class.
 358      *  @param clazz  The class for which we want to establish membership.
 359      *                This must be a subclass of the member's owner.
 360      */
 361     public boolean isInheritedIn(Symbol clazz, Types types) {
 362         switch ((int)(flags_field & Flags.AccessFlags)) {
 363         default: // error recovery
 364         case PUBLIC:
 365             return true;
 366         case PRIVATE:
 367             return this.owner == clazz;
 368         case PROTECTED:
 369             // we model interfaces as extending Object
 370             return (clazz.flags() & INTERFACE) == 0;
 371         case 0:
 372             PackageSymbol thisPackage = this.packge();
 373             for (Symbol sup = clazz;
 374                  sup != null && sup != this.owner;
 375                  sup = types.supertype(sup.type).tsym) {
 376                 while (sup.type.tag == TYPEVAR)
 377                     sup = sup.type.getUpperBound().tsym;
 378                 if (sup.type.isErroneous())
 379                     return true; // error recovery
 380                 if ((sup.flags() & COMPOUND) != 0)
 381                     continue;
 382                 if (sup.packge() != thisPackage)
 383                     return false;
 384             }
 385             return (clazz.flags() & INTERFACE) == 0;
 386         }
 387     }
 388 
 389     /** The (variable or method) symbol seen as a member of given
 390      *  class type`site' (this might change the symbol's type).
 391      *  This is used exclusively for producing diagnostics.
 392      */
 393     public Symbol asMemberOf(Type site, Types types) {
 394         throw new AssertionError();
 395     }
 396 
 397     /** Does this method symbol override `other' symbol, when both are seen as
 398      *  members of class `origin'?  It is assumed that _other is a member
 399      *  of origin.
 400      *
 401      *  It is assumed that both symbols have the same name.  The static
 402      *  modifier is ignored for this test.
 403      *
 404      *  See JLS 8.4.6.1 (without transitivity) and 8.4.6.4
 405      */
 406     public boolean overrides(Symbol _other, TypeSymbol origin, Types types, boolean checkResult) {
 407         return false;
 408     }
 409 
 410     /** Complete the elaboration of this symbol's definition.
 411      */
 412     public void complete() throws CompletionFailure {
 413         if (completer != null) {
 414             Completer c = completer;
 415             completer = null;
 416             c.complete(this);
 417         }
 418     }
 419 
 420     /** True if the symbol represents an entity that exists.
 421      */
 422     public boolean exists() {
 423         return true;
 424     }
 425 
 426     public Type asType() {
 427         return type;
 428     }
 429 
 430     public Symbol getEnclosingElement() {
 431         return owner;
 432     }
 433 
 434     public ElementKind getKind() {
 435         return ElementKind.OTHER;       // most unkind
 436     }
 437 
 438     public Set<Modifier> getModifiers() {
 439         return Flags.asModifierSet(flags());
 440     }
 441 
 442     public Name getSimpleName() {
 443         return name;
 444     }
 445 
 446     /**
 447      * @deprecated this method should never be used by javac internally.
 448      */
 449     @Deprecated
 450     public <A extends java.lang.annotation.Annotation> A getAnnotation(Class<A> annoType) {
 451         return JavacElements.getAnnotation(this, annoType);
 452     }
 453 
 454     // TODO: getEnclosedElements should return a javac List, fix in FilteredMemberList
 455     public java.util.List<Symbol> getEnclosedElements() {
 456         return List.nil();
 457     }
 458 
 459     public List<TypeSymbol> getTypeParameters() {
 460         ListBuffer<TypeSymbol> l = ListBuffer.lb();
 461         for (Type t : type.getTypeArguments()) {
 462             l.append(t.tsym);
 463         }
 464         return l.toList();
 465     }
 466 
 467     public static class DelegatedSymbol extends Symbol {
 468         protected Symbol other;
 469         public DelegatedSymbol(Symbol other) {
 470             super(other.kind, other.flags_field, other.name, other.type, other.owner);
 471             this.other = other;
 472         }
 473         public String toString() { return other.toString(); }
 474         public Symbol location() { return other.location(); }
 475         public Symbol location(Type site, Types types) { return other.location(site, types); }
 476         public Type erasure(Types types) { return other.erasure(types); }
 477         public Type externalType(Types types) { return other.externalType(types); }
 478         public boolean isLocal() { return other.isLocal(); }
 479         public boolean isConstructor() { return other.isConstructor(); }
 480         public Name getQualifiedName() { return other.getQualifiedName(); }
 481         public Name flatName() { return other.flatName(); }
 482         public Scope members() { return other.members(); }
 483         public boolean isInner() { return other.isInner(); }
 484         public boolean hasOuterInstance() { return other.hasOuterInstance(); }
 485         public ClassSymbol enclClass() { return other.enclClass(); }
 486         public ClassSymbol outermostClass() { return other.outermostClass(); }
 487         public PackageSymbol packge() { return other.packge(); }
 488         public boolean isSubClass(Symbol base, Types types) { return other.isSubClass(base, types); }
 489         public boolean isMemberOf(TypeSymbol clazz, Types types) { return other.isMemberOf(clazz, types); }
 490         public boolean isEnclosedBy(ClassSymbol clazz) { return other.isEnclosedBy(clazz); }
 491         public boolean isInheritedIn(Symbol clazz, Types types) { return other.isInheritedIn(clazz, types); }
 492         public Symbol asMemberOf(Type site, Types types) { return other.asMemberOf(site, types); }
 493         public void complete() throws CompletionFailure { other.complete(); }
 494 
 495         public <R, P> R accept(ElementVisitor<R, P> v, P p) {
 496             return other.accept(v, p);
 497         }
 498 
 499         public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
 500             return v.visitSymbol(other, p);
 501         }
 502     }
 503 
 504     /** A class for type symbols. Type variables are represented by instances
 505      *  of this class, classes and packages by instances of subclasses.
 506      */
 507     public static class TypeSymbol
 508             extends Symbol implements TypeParameterElement {
 509         // Implements TypeParameterElement because type parameters don't
 510         // have their own TypeSymbol subclass.
 511         // TODO: type parameters should have their own TypeSymbol subclass
 512 
 513         public TypeSymbol(long flags, Name name, Type type, Symbol owner) {
 514             super(TYP, flags, name, type, owner);
 515         }
 516 
 517         /** form a fully qualified name from a name and an owner
 518          */
 519         static public Name formFullName(Name name, Symbol owner) {
 520             if (owner == null) return name;
 521             if (((owner.kind != ERR)) &&
 522                 ((owner.kind & (VAR | MTH)) != 0
 523                  || (owner.kind == TYP && owner.type.tag == TYPEVAR)
 524                  )) return name;
 525             Name prefix = owner.getQualifiedName();
 526             if (prefix == null || prefix == prefix.table.names.empty)
 527                 return name;
 528             else return prefix.append('.', name);
 529         }
 530 
 531         /** form a fully qualified name from a name and an owner, after
 532          *  converting to flat representation
 533          */
 534         static public Name formFlatName(Name name, Symbol owner) {
 535             if (owner == null ||
 536                 (owner.kind & (VAR | MTH)) != 0
 537                 || (owner.kind == TYP && owner.type.tag == TYPEVAR)
 538                 ) return name;
 539             char sep = owner.kind == TYP ? '$' : '.';
 540             Name prefix = owner.flatName();
 541             if (prefix == null || prefix == prefix.table.names.empty)
 542                 return name;
 543             else return prefix.append(sep, name);
 544         }
 545 
 546         /**
 547          * A total ordering between type symbols that refines the
 548          * class inheritance graph.
 549          *
 550          * Typevariables always precede other kinds of symbols.
 551          */
 552         public final boolean precedes(TypeSymbol that, Types types) {
 553             if (this == that)
 554                 return false;
 555             if (this.type.tag == that.type.tag) {
 556                 if (this.type.tag == CLASS) {
 557                     return
 558                         types.rank(that.type) < types.rank(this.type) ||
 559                         types.rank(that.type) == types.rank(this.type) &&
 560                         that.getQualifiedName().compareTo(this.getQualifiedName()) < 0;
 561                 } else if (this.type.tag == TYPEVAR) {
 562                     return types.isSubtype(this.type, that.type);
 563                 }
 564             }
 565             return this.type.tag == TYPEVAR;
 566         }
 567 
 568         // For type params; overridden in subclasses.
 569         public ElementKind getKind() {
 570             return ElementKind.TYPE_PARAMETER;
 571         }
 572 
 573         public java.util.List<Symbol> getEnclosedElements() {
 574             List<Symbol> list = List.nil();
 575             for (Scope.Entry e = members().elems; e != null; e = e.sibling) {
 576                 if (e.sym != null && (e.sym.flags() & SYNTHETIC) == 0 && e.sym.owner == this)
 577                     list = list.prepend(e.sym);
 578             }
 579             return list;
 580         }
 581 
 582         // For type params.
 583         // Perhaps not needed if getEnclosingElement can be spec'ed
 584         // to do the same thing.
 585         // TODO: getGenericElement() might not be needed
 586         public Symbol getGenericElement() {
 587             return owner;
 588         }
 589 
 590         public <R, P> R accept(ElementVisitor<R, P> v, P p) {
 591             assert type.tag == TYPEVAR; // else override will be invoked
 592             return v.visitTypeParameter(this, p);
 593         }
 594 
 595         public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
 596             return v.visitTypeSymbol(this, p);
 597         }
 598 
 599         public List<Type> getBounds() {
 600             TypeVar t = (TypeVar)type;
 601             Type bound = t.getUpperBound();
 602             if (!bound.isCompound())
 603                 return List.of(bound);
 604             ClassType ct = (ClassType)bound;
 605             if (!ct.tsym.erasure_field.isInterface()) {
 606                 return ct.interfaces_field.prepend(ct.supertype_field);
 607             } else {
 608                 // No superclass was given in bounds.
 609                 // In this case, supertype is Object, erasure is first interface.
 610                 return ct.interfaces_field;
 611             }
 612         }
 613     }
 614 
 615     /** A class for package symbols
 616      */
 617     public static class PackageSymbol extends TypeSymbol
 618         implements PackageElement {
 619 
 620         public Scope members_field;
 621         public Name fullname;
 622         public ClassSymbol package_info; // see bug 6443073
 623 
 624         public PackageSymbol(Name name, Type type, Symbol owner) {
 625             super(0, name, type, owner);
 626             this.kind = PCK;
 627             this.members_field = null;
 628             this.fullname = formFullName(name, owner);
 629         }
 630 
 631         public PackageSymbol(Name name, Symbol owner) {
 632             this(name, null, owner);
 633             this.type = new PackageType(this);
 634         }
 635 
 636         public String toString() {
 637             return fullname.toString();
 638         }
 639 
 640         public Name getQualifiedName() {
 641             return fullname;
 642         }
 643 
 644         public boolean isUnnamed() {
 645             return name.isEmpty() && owner != null;
 646         }
 647 
 648         public Scope members() {
 649             if (completer != null) complete();
 650             return members_field;
 651         }
 652 
 653         public long flags() {
 654             if (completer != null) complete();
 655             return flags_field;
 656         }
 657 
 658         public List<Attribute.Compound> getAnnotationMirrors() {
 659             if (completer != null) complete();
 660             if (package_info != null && package_info.completer != null) {
 661                 package_info.complete();
 662                 if (attributes_field.isEmpty())
 663                     attributes_field = package_info.attributes_field;
 664             }
 665             assert attributes_field != null;
 666             return attributes_field;
 667         }
 668 
 669         /** A package "exists" if a type or package that exists has
 670          *  been seen within it.
 671          */
 672         public boolean exists() {
 673             return (flags_field & EXISTS) != 0;
 674         }
 675 
 676         public ElementKind getKind() {
 677             return ElementKind.PACKAGE;
 678         }
 679 
 680         public Symbol getEnclosingElement() {
 681             return null;
 682         }
 683 
 684         public <R, P> R accept(ElementVisitor<R, P> v, P p) {
 685             return v.visitPackage(this, p);
 686         }
 687 
 688         public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
 689             return v.visitPackageSymbol(this, p);
 690         }
 691     }
 692 
 693     /** A class for class symbols
 694      */
 695     public static class ClassSymbol extends TypeSymbol implements TypeElement {
 696 
 697         /** a scope for all class members; variables, methods and inner classes
 698          *  type parameters are not part of this scope
 699          */
 700         public Scope members_field;
 701 
 702         /** the fully qualified name of the class, i.e. pck.outer.inner.
 703          *  null for anonymous classes
 704          */
 705         public Name fullname;
 706 
 707         /** the fully qualified name of the class after converting to flat
 708          *  representation, i.e. pck.outer$inner,
 709          *  set externally for local and anonymous classes
 710          */
 711         public Name flatname;
 712 
 713         /** the sourcefile where the class came from
 714          */
 715         public JavaFileObject sourcefile;
 716 
 717         /** the classfile from where to load this class
 718          *  this will have extension .class or .java
 719          */
 720         public JavaFileObject classfile;
 721 
 722         /** the constant pool of the class
 723          */
 724         public Pool pool;
 725 
 726         public ClassSymbol(long flags, Name name, Type type, Symbol owner) {
 727             super(flags, name, type, owner);
 728             this.members_field = null;
 729             this.fullname = formFullName(name, owner);
 730             this.flatname = formFlatName(name, owner);
 731             this.sourcefile = null;
 732             this.classfile = null;
 733             this.pool = null;
 734         }
 735 
 736         public ClassSymbol(long flags, Name name, Symbol owner) {
 737             this(
 738                 flags,
 739                 name,
 740                 new ClassType(Type.noType, null, null),
 741                 owner);
 742             this.type.tsym = this;
 743         }
 744 
 745         /** The Java source which this symbol represents.
 746          */
 747         public String toString() {
 748             return className();
 749         }
 750 
 751         public long flags() {
 752             if (completer != null) complete();
 753             return flags_field;
 754         }
 755 
 756         public Scope members() {
 757             if (completer != null) complete();
 758             return members_field;
 759         }
 760 
 761         public List<Attribute.Compound> getAnnotationMirrors() {
 762             if (completer != null) complete();
 763             assert attributes_field != null;
 764             return attributes_field;
 765         }
 766 
 767         public Type erasure(Types types) {
 768             if (erasure_field == null)
 769                 erasure_field = new ClassType(types.erasure(type.getEnclosingType()),
 770                                               List.<Type>nil(), this);
 771             return erasure_field;
 772         }
 773 
 774         public String className() {
 775             if (name.isEmpty())
 776                 return
 777                     Log.getLocalizedString("anonymous.class", flatname);
 778             else
 779                 return fullname.toString();
 780         }
 781 
 782         public Name getQualifiedName() {
 783             if (fullname != null)
 784                 return fullname;
 785             else  // Anonymous classes have an empty name.
 786                 return name.table.fromString("");
 787         }
 788 
 789         public Name flatName() {
 790             return flatname;
 791         }
 792 
 793         public boolean isSubClass(Symbol base, Types types) {
 794             if (this == base) {
 795                 return true;
 796             } else if ((base.flags() & INTERFACE) != 0) {
 797                 for (Type t = type; t.tag == CLASS; t = types.supertype(t))
 798                     for (List<Type> is = types.interfaces(t);
 799                          is.nonEmpty();
 800                          is = is.tail)
 801                         if (is.head.tsym.isSubClass(base, types)) return true;
 802             } else {
 803                 for (Type t = type; t.tag == CLASS; t = types.supertype(t))
 804                     if (t.tsym == base) return true;
 805             }
 806             return false;
 807         }
 808 
 809         /** Complete the elaboration of this symbol's definition.
 810          */
 811         public void complete() throws CompletionFailure {
 812             try {
 813                 super.complete();
 814             } catch (CompletionFailure ex) {
 815                 // quiet error recovery
 816                 flags_field |= (PUBLIC|STATIC);
 817                 this.type = new ErrorType(this, Type.noType);
 818                 throw ex;
 819             }
 820         }
 821 
 822         public List<Type> getInterfaces() {
 823             complete();
 824             if (type instanceof ClassType) {
 825                 ClassType t = (ClassType)type;
 826                 if (t.interfaces_field == null) // FIXME: shouldn't be null
 827                     t.interfaces_field = List.nil();
 828                 return t.interfaces_field;
 829             } else {
 830                 return List.nil();
 831             }
 832         }
 833 
 834         public Type getSuperclass() {
 835             complete();
 836             if (type instanceof ClassType) {
 837                 ClassType t = (ClassType)type;
 838                 if (t.supertype_field == null) // FIXME: shouldn't be null
 839                     t.supertype_field = Type.noType;
 840                 // An interface has no superclass; its supertype is Object.
 841                 return t.isInterface()
 842                     ? Type.noType
 843                     : t.supertype_field;
 844             } else {
 845                 return Type.noType;
 846             }
 847         }
 848 
 849         public ElementKind getKind() {
 850             long flags = flags();
 851             if ((flags & ANNOTATION) != 0)
 852                 return ElementKind.ANNOTATION_TYPE;
 853             else if ((flags & INTERFACE) != 0)
 854                 return ElementKind.INTERFACE;
 855             else if ((flags & ENUM) != 0)
 856                 return ElementKind.ENUM;
 857             else
 858                 return ElementKind.CLASS;
 859         }
 860 
 861         public NestingKind getNestingKind() {
 862             complete();
 863             if (owner.kind == PCK)
 864                 return NestingKind.TOP_LEVEL;
 865             else if (name.isEmpty())
 866                 return NestingKind.ANONYMOUS;
 867             else if (owner.kind == MTH)
 868                 return NestingKind.LOCAL;
 869             else
 870                 return NestingKind.MEMBER;
 871         }
 872 
 873         /**
 874          * @deprecated this method should never be used by javac internally.
 875          */
 876         @Override @Deprecated
 877         public <A extends java.lang.annotation.Annotation> A getAnnotation(Class<A> annoType) {
 878             return JavacElements.getAnnotation(this, annoType);
 879         }
 880 
 881         public <R, P> R accept(ElementVisitor<R, P> v, P p) {
 882             return v.visitType(this, p);
 883         }
 884 
 885         public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
 886             return v.visitClassSymbol(this, p);
 887         }
 888     }
 889 
 890 
 891     /** A class for variable symbols
 892      */
 893     public static class VarSymbol extends Symbol implements VariableElement {
 894 
 895         /** The variable's declaration position.
 896          */
 897         public int pos = Position.NOPOS;
 898 
 899         /** The variable's address. Used for different purposes during
 900          *  flow analysis, translation and code generation.
 901          *  Flow analysis:
 902          *    If this is a blank final or local variable, its sequence number.
 903          *  Translation:
 904          *    If this is a private field, its access number.
 905          *  Code generation:
 906          *    If this is a local variable, its logical slot number.
 907          */
 908         public int adr = -1;
 909 
 910         /** Construct a variable symbol, given its flags, name, type and owner.
 911          */
 912         public VarSymbol(long flags, Name name, Type type, Symbol owner) {
 913             super(VAR, flags, name, type, owner);
 914         }
 915 
 916         /** Clone this symbol with new owner.
 917          */
 918         public VarSymbol clone(Symbol newOwner) {
 919             VarSymbol v = new VarSymbol(flags_field, name, type, newOwner);
 920             v.pos = pos;
 921             v.adr = adr;
 922             v.data = data;
 923 //          System.out.println("clone " + v + " in " + newOwner);//DEBUG
 924             return v;
 925         }
 926 
 927         public String toString() {
 928             return name.toString();
 929         }
 930 
 931         public Symbol asMemberOf(Type site, Types types) {
 932             return new VarSymbol(flags_field, name, types.memberType(site, this), owner);
 933         }
 934 
 935         public ElementKind getKind() {
 936             long flags = flags();
 937             if ((flags & PARAMETER) != 0) {
 938                 if (isExceptionParameter())
 939                     return ElementKind.EXCEPTION_PARAMETER;
 940                 else
 941                     return ElementKind.PARAMETER;
 942             } else if ((flags & ENUM) != 0) {
 943                 return ElementKind.ENUM_CONSTANT;
 944             } else if (owner.kind == TYP || owner.kind == ERR) {
 945                 return ElementKind.FIELD;
 946             } else {
 947                 return ElementKind.LOCAL_VARIABLE;
 948             }
 949         }
 950 
 951         public <R, P> R accept(ElementVisitor<R, P> v, P p) {
 952             return v.visitVariable(this, p);
 953         }
 954 
 955         public Object getConstantValue() { // Mirror API
 956             return Constants.decode(getConstValue(), type);
 957         }
 958 
 959         public void setLazyConstValue(final Env<AttrContext> env,
 960                                       final Log log,
 961                                       final Attr attr,
 962                                       final JCTree.JCExpression initializer)
 963         {
 964             setData(new Callable<Object>() {
 965                 public Object call() {
 966                     JavaFileObject source = log.useSource(env.toplevel.sourcefile);
 967                     try {
 968                         Type itype = attr.attribExpr(initializer, env, type);
 969                         if (itype.constValue() != null)
 970                             return attr.coerce(itype, type).constValue();
 971                         else
 972                             return null;
 973                     } finally {
 974                         log.useSource(source);
 975                     }
 976                 }
 977             });
 978         }
 979 
 980         /**
 981          * The variable's constant value, if this is a constant.
 982          * Before the constant value is evaluated, it points to an
 983          * initalizer environment.  If this is not a constant, it can
 984          * be used for other stuff.
 985          */
 986         private Object data;
 987 
 988         public boolean isExceptionParameter() {
 989             return data == ElementKind.EXCEPTION_PARAMETER;
 990         }
 991 
 992         public Object getConstValue() {
 993             // TODO: Consider if getConstValue and getConstantValue can be collapsed
 994             if (data == ElementKind.EXCEPTION_PARAMETER) {
 995                 return null;
 996             } else if (data instanceof Callable<?>) {
 997                 // In this case, this is final a variable, with an as
 998                 // yet unevaluated initializer.
 999                 Callable<?> eval = (Callable<?>)data;
1000                 data = null; // to make sure we don't evaluate this twice.
1001                 try {
1002                     data = eval.call();
1003                 } catch (Exception ex) {
1004                     throw new AssertionError(ex);
1005                 }
1006             }
1007             return data;
1008         }
1009 
1010         public void setData(Object data) {
1011             assert !(data instanceof Env<?>) : this;
1012             this.data = data;
1013         }
1014 
1015         public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
1016             return v.visitVarSymbol(this, p);
1017         }
1018     }
1019 
1020     /** A class for method symbols.
1021      */
1022     public static class MethodSymbol extends Symbol implements ExecutableElement {
1023 
1024         /** The code of the method. */
1025         public Code code = null;
1026 
1027         /** The parameters of the method. */
1028         public List<VarSymbol> params = null;
1029 
1030         /** The names of the parameters */
1031         public List<Name> savedParameterNames;
1032 
1033         /** For an attribute field accessor, its default value if any.
1034          *  The value is null if none appeared in the method
1035          *  declaration.
1036          */
1037         public Attribute defaultValue = null;
1038 
1039         /** Construct a method symbol, given its flags, name, type and owner.
1040          */
1041         public MethodSymbol(long flags, Name name, Type type, Symbol owner) {
1042             super(MTH, flags, name, type, owner);
1043             assert owner.type.tag != TYPEVAR : owner + "." + name;
1044         }
1045 
1046         /** Clone this symbol with new owner.
1047          */
1048         public MethodSymbol clone(Symbol newOwner) {
1049             MethodSymbol m = new MethodSymbol(flags_field, name, type, newOwner);
1050             m.code = code;
1051             return m;
1052         }
1053 
1054         /** The Java source which this symbol represents.
1055          */
1056         public String toString() {
1057             if ((flags() & BLOCK) != 0) {
1058                 return owner.name.toString();
1059             } else {
1060                 String s = (name == name.table.names.init)
1061                     ? owner.name.toString()
1062                     : name.toString();
1063                 if (type != null) {
1064                     if (type.tag == FORALL)
1065                         s = "<" + ((ForAll)type).getTypeArguments() + ">" + s;
1066                     s += "(" + type.argtypes((flags() & VARARGS) != 0) + ")";
1067                 }
1068                 return s;
1069             }
1070         }
1071 
1072         /** find a symbol that this (proxy method) symbol implements.
1073          *  @param    c       The class whose members are searched for
1074          *                    implementations
1075          */
1076         public Symbol implemented(TypeSymbol c, Types types) {
1077             Symbol impl = null;
1078             for (List<Type> is = types.interfaces(c.type);
1079                  impl == null && is.nonEmpty();
1080                  is = is.tail) {
1081                 TypeSymbol i = is.head.tsym;
1082                 for (Scope.Entry e = i.members().lookup(name);
1083                      impl == null && e.scope != null;
1084                      e = e.next()) {
1085                     if (this.overrides(e.sym, (TypeSymbol)owner, types, true) &&
1086                         // FIXME: I suspect the following requires a
1087                         // subst() for a parametric return type.
1088                         types.isSameType(type.getReturnType(),
1089                                          types.memberType(owner.type, e.sym).getReturnType())) {
1090                         impl = e.sym;
1091                     }
1092                     if (impl == null)
1093                         impl = implemented(i, types);
1094                 }
1095             }
1096             return impl;
1097         }
1098 
1099         /** Will the erasure of this method be considered by the VM to
1100          *  override the erasure of the other when seen from class `origin'?
1101          */
1102         public boolean binaryOverrides(Symbol _other, TypeSymbol origin, Types types) {
1103             if (isConstructor() || _other.kind != MTH) return false;
1104 
1105             if (this == _other) return true;
1106             MethodSymbol other = (MethodSymbol)_other;
1107 
1108             // check for a direct implementation
1109             if (other.isOverridableIn((TypeSymbol)owner) &&
1110                 types.asSuper(owner.type, other.owner) != null &&
1111                 types.isSameType(erasure(types), other.erasure(types)))
1112                 return true;
1113 
1114             // check for an inherited implementation
1115             return
1116                 (flags() & ABSTRACT) == 0 &&
1117                 other.isOverridableIn(origin) &&
1118                 this.isMemberOf(origin, types) &&
1119                 types.isSameType(erasure(types), other.erasure(types));
1120         }
1121 
1122         /** The implementation of this (abstract) symbol in class origin,
1123          *  from the VM's point of view, null if method does not have an
1124          *  implementation in class.
1125          *  @param origin   The class of which the implementation is a member.
1126          */
1127         public MethodSymbol binaryImplementation(ClassSymbol origin, Types types) {
1128             for (TypeSymbol c = origin; c != null; c = types.supertype(c.type).tsym) {
1129                 for (Scope.Entry e = c.members().lookup(name);
1130                      e.scope != null;
1131                      e = e.next()) {
1132                     if (e.sym.kind == MTH &&
1133                         ((MethodSymbol)e.sym).binaryOverrides(this, origin, types))
1134                         return (MethodSymbol)e.sym;
1135                 }
1136             }
1137             return null;
1138         }
1139 
1140         /** Does this symbol override `other' symbol, when both are seen as
1141          *  members of class `origin'?  It is assumed that _other is a member
1142          *  of origin.
1143          *
1144          *  It is assumed that both symbols have the same name.  The static
1145          *  modifier is ignored for this test.
1146          *
1147          *  See JLS 8.4.6.1 (without transitivity) and 8.4.6.4
1148          */
1149         public boolean overrides(Symbol _other, TypeSymbol origin, Types types, boolean checkResult) {
1150             if (isConstructor() || _other.kind != MTH) return false;
1151 
1152             if (this == _other) return true;
1153             MethodSymbol other = (MethodSymbol)_other;
1154 
1155             // check for a direct implementation
1156             if (other.isOverridableIn((TypeSymbol)owner) &&
1157                 types.asSuper(owner.type, other.owner) != null) {
1158                 Type mt = types.memberType(owner.type, this);
1159                 Type ot = types.memberType(owner.type, other);
1160                 if (types.isSubSignature(mt, ot)) {
1161                     if (!checkResult)
1162                         return true;
1163                     if (types.returnTypeSubstitutable(mt, ot))
1164                         return true;
1165                 }
1166             }
1167 
1168             // check for an inherited implementation
1169             if ((flags() & ABSTRACT) != 0 ||
1170                 (other.flags() & ABSTRACT) == 0 ||
1171                 !other.isOverridableIn(origin) ||
1172                 !this.isMemberOf(origin, types))
1173                 return false;
1174 
1175             // assert types.asSuper(origin.type, other.owner) != null;
1176             Type mt = types.memberType(origin.type, this);
1177             Type ot = types.memberType(origin.type, other);
1178             return
1179                 types.isSubSignature(mt, ot) &&
1180                 (!checkResult || types.resultSubtype(mt, ot, Warner.noWarnings));
1181         }
1182 
1183         private boolean isOverridableIn(TypeSymbol origin) {
1184             // JLS3 8.4.6.1
1185             switch ((int)(flags_field & Flags.AccessFlags)) {
1186             case Flags.PRIVATE:
1187                 return false;
1188             case Flags.PUBLIC:
1189                 return true;
1190             case Flags.PROTECTED:
1191                 return (origin.flags() & INTERFACE) == 0;
1192             case 0:
1193                 // for package private: can only override in the same
1194                 // package
1195                 return
1196                     this.packge() == origin.packge() &&
1197                     (origin.flags() & INTERFACE) == 0;
1198             default:
1199                 return false;
1200             }
1201         }
1202 
1203         /** The implementation of this (abstract) symbol in class origin;
1204          *  null if none exists. Synthetic methods are not considered
1205          *  as possible implementations.
1206          */
1207         public MethodSymbol implementation(TypeSymbol origin, Types types, boolean checkResult) {
1208             MethodSymbol res = types.implementation(this, origin, types, checkResult);
1209             if (res != null)
1210                 return res;
1211             // if origin is derived from a raw type, we might have missed
1212             // an implementation because we do not know enough about instantiations.
1213             // in this case continue with the supertype as origin.
1214             if (types.isDerivedRaw(origin.type))
1215                 return implementation(types.supertype(origin.type).tsym, types, checkResult);
1216             else
1217                 return null;
1218         }
1219 
1220         public List<VarSymbol> params() {
1221             owner.complete();
1222             if (params == null) {
1223                 // If ClassReader.saveParameterNames has been set true, then
1224                 // savedParameterNames will be set to a list of names that
1225                 // matches the types in type.getParameterTypes().  If any names
1226                 // were not found in the class file, those names in the list will
1227                 // be set to the empty name.
1228                 // If ClassReader.saveParameterNames has been set false, then
1229                 // savedParameterNames will be null.
1230                 List<Name> paramNames = savedParameterNames;
1231                 savedParameterNames = null;
1232                 // discard the provided names if the list of names is the wrong size.
1233                 if (paramNames == null || paramNames.size() != type.getParameterTypes().size())
1234                     paramNames = List.nil();
1235                 ListBuffer<VarSymbol> buf = new ListBuffer<VarSymbol>();
1236                 List<Name> remaining = paramNames;
1237                 // assert: remaining and paramNames are both empty or both
1238                 // have same cardinality as type.getParameterTypes()
1239                 int i = 0;
1240                 for (Type t : type.getParameterTypes()) {
1241                     Name paramName;
1242                     if (remaining.isEmpty()) {
1243                         // no names for any parameters available
1244                         paramName = createArgName(i, paramNames);
1245                     } else {
1246                         paramName = remaining.head;
1247                         remaining = remaining.tail;
1248                         if (paramName.isEmpty()) {
1249                             // no name for this specific parameter
1250                             paramName = createArgName(i, paramNames);
1251                         }
1252                     }
1253                     buf.append(new VarSymbol(PARAMETER, paramName, t, this));
1254                     i++;
1255                 }
1256                 params = buf.toList();
1257             }
1258             return params;
1259         }
1260 
1261         // Create a name for the argument at position 'index' that is not in
1262         // the exclude list. In normal use, either no names will have been
1263         // provided, in which case the exclude list is empty, or all the names
1264         // will have been provided, in which case this method will not be called.
1265         private Name createArgName(int index, List<Name> exclude) {
1266             String prefix = "arg";
1267             while (true) {
1268                 Name argName = name.table.fromString(prefix + index);
1269                 if (!exclude.contains(argName))
1270                     return argName;
1271                 prefix += "$";
1272             }
1273         }
1274 
1275         public Symbol asMemberOf(Type site, Types types) {
1276             return new MethodSymbol(flags_field, name, types.memberType(site, this), owner);
1277         }
1278 
1279         public ElementKind getKind() {
1280             if (name == name.table.names.init)
1281                 return ElementKind.CONSTRUCTOR;
1282             else if (name == name.table.names.clinit)
1283                 return ElementKind.STATIC_INIT;
1284             else
1285                 return ElementKind.METHOD;
1286         }
1287 
1288         public Attribute getDefaultValue() {
1289             return defaultValue;
1290         }
1291 
1292         public List<VarSymbol> getParameters() {
1293             return params();
1294         }
1295 
1296         public boolean isVarArgs() {
1297             return (flags() & VARARGS) != 0;
1298         }
1299 
1300         public <R, P> R accept(ElementVisitor<R, P> v, P p) {
1301             return v.visitExecutable(this, p);
1302         }
1303 
1304         public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
1305             return v.visitMethodSymbol(this, p);
1306         }
1307 
1308         public Type getReturnType() {
1309             return asType().getReturnType();
1310         }
1311 
1312         public List<Type> getThrownTypes() {
1313             return asType().getThrownTypes();
1314         }
1315     }
1316 
1317     /** A class for predefined operators.
1318      */
1319     public static class OperatorSymbol extends MethodSymbol {
1320 
1321         public int opcode;
1322 
1323         public OperatorSymbol(Name name, Type type, int opcode, Symbol owner) {
1324             super(PUBLIC | STATIC, name, type, owner);
1325             this.opcode = opcode;
1326         }
1327 
1328         public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
1329             return v.visitOperatorSymbol(this, p);
1330         }
1331     }
1332 
1333     /** Symbol completer interface.
1334      */
1335     public static interface Completer {
1336         void complete(Symbol sym) throws CompletionFailure;
1337     }
1338 
1339     public static class CompletionFailure extends RuntimeException {
1340         private static final long serialVersionUID = 0;
1341         public Symbol sym;
1342 
1343         /** A diagnostic object describing the failure
1344          */
1345         public JCDiagnostic diag;
1346 
1347         /** A localized string describing the failure.
1348          * @deprecated Use {@code getDetail()} or {@code getMessage()}
1349          */
1350         @Deprecated
1351         public String errmsg;
1352 
1353         public CompletionFailure(Symbol sym, String errmsg) {
1354             this.sym = sym;
1355             this.errmsg = errmsg;
1356 //          this.printStackTrace();//DEBUG
1357         }
1358 
1359         public CompletionFailure(Symbol sym, JCDiagnostic diag) {
1360             this.sym = sym;
1361             this.diag = diag;
1362 //          this.printStackTrace();//DEBUG
1363         }
1364 
1365         public JCDiagnostic getDiagnostic() {
1366             return diag;
1367         }
1368 
1369         @Override
1370         public String getMessage() {
1371             if (diag != null)
1372                 return diag.getMessage(null);
1373             else
1374                 return errmsg;
1375         }
1376 
1377         public Object getDetailValue() {
1378             return (diag != null ? diag : errmsg);
1379         }
1380 
1381         @Override
1382         public CompletionFailure initCause(Throwable cause) {
1383             super.initCause(cause);
1384             return this;
1385         }
1386 
1387     }
1388 
1389     /**
1390      * A visitor for symbols.  A visitor is used to implement operations
1391      * (or relations) on symbols.  Most common operations on types are
1392      * binary relations and this interface is designed for binary
1393      * relations, that is, operations on the form
1394      * Symbol&nbsp;&times;&nbsp;P&nbsp;&rarr;&nbsp;R.
1395      * <!-- In plain text: Type x P -> R -->
1396      *
1397      * @param <R> the return type of the operation implemented by this
1398      * visitor; use Void if no return type is needed.
1399      * @param <P> the type of the second argument (the first being the
1400      * symbol itself) of the operation implemented by this visitor; use
1401      * Void if a second argument is not needed.
1402      */
1403     public interface Visitor<R,P> {
1404         R visitClassSymbol(ClassSymbol s, P arg);
1405         R visitMethodSymbol(MethodSymbol s, P arg);
1406         R visitPackageSymbol(PackageSymbol s, P arg);
1407         R visitOperatorSymbol(OperatorSymbol s, P arg);
1408         R visitVarSymbol(VarSymbol s, P arg);
1409         R visitTypeSymbol(TypeSymbol s, P arg);
1410         R visitSymbol(Symbol s, P arg);
1411     }
1412 }