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)) {
 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             assert attributes_field != null;
 661             return attributes_field;
 662         }
 663 
 664         /** A package "exists" if a type or package that exists has
 665          *  been seen within it.
 666          */
 667         public boolean exists() {
 668             return (flags_field & EXISTS) != 0;
 669         }
 670 
 671         public ElementKind getKind() {
 672             return ElementKind.PACKAGE;
 673         }
 674 
 675         public Symbol getEnclosingElement() {
 676             return null;
 677         }
 678 
 679         public <R, P> R accept(ElementVisitor<R, P> v, P p) {
 680             return v.visitPackage(this, p);
 681         }
 682 
 683         public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
 684             return v.visitPackageSymbol(this, p);
 685         }
 686     }
 687 
 688     /** A class for class symbols
 689      */
 690     public static class ClassSymbol extends TypeSymbol implements TypeElement {
 691 
 692         /** a scope for all class members; variables, methods and inner classes
 693          *  type parameters are not part of this scope
 694          */
 695         public Scope members_field;
 696 
 697         /** the fully qualified name of the class, i.e. pck.outer.inner.
 698          *  null for anonymous classes
 699          */
 700         public Name fullname;
 701 
 702         /** the fully qualified name of the class after converting to flat
 703          *  representation, i.e. pck.outer$inner,
 704          *  set externally for local and anonymous classes
 705          */
 706         public Name flatname;
 707 
 708         /** the sourcefile where the class came from
 709          */
 710         public JavaFileObject sourcefile;
 711 
 712         /** the classfile from where to load this class
 713          *  this will have extension .class or .java
 714          */
 715         public JavaFileObject classfile;
 716 
 717         /** the constant pool of the class
 718          */
 719         public Pool pool;
 720 
 721         public ClassSymbol(long flags, Name name, Type type, Symbol owner) {
 722             super(flags, name, type, owner);
 723             this.members_field = null;
 724             this.fullname = formFullName(name, owner);
 725             this.flatname = formFlatName(name, owner);
 726             this.sourcefile = null;
 727             this.classfile = null;
 728             this.pool = null;
 729         }
 730 
 731         public ClassSymbol(long flags, Name name, Symbol owner) {
 732             this(
 733                 flags,
 734                 name,
 735                 new ClassType(Type.noType, null, null),
 736                 owner);
 737             this.type.tsym = this;
 738         }
 739 
 740         /** The Java source which this symbol represents.
 741          */
 742         public String toString() {
 743             return className();
 744         }
 745 
 746         public long flags() {
 747             if (completer != null) complete();
 748             return flags_field;
 749         }
 750 
 751         public Scope members() {
 752             if (completer != null) complete();
 753             return members_field;
 754         }
 755 
 756         public List<Attribute.Compound> getAnnotationMirrors() {
 757             if (completer != null) complete();
 758             assert attributes_field != null;
 759             return attributes_field;
 760         }
 761 
 762         public Type erasure(Types types) {
 763             if (erasure_field == null)
 764                 erasure_field = new ClassType(types.erasure(type.getEnclosingType()),
 765                                               List.<Type>nil(), this);
 766             return erasure_field;
 767         }
 768 
 769         public String className() {
 770             if (name.isEmpty())
 771                 return
 772                     Log.getLocalizedString("anonymous.class", flatname);
 773             else
 774                 return fullname.toString();
 775         }
 776 
 777         public Name getQualifiedName() {
 778             return fullname;
 779         }
 780 
 781         public Name flatName() {
 782             return flatname;
 783         }
 784 
 785         public boolean isSubClass(Symbol base, Types types) {
 786             if (this == base) {
 787                 return true;
 788             } else if ((base.flags() & INTERFACE) != 0) {
 789                 for (Type t = type; t.tag == CLASS; t = types.supertype(t))
 790                     for (List<Type> is = types.interfaces(t);
 791                          is.nonEmpty();
 792                          is = is.tail)
 793                         if (is.head.tsym.isSubClass(base, types)) return true;
 794             } else {
 795                 for (Type t = type; t.tag == CLASS; t = types.supertype(t))
 796                     if (t.tsym == base) return true;
 797             }
 798             return false;
 799         }
 800 
 801         /** Complete the elaboration of this symbol's definition.
 802          */
 803         public void complete() throws CompletionFailure {
 804             try {
 805                 super.complete();
 806             } catch (CompletionFailure ex) {
 807                 // quiet error recovery
 808                 flags_field |= (PUBLIC|STATIC);
 809                 this.type = new ErrorType(this, Type.noType);
 810                 throw ex;
 811             }
 812         }
 813 
 814         public List<Type> getInterfaces() {
 815             complete();
 816             if (type instanceof ClassType) {
 817                 ClassType t = (ClassType)type;
 818                 if (t.interfaces_field == null) // FIXME: shouldn't be null
 819                     t.interfaces_field = List.nil();
 820                 return t.interfaces_field;
 821             } else {
 822                 return List.nil();
 823             }
 824         }
 825 
 826         public Type getSuperclass() {
 827             complete();
 828             if (type instanceof ClassType) {
 829                 ClassType t = (ClassType)type;
 830                 if (t.supertype_field == null) // FIXME: shouldn't be null
 831                     t.supertype_field = Type.noType;
 832                 // An interface has no superclass; its supertype is Object.
 833                 return t.isInterface()
 834                     ? Type.noType
 835                     : t.supertype_field;
 836             } else {
 837                 return Type.noType;
 838             }
 839         }
 840 
 841         public ElementKind getKind() {
 842             long flags = flags();
 843             if ((flags & ANNOTATION) != 0)
 844                 return ElementKind.ANNOTATION_TYPE;
 845             else if ((flags & INTERFACE) != 0)
 846                 return ElementKind.INTERFACE;
 847             else if ((flags & ENUM) != 0)
 848                 return ElementKind.ENUM;
 849             else
 850                 return ElementKind.CLASS;
 851         }
 852 
 853         public NestingKind getNestingKind() {
 854             complete();
 855             if (owner.kind == PCK)
 856                 return NestingKind.TOP_LEVEL;
 857             else if (name.isEmpty())
 858                 return NestingKind.ANONYMOUS;
 859             else if (owner.kind == MTH)
 860                 return NestingKind.LOCAL;
 861             else
 862                 return NestingKind.MEMBER;
 863         }
 864 
 865         /**
 866          * @deprecated this method should never be used by javac internally.
 867          */
 868         @Override @Deprecated
 869         public <A extends java.lang.annotation.Annotation> A getAnnotation(Class<A> annoType) {
 870             return JavacElements.getAnnotation(this, annoType);
 871         }
 872 
 873         public <R, P> R accept(ElementVisitor<R, P> v, P p) {
 874             return v.visitType(this, p);
 875         }
 876 
 877         public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
 878             return v.visitClassSymbol(this, p);
 879         }
 880     }
 881 
 882 
 883     /** A class for variable symbols
 884      */
 885     public static class VarSymbol extends Symbol implements VariableElement {
 886 
 887         /** The variable's declaration position.
 888          */
 889         public int pos = Position.NOPOS;
 890 
 891         /** The variable's address. Used for different purposes during
 892          *  flow analysis, translation and code generation.
 893          *  Flow analysis:
 894          *    If this is a blank final or local variable, its sequence number.
 895          *  Translation:
 896          *    If this is a private field, its access number.
 897          *  Code generation:
 898          *    If this is a local variable, its logical slot number.
 899          */
 900         public int adr = -1;
 901 
 902         /** Construct a variable symbol, given its flags, name, type and owner.
 903          */
 904         public VarSymbol(long flags, Name name, Type type, Symbol owner) {
 905             super(VAR, flags, name, type, owner);
 906         }
 907 
 908         /** Clone this symbol with new owner.
 909          */
 910         public VarSymbol clone(Symbol newOwner) {
 911             VarSymbol v = new VarSymbol(flags_field, name, type, newOwner);
 912             v.pos = pos;
 913             v.adr = adr;
 914             v.data = data;
 915 //          System.out.println("clone " + v + " in " + newOwner);//DEBUG
 916             return v;
 917         }
 918 
 919         public String toString() {
 920             return name.toString();
 921         }
 922 
 923         public Symbol asMemberOf(Type site, Types types) {
 924             return new VarSymbol(flags_field, name, types.memberType(site, this), owner);
 925         }
 926 
 927         public ElementKind getKind() {
 928             long flags = flags();
 929             if ((flags & PARAMETER) != 0) {
 930                 if (isExceptionParameter())
 931                     return ElementKind.EXCEPTION_PARAMETER;
 932                 else
 933                     return ElementKind.PARAMETER;
 934             } else if ((flags & ENUM) != 0) {
 935                 return ElementKind.ENUM_CONSTANT;
 936             } else if (owner.kind == TYP || owner.kind == ERR) {
 937                 return ElementKind.FIELD;
 938             } else {
 939                 return ElementKind.LOCAL_VARIABLE;
 940             }
 941         }
 942 
 943         public <R, P> R accept(ElementVisitor<R, P> v, P p) {
 944             return v.visitVariable(this, p);
 945         }
 946 
 947         public Object getConstantValue() { // Mirror API
 948             return Constants.decode(getConstValue(), type);
 949         }
 950 
 951         public void setLazyConstValue(final Env<AttrContext> env,
 952                                       final Log log,
 953                                       final Attr attr,
 954                                       final JCTree.JCExpression initializer)
 955         {
 956             setData(new Callable<Object>() {
 957                 public Object call() {
 958                     JavaFileObject source = log.useSource(env.toplevel.sourcefile);
 959                     try {
 960                         Type itype = attr.attribExpr(initializer, env, type);
 961                         if (itype.constValue() != null)
 962                             return attr.coerce(itype, type).constValue();
 963                         else
 964                             return null;
 965                     } finally {
 966                         log.useSource(source);
 967                     }
 968                 }
 969             });
 970         }
 971 
 972         /**
 973          * The variable's constant value, if this is a constant.
 974          * Before the constant value is evaluated, it points to an
 975          * initalizer environment.  If this is not a constant, it can
 976          * be used for other stuff.
 977          */
 978         private Object data;
 979 
 980         public boolean isExceptionParameter() {
 981             return data == ElementKind.EXCEPTION_PARAMETER;
 982         }
 983 
 984         public Object getConstValue() {
 985             // TODO: Consider if getConstValue and getConstantValue can be collapsed
 986             if (data == ElementKind.EXCEPTION_PARAMETER) {
 987                 return null;
 988             } else if (data instanceof Callable<?>) {
 989                 // In this case, this is final a variable, with an as
 990                 // yet unevaluated initializer.
 991                 Callable<?> eval = (Callable<?>)data;
 992                 data = null; // to make sure we don't evaluate this twice.
 993                 try {
 994                     data = eval.call();
 995                 } catch (Exception ex) {
 996                     throw new AssertionError(ex);
 997                 }
 998             }
 999             return data;
1000         }
1001 
1002         public void setData(Object data) {
1003             assert !(data instanceof Env<?>) : this;
1004             this.data = data;
1005         }
1006 
1007         public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
1008             return v.visitVarSymbol(this, p);
1009         }
1010     }
1011 
1012     /** A class for method symbols.
1013      */
1014     public static class MethodSymbol extends Symbol implements ExecutableElement {
1015 
1016         /** The code of the method. */
1017         public Code code = null;
1018 
1019         /** The parameters of the method. */
1020         public List<VarSymbol> params = null;
1021 
1022         /** The names of the parameters */
1023         public List<Name> savedParameterNames;
1024 
1025         /** For an attribute field accessor, its default value if any.
1026          *  The value is null if none appeared in the method
1027          *  declaration.
1028          */
1029         public Attribute defaultValue = null;
1030 
1031         /** Construct a method symbol, given its flags, name, type and owner.
1032          */
1033         public MethodSymbol(long flags, Name name, Type type, Symbol owner) {
1034             super(MTH, flags, name, type, owner);
1035             assert owner.type.tag != TYPEVAR : owner + "." + name;
1036         }
1037 
1038         /** Clone this symbol with new owner.
1039          */
1040         public MethodSymbol clone(Symbol newOwner) {
1041             MethodSymbol m = new MethodSymbol(flags_field, name, type, newOwner);
1042             m.code = code;
1043             return m;
1044         }
1045 
1046         /** The Java source which this symbol represents.
1047          */
1048         public String toString() {
1049             if ((flags() & BLOCK) != 0) {
1050                 return owner.name.toString();
1051             } else {
1052                 String s = (name == name.table.names.init)
1053                     ? owner.name.toString()
1054                     : name.toString();
1055                 if (type != null) {
1056                     if (type.tag == FORALL)
1057                         s = "<" + ((ForAll)type).getTypeArguments() + ">" + s;
1058                     s += "(" + type.argtypes((flags() & VARARGS) != 0) + ")";
1059                 }
1060                 return s;
1061             }
1062         }
1063 
1064         /** find a symbol that this (proxy method) symbol implements.
1065          *  @param    c       The class whose members are searched for
1066          *                    implementations
1067          */
1068         public Symbol implemented(TypeSymbol c, Types types) {
1069             Symbol impl = null;
1070             for (List<Type> is = types.interfaces(c.type);
1071                  impl == null && is.nonEmpty();
1072                  is = is.tail) {
1073                 TypeSymbol i = is.head.tsym;
1074                 for (Scope.Entry e = i.members().lookup(name);
1075                      impl == null && e.scope != null;
1076                      e = e.next()) {
1077                     if (this.overrides(e.sym, (TypeSymbol)owner, types, true) &&
1078                         // FIXME: I suspect the following requires a
1079                         // subst() for a parametric return type.
1080                         types.isSameType(type.getReturnType(),
1081                                          types.memberType(owner.type, e.sym).getReturnType())) {
1082                         impl = e.sym;
1083                     }
1084                     if (impl == null)
1085                         impl = implemented(i, types);
1086                 }
1087             }
1088             return impl;
1089         }
1090 
1091         /** Will the erasure of this method be considered by the VM to
1092          *  override the erasure of the other when seen from class `origin'?
1093          */
1094         public boolean binaryOverrides(Symbol _other, TypeSymbol origin, Types types) {
1095             if (isConstructor() || _other.kind != MTH) return false;
1096 
1097             if (this == _other) return true;
1098             MethodSymbol other = (MethodSymbol)_other;
1099 
1100             // check for a direct implementation
1101             if (other.isOverridableIn((TypeSymbol)owner) &&
1102                 types.asSuper(owner.type, other.owner) != null &&
1103                 types.isSameType(erasure(types), other.erasure(types)))
1104                 return true;
1105 
1106             // check for an inherited implementation
1107             return
1108                 (flags() & ABSTRACT) == 0 &&
1109                 other.isOverridableIn(origin) &&
1110                 this.isMemberOf(origin, types) &&
1111                 types.isSameType(erasure(types), other.erasure(types));
1112         }
1113 
1114         /** The implementation of this (abstract) symbol in class origin,
1115          *  from the VM's point of view, null if method does not have an
1116          *  implementation in class.
1117          *  @param origin   The class of which the implementation is a member.
1118          */
1119         public MethodSymbol binaryImplementation(ClassSymbol origin, Types types) {
1120             for (TypeSymbol c = origin; c != null; c = types.supertype(c.type).tsym) {
1121                 for (Scope.Entry e = c.members().lookup(name);
1122                      e.scope != null;
1123                      e = e.next()) {
1124                     if (e.sym.kind == MTH &&
1125                         ((MethodSymbol)e.sym).binaryOverrides(this, origin, types))
1126                         return (MethodSymbol)e.sym;
1127                 }
1128             }
1129             return null;
1130         }
1131 
1132         /** Does this symbol override `other' symbol, when both are seen as
1133          *  members of class `origin'?  It is assumed that _other is a member
1134          *  of origin.
1135          *
1136          *  It is assumed that both symbols have the same name.  The static
1137          *  modifier is ignored for this test.
1138          *
1139          *  See JLS 8.4.6.1 (without transitivity) and 8.4.6.4
1140          */
1141         public boolean overrides(Symbol _other, TypeSymbol origin, Types types, boolean checkResult) {
1142             if (isConstructor() || _other.kind != MTH) return false;
1143 
1144             if (this == _other) return true;
1145             MethodSymbol other = (MethodSymbol)_other;
1146 
1147             // check for a direct implementation
1148             if (other.isOverridableIn((TypeSymbol)owner) &&
1149                 types.asSuper(owner.type, other.owner) != null) {
1150                 Type mt = types.memberType(owner.type, this);
1151                 Type ot = types.memberType(owner.type, other);
1152                 if (types.isSubSignature(mt, ot)) {
1153                     if (!checkResult)
1154                         return true;
1155                     if (types.returnTypeSubstitutable(mt, ot))
1156                         return true;
1157                 }
1158             }
1159 
1160             // check for an inherited implementation
1161             if ((flags() & ABSTRACT) != 0 ||
1162                 (other.flags() & ABSTRACT) == 0 ||
1163                 !other.isOverridableIn(origin) ||
1164                 !this.isMemberOf(origin, types))
1165                 return false;
1166 
1167             // assert types.asSuper(origin.type, other.owner) != null;
1168             Type mt = types.memberType(origin.type, this);
1169             Type ot = types.memberType(origin.type, other);
1170             return
1171                 types.isSubSignature(mt, ot) &&
1172                 (!checkResult || types.resultSubtype(mt, ot, Warner.noWarnings));
1173         }
1174 
1175         private boolean isOverridableIn(TypeSymbol origin) {
1176             // JLS3 8.4.6.1
1177             switch ((int)(flags_field & Flags.AccessFlags)) {
1178             case Flags.PRIVATE:
1179                 return false;
1180             case Flags.PUBLIC:
1181                 return true;
1182             case Flags.PROTECTED:
1183                 return (origin.flags() & INTERFACE) == 0;
1184             case 0:
1185                 // for package private: can only override in the same
1186                 // package
1187                 return
1188                     this.packge() == origin.packge() &&
1189                     (origin.flags() & INTERFACE) == 0;
1190             default:
1191                 return false;
1192             }
1193         }
1194 
1195         /** The implementation of this (abstract) symbol in class origin;
1196          *  null if none exists. Synthetic methods are not considered
1197          *  as possible implementations.
1198          */
1199         public MethodSymbol implementation(TypeSymbol origin, Types types, boolean checkResult) {
1200             MethodSymbol res = types.implementation(this, origin, types, checkResult);
1201             if (res != null)
1202                 return res;
1203             // if origin is derived from a raw type, we might have missed
1204             // an implementation because we do not know enough about instantiations.
1205             // in this case continue with the supertype as origin.
1206             if (types.isDerivedRaw(origin.type))
1207                 return implementation(types.supertype(origin.type).tsym, types, checkResult);
1208             else
1209                 return null;
1210         }
1211 
1212         public List<VarSymbol> params() {
1213             owner.complete();
1214             if (params == null) {
1215                 List<Name> names = savedParameterNames;
1216                 savedParameterNames = null;
1217                 if (names == null) {
1218                     names = List.nil();
1219                     int i = 0;
1220                     for (Type t : type.getParameterTypes())
1221                         names = names.prepend(name.table.fromString("arg" + i++));
1222                     names = names.reverse();
1223                 }
1224                 ListBuffer<VarSymbol> buf = new ListBuffer<VarSymbol>();
1225                 for (Type t : type.getParameterTypes()) {
1226                     buf.append(new VarSymbol(PARAMETER, names.head, t, this));
1227                     names = names.tail;
1228                 }
1229                 params = buf.toList();
1230             }
1231             return params;
1232         }
1233 
1234         public Symbol asMemberOf(Type site, Types types) {
1235             return new MethodSymbol(flags_field, name, types.memberType(site, this), owner);
1236         }
1237 
1238         public ElementKind getKind() {
1239             if (name == name.table.names.init)
1240                 return ElementKind.CONSTRUCTOR;
1241             else if (name == name.table.names.clinit)
1242                 return ElementKind.STATIC_INIT;
1243             else
1244                 return ElementKind.METHOD;
1245         }
1246 
1247         public Attribute getDefaultValue() {
1248             return defaultValue;
1249         }
1250 
1251         public List<VarSymbol> getParameters() {
1252             return params();
1253         }
1254 
1255         public boolean isVarArgs() {
1256             return (flags() & VARARGS) != 0;
1257         }
1258 
1259         public <R, P> R accept(ElementVisitor<R, P> v, P p) {
1260             return v.visitExecutable(this, p);
1261         }
1262 
1263         public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
1264             return v.visitMethodSymbol(this, p);
1265         }
1266 
1267         public Type getReturnType() {
1268             return asType().getReturnType();
1269         }
1270 
1271         public List<Type> getThrownTypes() {
1272             return asType().getThrownTypes();
1273         }
1274     }
1275 
1276     /** A class for predefined operators.
1277      */
1278     public static class OperatorSymbol extends MethodSymbol {
1279 
1280         public int opcode;
1281 
1282         public OperatorSymbol(Name name, Type type, int opcode, Symbol owner) {
1283             super(PUBLIC | STATIC, name, type, owner);
1284             this.opcode = opcode;
1285         }
1286 
1287         public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
1288             return v.visitOperatorSymbol(this, p);
1289         }
1290     }
1291 
1292     /** Symbol completer interface.
1293      */
1294     public static interface Completer {
1295         void complete(Symbol sym) throws CompletionFailure;
1296     }
1297 
1298     public static class CompletionFailure extends RuntimeException {
1299         private static final long serialVersionUID = 0;
1300         public Symbol sym;
1301 
1302         /** A diagnostic object describing the failure
1303          */
1304         public JCDiagnostic diag;
1305 
1306         /** A localized string describing the failure.
1307          * @deprecated Use {@code getDetail()} or {@code getMessage()}
1308          */
1309         @Deprecated
1310         public String errmsg;
1311 
1312         public CompletionFailure(Symbol sym, String errmsg) {
1313             this.sym = sym;
1314             this.errmsg = errmsg;
1315 //          this.printStackTrace();//DEBUG
1316         }
1317 
1318         public CompletionFailure(Symbol sym, JCDiagnostic diag) {
1319             this.sym = sym;
1320             this.diag = diag;
1321 //          this.printStackTrace();//DEBUG
1322         }
1323 
1324         public JCDiagnostic getDiagnostic() {
1325             return diag;
1326         }
1327 
1328         @Override
1329         public String getMessage() {
1330             if (diag != null)
1331                 return diag.getMessage(null);
1332             else
1333                 return errmsg;
1334         }
1335 
1336         public Object getDetailValue() {
1337             return (diag != null ? diag : errmsg);
1338         }
1339 
1340         @Override
1341         public CompletionFailure initCause(Throwable cause) {
1342             super.initCause(cause);
1343             return this;
1344         }
1345 
1346     }
1347 
1348     /**
1349      * A visitor for symbols.  A visitor is used to implement operations
1350      * (or relations) on symbols.  Most common operations on types are
1351      * binary relations and this interface is designed for binary
1352      * relations, that is, operations on the form
1353      * Symbol&nbsp;&times;&nbsp;P&nbsp;&rarr;&nbsp;R.
1354      * <!-- In plain text: Type x P -> R -->
1355      *
1356      * @param <R> the return type of the operation implemented by this
1357      * visitor; use Void if no return type is needed.
1358      * @param <P> the type of the second argument (the first being the
1359      * symbol itself) of the operation implemented by this visitor; use
1360      * Void if a second argument is not needed.
1361      */
1362     public interface Visitor<R,P> {
1363         R visitClassSymbol(ClassSymbol s, P arg);
1364         R visitMethodSymbol(MethodSymbol s, P arg);
1365         R visitPackageSymbol(PackageSymbol s, P arg);
1366         R visitOperatorSymbol(OperatorSymbol s, P arg);
1367         R visitVarSymbol(VarSymbol s, P arg);
1368         R visitTypeSymbol(TypeSymbol s, P arg);
1369         R visitSymbol(Symbol s, P arg);
1370     }
1371 }