src/share/classes/com/sun/tools/javac/code/Symbol.java

Tue, 07 Sep 2010 17:31:54 +0100

author
mcimadamore
date
Tue, 07 Sep 2010 17:31:54 +0100
changeset 673
7ae4016c5938
parent 666
f37253c9e082
child 674
584365f256a7
permissions
-rw-r--r--

6337171: javac should create bridge methods when type variable bounds restricted
Summary: javac should add synthetic overrides for inherited abstract methods in order to preserve binary compatibility
Reviewed-by: jjg

     1 /*
     2  * Copyright (c) 1999, 2008, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    26 package com.sun.tools.javac.code;
    28 import java.util.Set;
    29 import java.util.concurrent.Callable;
    30 import javax.lang.model.element.*;
    31 import javax.tools.JavaFileObject;
    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;
    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.*;
    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 supported API.
    53  *  If 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();
    60     /** The kind of this symbol.
    61      *  @see Kinds
    62      */
    63     public int kind;
    65     /** The flags of this symbol.
    66      */
    67     public long flags_field;
    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; }
    75     /** The attributes of this symbol.
    76      */
    77     public List<Attribute.Compound> attributes_field;
    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     }
    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     }
    95     /** The name of this symbol in Utf8 representation.
    96      */
    97     public Name name;
    99     /** The type of this symbol.
   100      */
   101     public Type type;
   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;
   114     /** The owner of this symbol.
   115      */
   116     public Symbol owner;
   118     /** The completer of this symbol.
   119      */
   120     public Completer completer;
   122     /** A cache for the type erasure of this symbol.
   123      */
   124     public Type erasure_field;
   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     }
   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     }
   147     public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
   148         return v.visitSymbol(this, p);
   149     }
   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     }
   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     }
   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     }
   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     }
   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     }
   207     public boolean isStatic() {
   208         return
   209             (flags() & STATIC) != 0 ||
   210             (owner.flags() & INTERFACE) != 0 && kind != MTH;
   211     }
   213     public boolean isInterface() {
   214         return (flags() & INTERFACE) != 0;
   215     }
   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     }
   228     /** Has this symbol an empty name? This includes anonymous
   229      *  inner classses.
   230      */
   231     public boolean isAnonymous() {
   232         return name.isEmpty();
   233     }
   235     /** Is this symbol a constructor?
   236      */
   237     public boolean isConstructor() {
   238         return name == name.table.names.init;
   239     }
   241     /** The fully qualified name of this symbol.
   242      *  This is the same as the symbol's name except for class symbols,
   243      *  which are handled separately.
   244      */
   245     public Name getQualifiedName() {
   246         return name;
   247     }
   249     /** The fully qualified name of this symbol after converting to flat
   250      *  representation. This is the same as the symbol's name except for
   251      *  class symbols, which are handled separately.
   252      */
   253     public Name flatName() {
   254         return getQualifiedName();
   255     }
   257     /** If this is a class or package, its members, otherwise null.
   258      */
   259     public Scope members() {
   260         return null;
   261     }
   263     /** A class is an inner class if it it has an enclosing instance class.
   264      */
   265     public boolean isInner() {
   266         return type.getEnclosingType().tag == CLASS;
   267     }
   269     /** An inner class has an outer instance if it is not an interface
   270      *  it has an enclosing instance class which might be referenced from the class.
   271      *  Nested classes can see instance members of their enclosing class.
   272      *  Their constructors carry an additional this$n parameter, inserted
   273      *  implicitly by the compiler.
   274      *
   275      *  @see #isInner
   276      */
   277     public boolean hasOuterInstance() {
   278         return
   279             type.getEnclosingType().tag == CLASS && (flags() & (INTERFACE | NOOUTERTHIS)) == 0;
   280     }
   282     /** The closest enclosing class of this symbol's declaration.
   283      */
   284     public ClassSymbol enclClass() {
   285         Symbol c = this;
   286         while (c != null &&
   287                ((c.kind & TYP) == 0 || c.type.tag != CLASS)) {
   288             c = c.owner;
   289         }
   290         return (ClassSymbol)c;
   291     }
   293     /** The outermost class which indirectly owns this symbol.
   294      */
   295     public ClassSymbol outermostClass() {
   296         Symbol sym = this;
   297         Symbol prev = null;
   298         while (sym.kind != PCK) {
   299             prev = sym;
   300             sym = sym.owner;
   301         }
   302         return (ClassSymbol) prev;
   303     }
   305     /** The package which indirectly owns this symbol.
   306      */
   307     public PackageSymbol packge() {
   308         Symbol sym = this;
   309         while (sym.kind != PCK) {
   310             sym = sym.owner;
   311         }
   312         return (PackageSymbol) sym;
   313     }
   315     /** Is this symbol a subclass of `base'? Only defined for ClassSymbols.
   316      */
   317     public boolean isSubClass(Symbol base, Types types) {
   318         throw new AssertionError("isSubClass " + this);
   319     }
   321     /** Fully check membership: hierarchy, protection, and hiding.
   322      *  Does not exclude methods not inherited due to overriding.
   323      */
   324     public boolean isMemberOf(TypeSymbol clazz, Types types) {
   325         return
   326             owner == clazz ||
   327             clazz.isSubClass(owner, types) &&
   328             isInheritedIn(clazz, types) &&
   329             !hiddenIn((ClassSymbol)clazz, types);
   330     }
   332     /** Is this symbol the same as or enclosed by the given class? */
   333     public boolean isEnclosedBy(ClassSymbol clazz) {
   334         for (Symbol sym = this; sym.kind != PCK; sym = sym.owner)
   335             if (sym == clazz) return true;
   336         return false;
   337     }
   339     /** Check for hiding.  Note that this doesn't handle multiple
   340      *  (interface) inheritance. */
   341     private boolean hiddenIn(ClassSymbol clazz, Types types) {
   342         if (kind == MTH && (flags() & STATIC) == 0) return false;
   343         while (true) {
   344             if (owner == clazz) return false;
   345             Scope.Entry e = clazz.members().lookup(name);
   346             while (e.scope != null) {
   347                 if (e.sym == this) return false;
   348                 if (e.sym.kind == kind &&
   349                     (kind != MTH ||
   350                      (e.sym.flags() & STATIC) != 0 &&
   351                      types.isSubSignature(e.sym.type, type)))
   352                     return true;
   353                 e = e.next();
   354             }
   355             Type superType = types.supertype(clazz.type);
   356             if (superType.tag != TypeTags.CLASS) return false;
   357             clazz = (ClassSymbol)superType.tsym;
   358         }
   359     }
   361     /** Is this symbol inherited into a given class?
   362      *  PRE: If symbol's owner is a interface,
   363      *       it is already assumed that the interface is a superinterface
   364      *       of given class.
   365      *  @param clazz  The class for which we want to establish membership.
   366      *                This must be a subclass of the member's owner.
   367      */
   368     public boolean isInheritedIn(Symbol clazz, Types types) {
   369         switch ((int)(flags_field & Flags.AccessFlags)) {
   370         default: // error recovery
   371         case PUBLIC:
   372             return true;
   373         case PRIVATE:
   374             return this.owner == clazz;
   375         case PROTECTED:
   376             // we model interfaces as extending Object
   377             return (clazz.flags() & INTERFACE) == 0;
   378         case 0:
   379             PackageSymbol thisPackage = this.packge();
   380             for (Symbol sup = clazz;
   381                  sup != null && sup != this.owner;
   382                  sup = types.supertype(sup.type).tsym) {
   383                 while (sup.type.tag == TYPEVAR)
   384                     sup = sup.type.getUpperBound().tsym;
   385                 if (sup.type.isErroneous())
   386                     return true; // error recovery
   387                 if ((sup.flags() & COMPOUND) != 0)
   388                     continue;
   389                 if (sup.packge() != thisPackage)
   390                     return false;
   391             }
   392             return (clazz.flags() & INTERFACE) == 0;
   393         }
   394     }
   396     /** The (variable or method) symbol seen as a member of given
   397      *  class type`site' (this might change the symbol's type).
   398      *  This is used exclusively for producing diagnostics.
   399      */
   400     public Symbol asMemberOf(Type site, Types types) {
   401         throw new AssertionError();
   402     }
   404     /** Does this method symbol override `other' symbol, when both are seen as
   405      *  members of class `origin'?  It is assumed that _other is a member
   406      *  of origin.
   407      *
   408      *  It is assumed that both symbols have the same name.  The static
   409      *  modifier is ignored for this test.
   410      *
   411      *  See JLS 8.4.6.1 (without transitivity) and 8.4.6.4
   412      */
   413     public boolean overrides(Symbol _other, TypeSymbol origin, Types types, boolean checkResult) {
   414         return false;
   415     }
   417     /** Complete the elaboration of this symbol's definition.
   418      */
   419     public void complete() throws CompletionFailure {
   420         if (completer != null) {
   421             Completer c = completer;
   422             completer = null;
   423             c.complete(this);
   424         }
   425     }
   427     /** True if the symbol represents an entity that exists.
   428      */
   429     public boolean exists() {
   430         return true;
   431     }
   433     public Type asType() {
   434         return type;
   435     }
   437     public Symbol getEnclosingElement() {
   438         return owner;
   439     }
   441     public ElementKind getKind() {
   442         return ElementKind.OTHER;       // most unkind
   443     }
   445     public Set<Modifier> getModifiers() {
   446         return Flags.asModifierSet(flags());
   447     }
   449     public Name getSimpleName() {
   450         return name;
   451     }
   453     /**
   454      * @deprecated this method should never be used by javac internally.
   455      */
   456     @Deprecated
   457     public <A extends java.lang.annotation.Annotation> A getAnnotation(Class<A> annoType) {
   458         return JavacElements.getAnnotation(this, annoType);
   459     }
   461     // TODO: getEnclosedElements should return a javac List, fix in FilteredMemberList
   462     public java.util.List<Symbol> getEnclosedElements() {
   463         return List.nil();
   464     }
   466     public List<TypeSymbol> getTypeParameters() {
   467         ListBuffer<TypeSymbol> l = ListBuffer.lb();
   468         for (Type t : type.getTypeArguments()) {
   469             l.append(t.tsym);
   470         }
   471         return l.toList();
   472     }
   474     public static class DelegatedSymbol extends Symbol {
   475         protected Symbol other;
   476         public DelegatedSymbol(Symbol other) {
   477             super(other.kind, other.flags_field, other.name, other.type, other.owner);
   478             this.other = other;
   479         }
   480         public String toString() { return other.toString(); }
   481         public Symbol location() { return other.location(); }
   482         public Symbol location(Type site, Types types) { return other.location(site, types); }
   483         public Type erasure(Types types) { return other.erasure(types); }
   484         public Type externalType(Types types) { return other.externalType(types); }
   485         public boolean isLocal() { return other.isLocal(); }
   486         public boolean isConstructor() { return other.isConstructor(); }
   487         public Name getQualifiedName() { return other.getQualifiedName(); }
   488         public Name flatName() { return other.flatName(); }
   489         public Scope members() { return other.members(); }
   490         public boolean isInner() { return other.isInner(); }
   491         public boolean hasOuterInstance() { return other.hasOuterInstance(); }
   492         public ClassSymbol enclClass() { return other.enclClass(); }
   493         public ClassSymbol outermostClass() { return other.outermostClass(); }
   494         public PackageSymbol packge() { return other.packge(); }
   495         public boolean isSubClass(Symbol base, Types types) { return other.isSubClass(base, types); }
   496         public boolean isMemberOf(TypeSymbol clazz, Types types) { return other.isMemberOf(clazz, types); }
   497         public boolean isEnclosedBy(ClassSymbol clazz) { return other.isEnclosedBy(clazz); }
   498         public boolean isInheritedIn(Symbol clazz, Types types) { return other.isInheritedIn(clazz, types); }
   499         public Symbol asMemberOf(Type site, Types types) { return other.asMemberOf(site, types); }
   500         public void complete() throws CompletionFailure { other.complete(); }
   502         public <R, P> R accept(ElementVisitor<R, P> v, P p) {
   503             return other.accept(v, p);
   504         }
   506         public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
   507             return v.visitSymbol(other, p);
   508         }
   509     }
   511     /** A class for type symbols. Type variables are represented by instances
   512      *  of this class, classes and packages by instances of subclasses.
   513      */
   514     public static class TypeSymbol
   515             extends Symbol implements TypeParameterElement {
   516         // Implements TypeParameterElement because type parameters don't
   517         // have their own TypeSymbol subclass.
   518         // TODO: type parameters should have their own TypeSymbol subclass
   520         public TypeSymbol(long flags, Name name, Type type, Symbol owner) {
   521             super(TYP, flags, name, type, owner);
   522         }
   524         /** form a fully qualified name from a name and an owner
   525          */
   526         static public Name formFullName(Name name, Symbol owner) {
   527             if (owner == null) return name;
   528             if (((owner.kind != ERR)) &&
   529                 ((owner.kind & (VAR | MTH)) != 0
   530                  || (owner.kind == TYP && owner.type.tag == TYPEVAR)
   531                  )) return name;
   532             Name prefix = owner.getQualifiedName();
   533             if (prefix == null || prefix == prefix.table.names.empty)
   534                 return name;
   535             else return prefix.append('.', name);
   536         }
   538         /** form a fully qualified name from a name and an owner, after
   539          *  converting to flat representation
   540          */
   541         static public Name formFlatName(Name name, Symbol owner) {
   542             if (owner == null ||
   543                 (owner.kind & (VAR | MTH)) != 0
   544                 || (owner.kind == TYP && owner.type.tag == TYPEVAR)
   545                 ) return name;
   546             char sep = owner.kind == TYP ? '$' : '.';
   547             Name prefix = owner.flatName();
   548             if (prefix == null || prefix == prefix.table.names.empty)
   549                 return name;
   550             else return prefix.append(sep, name);
   551         }
   553         /**
   554          * A total ordering between type symbols that refines the
   555          * class inheritance graph.
   556          *
   557          * Typevariables always precede other kinds of symbols.
   558          */
   559         public final boolean precedes(TypeSymbol that, Types types) {
   560             if (this == that)
   561                 return false;
   562             if (this.type.tag == that.type.tag) {
   563                 if (this.type.tag == CLASS) {
   564                     return
   565                         types.rank(that.type) < types.rank(this.type) ||
   566                         types.rank(that.type) == types.rank(this.type) &&
   567                         that.getQualifiedName().compareTo(this.getQualifiedName()) < 0;
   568                 } else if (this.type.tag == TYPEVAR) {
   569                     return types.isSubtype(this.type, that.type);
   570                 }
   571             }
   572             return this.type.tag == TYPEVAR;
   573         }
   575         // For type params; overridden in subclasses.
   576         public ElementKind getKind() {
   577             return ElementKind.TYPE_PARAMETER;
   578         }
   580         public java.util.List<Symbol> getEnclosedElements() {
   581             List<Symbol> list = List.nil();
   582             if (kind == TYP && type.tag == TYPEVAR) {
   583                 return list;
   584             }
   585             for (Scope.Entry e = members().elems; e != null; e = e.sibling) {
   586                 if (e.sym != null && (e.sym.flags() & SYNTHETIC) == 0 && e.sym.owner == this)
   587                     list = list.prepend(e.sym);
   588             }
   589             return list;
   590         }
   592         // For type params.
   593         // Perhaps not needed if getEnclosingElement can be spec'ed
   594         // to do the same thing.
   595         // TODO: getGenericElement() might not be needed
   596         public Symbol getGenericElement() {
   597             return owner;
   598         }
   600         public <R, P> R accept(ElementVisitor<R, P> v, P p) {
   601             assert type.tag == TYPEVAR; // else override will be invoked
   602             return v.visitTypeParameter(this, p);
   603         }
   605         public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
   606             return v.visitTypeSymbol(this, p);
   607         }
   609         public List<Type> getBounds() {
   610             TypeVar t = (TypeVar)type;
   611             Type bound = t.getUpperBound();
   612             if (!bound.isCompound())
   613                 return List.of(bound);
   614             ClassType ct = (ClassType)bound;
   615             if (!ct.tsym.erasure_field.isInterface()) {
   616                 return ct.interfaces_field.prepend(ct.supertype_field);
   617             } else {
   618                 // No superclass was given in bounds.
   619                 // In this case, supertype is Object, erasure is first interface.
   620                 return ct.interfaces_field;
   621             }
   622         }
   623     }
   625     /** A class for package symbols
   626      */
   627     public static class PackageSymbol extends TypeSymbol
   628         implements PackageElement {
   630         public Scope members_field;
   631         public Name fullname;
   632         public ClassSymbol package_info; // see bug 6443073
   634         public PackageSymbol(Name name, Type type, Symbol owner) {
   635             super(0, name, type, owner);
   636             this.kind = PCK;
   637             this.members_field = null;
   638             this.fullname = formFullName(name, owner);
   639         }
   641         public PackageSymbol(Name name, Symbol owner) {
   642             this(name, null, owner);
   643             this.type = new PackageType(this);
   644         }
   646         public String toString() {
   647             return fullname.toString();
   648         }
   650         public Name getQualifiedName() {
   651             return fullname;
   652         }
   654         public boolean isUnnamed() {
   655             return name.isEmpty() && owner != null;
   656         }
   658         public Scope members() {
   659             if (completer != null) complete();
   660             return members_field;
   661         }
   663         public long flags() {
   664             if (completer != null) complete();
   665             return flags_field;
   666         }
   668         public List<Attribute.Compound> getAnnotationMirrors() {
   669             if (completer != null) complete();
   670             if (package_info != null && package_info.completer != null) {
   671                 package_info.complete();
   672                 if (attributes_field.isEmpty())
   673                     attributes_field = package_info.attributes_field;
   674             }
   675             assert attributes_field != null;
   676             return attributes_field;
   677         }
   679         /** A package "exists" if a type or package that exists has
   680          *  been seen within it.
   681          */
   682         public boolean exists() {
   683             return (flags_field & EXISTS) != 0;
   684         }
   686         public ElementKind getKind() {
   687             return ElementKind.PACKAGE;
   688         }
   690         public Symbol getEnclosingElement() {
   691             return null;
   692         }
   694         public <R, P> R accept(ElementVisitor<R, P> v, P p) {
   695             return v.visitPackage(this, p);
   696         }
   698         public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
   699             return v.visitPackageSymbol(this, p);
   700         }
   701     }
   703     /** A class for class symbols
   704      */
   705     public static class ClassSymbol extends TypeSymbol implements TypeElement {
   707         /** a scope for all class members; variables, methods and inner classes
   708          *  type parameters are not part of this scope
   709          */
   710         public Scope members_field;
   712         /** the fully qualified name of the class, i.e. pck.outer.inner.
   713          *  null for anonymous classes
   714          */
   715         public Name fullname;
   717         /** the fully qualified name of the class after converting to flat
   718          *  representation, i.e. pck.outer$inner,
   719          *  set externally for local and anonymous classes
   720          */
   721         public Name flatname;
   723         /** the sourcefile where the class came from
   724          */
   725         public JavaFileObject sourcefile;
   727         /** the classfile from where to load this class
   728          *  this will have extension .class or .java
   729          */
   730         public JavaFileObject classfile;
   732         /** the constant pool of the class
   733          */
   734         public Pool pool;
   736         public ClassSymbol(long flags, Name name, Type type, Symbol owner) {
   737             super(flags, name, type, owner);
   738             this.members_field = null;
   739             this.fullname = formFullName(name, owner);
   740             this.flatname = formFlatName(name, owner);
   741             this.sourcefile = null;
   742             this.classfile = null;
   743             this.pool = null;
   744         }
   746         public ClassSymbol(long flags, Name name, Symbol owner) {
   747             this(
   748                 flags,
   749                 name,
   750                 new ClassType(Type.noType, null, null),
   751                 owner);
   752             this.type.tsym = this;
   753         }
   755         /** The Java source which this symbol represents.
   756          */
   757         public String toString() {
   758             return className();
   759         }
   761         public long flags() {
   762             if (completer != null) complete();
   763             return flags_field;
   764         }
   766         public Scope members() {
   767             if (completer != null) complete();
   768             return members_field;
   769         }
   771         public List<Attribute.Compound> getAnnotationMirrors() {
   772             if (completer != null) complete();
   773             assert attributes_field != null;
   774             return attributes_field;
   775         }
   777         public Type erasure(Types types) {
   778             if (erasure_field == null)
   779                 erasure_field = new ClassType(types.erasure(type.getEnclosingType()),
   780                                               List.<Type>nil(), this);
   781             return erasure_field;
   782         }
   784         public String className() {
   785             if (name.isEmpty())
   786                 return
   787                     Log.getLocalizedString("anonymous.class", flatname);
   788             else
   789                 return fullname.toString();
   790         }
   792         public Name getQualifiedName() {
   793             return fullname;
   794         }
   796         public Name flatName() {
   797             return flatname;
   798         }
   800         public boolean isSubClass(Symbol base, Types types) {
   801             if (this == base) {
   802                 return true;
   803             } else if ((base.flags() & INTERFACE) != 0) {
   804                 for (Type t = type; t.tag == CLASS; t = types.supertype(t))
   805                     for (List<Type> is = types.interfaces(t);
   806                          is.nonEmpty();
   807                          is = is.tail)
   808                         if (is.head.tsym.isSubClass(base, types)) return true;
   809             } else {
   810                 for (Type t = type; t.tag == CLASS; t = types.supertype(t))
   811                     if (t.tsym == base) return true;
   812             }
   813             return false;
   814         }
   816         /** Complete the elaboration of this symbol's definition.
   817          */
   818         public void complete() throws CompletionFailure {
   819             try {
   820                 super.complete();
   821             } catch (CompletionFailure ex) {
   822                 // quiet error recovery
   823                 flags_field |= (PUBLIC|STATIC);
   824                 this.type = new ErrorType(this, Type.noType);
   825                 throw ex;
   826             }
   827         }
   829         public List<Type> getInterfaces() {
   830             complete();
   831             if (type instanceof ClassType) {
   832                 ClassType t = (ClassType)type;
   833                 if (t.interfaces_field == null) // FIXME: shouldn't be null
   834                     t.interfaces_field = List.nil();
   835                 return t.interfaces_field;
   836             } else {
   837                 return List.nil();
   838             }
   839         }
   841         public Type getSuperclass() {
   842             complete();
   843             if (type instanceof ClassType) {
   844                 ClassType t = (ClassType)type;
   845                 if (t.supertype_field == null) // FIXME: shouldn't be null
   846                     t.supertype_field = Type.noType;
   847                 // An interface has no superclass; its supertype is Object.
   848                 return t.isInterface()
   849                     ? Type.noType
   850                     : t.supertype_field;
   851             } else {
   852                 return Type.noType;
   853             }
   854         }
   856         public ElementKind getKind() {
   857             long flags = flags();
   858             if ((flags & ANNOTATION) != 0)
   859                 return ElementKind.ANNOTATION_TYPE;
   860             else if ((flags & INTERFACE) != 0)
   861                 return ElementKind.INTERFACE;
   862             else if ((flags & ENUM) != 0)
   863                 return ElementKind.ENUM;
   864             else
   865                 return ElementKind.CLASS;
   866         }
   868         public NestingKind getNestingKind() {
   869             complete();
   870             if (owner.kind == PCK)
   871                 return NestingKind.TOP_LEVEL;
   872             else if (name.isEmpty())
   873                 return NestingKind.ANONYMOUS;
   874             else if (owner.kind == MTH)
   875                 return NestingKind.LOCAL;
   876             else
   877                 return NestingKind.MEMBER;
   878         }
   880         /**
   881          * @deprecated this method should never be used by javac internally.
   882          */
   883         @Override @Deprecated
   884         public <A extends java.lang.annotation.Annotation> A getAnnotation(Class<A> annoType) {
   885             return JavacElements.getAnnotation(this, annoType);
   886         }
   888         public <R, P> R accept(ElementVisitor<R, P> v, P p) {
   889             return v.visitType(this, p);
   890         }
   892         public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
   893             return v.visitClassSymbol(this, p);
   894         }
   895     }
   898     /** A class for variable symbols
   899      */
   900     public static class VarSymbol extends Symbol implements VariableElement {
   902         /** The variable's declaration position.
   903          */
   904         public int pos = Position.NOPOS;
   906         /** The variable's address. Used for different purposes during
   907          *  flow analysis, translation and code generation.
   908          *  Flow analysis:
   909          *    If this is a blank final or local variable, its sequence number.
   910          *  Translation:
   911          *    If this is a private field, its access number.
   912          *  Code generation:
   913          *    If this is a local variable, its logical slot number.
   914          */
   915         public int adr = -1;
   917         /** Construct a variable symbol, given its flags, name, type and owner.
   918          */
   919         public VarSymbol(long flags, Name name, Type type, Symbol owner) {
   920             super(VAR, flags, name, type, owner);
   921         }
   923         /** Clone this symbol with new owner.
   924          */
   925         public VarSymbol clone(Symbol newOwner) {
   926             VarSymbol v = new VarSymbol(flags_field, name, type, newOwner);
   927             v.pos = pos;
   928             v.adr = adr;
   929             v.data = data;
   930 //          System.out.println("clone " + v + " in " + newOwner);//DEBUG
   931             return v;
   932         }
   934         public String toString() {
   935             return name.toString();
   936         }
   938         public Symbol asMemberOf(Type site, Types types) {
   939             return new VarSymbol(flags_field, name, types.memberType(site, this), owner);
   940         }
   942         public ElementKind getKind() {
   943             long flags = flags();
   944             if ((flags & PARAMETER) != 0) {
   945                 if (isExceptionParameter())
   946                     return ElementKind.EXCEPTION_PARAMETER;
   947                 else
   948                     return ElementKind.PARAMETER;
   949             } else if ((flags & ENUM) != 0) {
   950                 return ElementKind.ENUM_CONSTANT;
   951             } else if (owner.kind == TYP || owner.kind == ERR) {
   952                 return ElementKind.FIELD;
   953             } else {
   954                 return ElementKind.LOCAL_VARIABLE;
   955             }
   956         }
   958         public <R, P> R accept(ElementVisitor<R, P> v, P p) {
   959             return v.visitVariable(this, p);
   960         }
   962         public Object getConstantValue() { // Mirror API
   963             return Constants.decode(getConstValue(), type);
   964         }
   966         public void setLazyConstValue(final Env<AttrContext> env,
   967                                       final Log log,
   968                                       final Attr attr,
   969                                       final JCTree.JCExpression initializer)
   970         {
   971             setData(new Callable<Object>() {
   972                 public Object call() {
   973                     JavaFileObject source = log.useSource(env.toplevel.sourcefile);
   974                     try {
   975                         Type itype = attr.attribExpr(initializer, env, type);
   976                         if (itype.constValue() != null)
   977                             return attr.coerce(itype, type).constValue();
   978                         else
   979                             return null;
   980                     } finally {
   981                         log.useSource(source);
   982                     }
   983                 }
   984             });
   985         }
   987         /**
   988          * The variable's constant value, if this is a constant.
   989          * Before the constant value is evaluated, it points to an
   990          * initalizer environment.  If this is not a constant, it can
   991          * be used for other stuff.
   992          */
   993         private Object data;
   995         public boolean isExceptionParameter() {
   996             return data == ElementKind.EXCEPTION_PARAMETER;
   997         }
   999         public boolean isResourceVariable() {
  1000             return data == ElementKind.RESOURCE_VARIABLE;
  1003         public Object getConstValue() {
  1004             // TODO: Consider if getConstValue and getConstantValue can be collapsed
  1005             if (data == ElementKind.EXCEPTION_PARAMETER ||
  1006                 data == ElementKind.RESOURCE_VARIABLE) {
  1007                 return null;
  1008             } else if (data instanceof Callable<?>) {
  1009                 // In this case, this is a final variable, with an as
  1010                 // yet unevaluated initializer.
  1011                 Callable<?> eval = (Callable<?>)data;
  1012                 data = null; // to make sure we don't evaluate this twice.
  1013                 try {
  1014                     data = eval.call();
  1015                 } catch (Exception ex) {
  1016                     throw new AssertionError(ex);
  1019             return data;
  1022         public void setData(Object data) {
  1023             assert !(data instanceof Env<?>) : this;
  1024             this.data = data;
  1027         public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
  1028             return v.visitVarSymbol(this, p);
  1032     /** A class for method symbols.
  1033      */
  1034     public static class MethodSymbol extends Symbol implements ExecutableElement {
  1036         /** The code of the method. */
  1037         public Code code = null;
  1039         /** The parameters of the method. */
  1040         public List<VarSymbol> params = null;
  1042         /** The names of the parameters */
  1043         public List<Name> savedParameterNames;
  1045         /** For an attribute field accessor, its default value if any.
  1046          *  The value is null if none appeared in the method
  1047          *  declaration.
  1048          */
  1049         public Attribute defaultValue = null;
  1051         /** Construct a method symbol, given its flags, name, type and owner.
  1052          */
  1053         public MethodSymbol(long flags, Name name, Type type, Symbol owner) {
  1054             super(MTH, flags, name, type, owner);
  1055             assert owner.type.tag != TYPEVAR : owner + "." + name;
  1058         /** Clone this symbol with new owner.
  1059          */
  1060         public MethodSymbol clone(Symbol newOwner) {
  1061             MethodSymbol m = new MethodSymbol(flags_field, name, type, newOwner);
  1062             m.code = code;
  1063             return m;
  1066         /** The Java source which this symbol represents.
  1067          */
  1068         public String toString() {
  1069             if ((flags() & BLOCK) != 0) {
  1070                 return owner.name.toString();
  1071             } else {
  1072                 String s = (name == name.table.names.init)
  1073                     ? owner.name.toString()
  1074                     : name.toString();
  1075                 if (type != null) {
  1076                     if (type.tag == FORALL)
  1077                         s = "<" + ((ForAll)type).getTypeArguments() + ">" + s;
  1078                     s += "(" + type.argtypes((flags() & VARARGS) != 0) + ")";
  1080                 return s;
  1084         /** find a symbol that this (proxy method) symbol implements.
  1085          *  @param    c       The class whose members are searched for
  1086          *                    implementations
  1087          */
  1088         public Symbol implemented(TypeSymbol c, Types types) {
  1089             Symbol impl = null;
  1090             for (List<Type> is = types.interfaces(c.type);
  1091                  impl == null && is.nonEmpty();
  1092                  is = is.tail) {
  1093                 TypeSymbol i = is.head.tsym;
  1094                 for (Scope.Entry e = i.members().lookup(name);
  1095                      impl == null && e.scope != null;
  1096                      e = e.next()) {
  1097                     if (this.overrides(e.sym, (TypeSymbol)owner, types, true) &&
  1098                         // FIXME: I suspect the following requires a
  1099                         // subst() for a parametric return type.
  1100                         types.isSameType(type.getReturnType(),
  1101                                          types.memberType(owner.type, e.sym).getReturnType())) {
  1102                         impl = e.sym;
  1104                     if (impl == null)
  1105                         impl = implemented(i, types);
  1108             return impl;
  1111         /** Will the erasure of this method be considered by the VM to
  1112          *  override the erasure of the other when seen from class `origin'?
  1113          */
  1114         public boolean binaryOverrides(Symbol _other, TypeSymbol origin, Types types) {
  1115             if (isConstructor() || _other.kind != MTH) return false;
  1117             if (this == _other) return true;
  1118             MethodSymbol other = (MethodSymbol)_other;
  1120             // check for a direct implementation
  1121             if (other.isOverridableIn((TypeSymbol)owner) &&
  1122                 types.asSuper(owner.type, other.owner) != null &&
  1123                 types.isSameType(erasure(types), other.erasure(types)))
  1124                 return true;
  1126             // check for an inherited implementation
  1127             return
  1128                 (flags() & ABSTRACT) == 0 &&
  1129                 other.isOverridableIn(origin) &&
  1130                 this.isMemberOf(origin, types) &&
  1131                 types.isSameType(erasure(types), other.erasure(types));
  1134         /** The implementation of this (abstract) symbol in class origin,
  1135          *  from the VM's point of view, null if method does not have an
  1136          *  implementation in class.
  1137          *  @param origin   The class of which the implementation is a member.
  1138          */
  1139         public MethodSymbol binaryImplementation(ClassSymbol origin, Types types) {
  1140             for (TypeSymbol c = origin; c != null; c = types.supertype(c.type).tsym) {
  1141                 for (Scope.Entry e = c.members().lookup(name);
  1142                      e.scope != null;
  1143                      e = e.next()) {
  1144                     if (e.sym.kind == MTH &&
  1145                         ((MethodSymbol)e.sym).binaryOverrides(this, origin, types))
  1146                         return (MethodSymbol)e.sym;
  1149             return null;
  1152         /** Does this symbol override `other' symbol, when both are seen as
  1153          *  members of class `origin'?  It is assumed that _other is a member
  1154          *  of origin.
  1156          *  It is assumed that both symbols have the same name.  The static
  1157          *  modifier is ignored for this test.
  1159          *  See JLS 8.4.6.1 (without transitivity) and 8.4.6.4
  1160          */
  1161         public boolean overrides(Symbol _other, TypeSymbol origin, Types types, boolean checkResult) {
  1162             if (isConstructor() || _other.kind != MTH) return false;
  1164             if (this == _other) return true;
  1165             MethodSymbol other = (MethodSymbol)_other;
  1167             // check for a direct implementation
  1168             if (other.isOverridableIn((TypeSymbol)owner) &&
  1169                 types.asSuper(owner.type, other.owner) != null) {
  1170                 Type mt = types.memberType(owner.type, this);
  1171                 Type ot = types.memberType(owner.type, other);
  1172                 if (types.isSubSignature(mt, ot)) {
  1173                     if (!checkResult)
  1174                         return true;
  1175                     if (types.returnTypeSubstitutable(mt, ot))
  1176                         return true;
  1180             // check for an inherited implementation
  1181             if ((flags() & ABSTRACT) != 0 ||
  1182                 (other.flags() & ABSTRACT) == 0 ||
  1183                 !other.isOverridableIn(origin) ||
  1184                 !this.isMemberOf(origin, types))
  1185                 return false;
  1187             // assert types.asSuper(origin.type, other.owner) != null;
  1188             Type mt = types.memberType(origin.type, this);
  1189             Type ot = types.memberType(origin.type, other);
  1190             return
  1191                 types.isSubSignature(mt, ot) &&
  1192                 (!checkResult || types.resultSubtype(mt, ot, Warner.noWarnings));
  1195         private boolean isOverridableIn(TypeSymbol origin) {
  1196             // JLS3 8.4.6.1
  1197             switch ((int)(flags_field & Flags.AccessFlags)) {
  1198             case Flags.PRIVATE:
  1199                 return false;
  1200             case Flags.PUBLIC:
  1201                 return true;
  1202             case Flags.PROTECTED:
  1203                 return (origin.flags() & INTERFACE) == 0;
  1204             case 0:
  1205                 // for package private: can only override in the same
  1206                 // package
  1207                 return
  1208                     this.packge() == origin.packge() &&
  1209                     (origin.flags() & INTERFACE) == 0;
  1210             default:
  1211                 return false;
  1215         /** The implementation of this (abstract) symbol in class origin;
  1216          *  null if none exists. Synthetic methods are not considered
  1217          *  as possible implementations.
  1218          */
  1219         public MethodSymbol implementation(TypeSymbol origin, Types types, boolean checkResult) {
  1220             return implementation(origin, types, checkResult, implementation_filter);
  1222         // where
  1223             private static final Filter<Symbol> implementation_filter = new Filter<Symbol>() {
  1224                 public boolean accepts(Symbol s) {
  1225                     return s.kind == Kinds.MTH &&
  1226                             (s.flags() & SYNTHETIC) == 0;
  1228             };
  1230         public MethodSymbol implementation(TypeSymbol origin, Types types, boolean checkResult, Filter<Symbol> implFilter) {
  1231             MethodSymbol res = types.implementation(this, origin, types, checkResult, implFilter);
  1232             if (res != null)
  1233                 return res;
  1234             // if origin is derived from a raw type, we might have missed
  1235             // an implementation because we do not know enough about instantiations.
  1236             // in this case continue with the supertype as origin.
  1237             if (types.isDerivedRaw(origin.type))
  1238                 return implementation(types.supertype(origin.type).tsym, types, checkResult);
  1239             else
  1240                 return null;
  1243         public List<VarSymbol> params() {
  1244             owner.complete();
  1245             if (params == null) {
  1246                 // If ClassReader.saveParameterNames has been set true, then
  1247                 // savedParameterNames will be set to a list of names that
  1248                 // matches the types in type.getParameterTypes().  If any names
  1249                 // were not found in the class file, those names in the list will
  1250                 // be set to the empty name.
  1251                 // If ClassReader.saveParameterNames has been set false, then
  1252                 // savedParameterNames will be null.
  1253                 List<Name> paramNames = savedParameterNames;
  1254                 savedParameterNames = null;
  1255                 // discard the provided names if the list of names is the wrong size.
  1256                 if (paramNames == null || paramNames.size() != type.getParameterTypes().size())
  1257                     paramNames = List.nil();
  1258                 ListBuffer<VarSymbol> buf = new ListBuffer<VarSymbol>();
  1259                 List<Name> remaining = paramNames;
  1260                 // assert: remaining and paramNames are both empty or both
  1261                 // have same cardinality as type.getParameterTypes()
  1262                 int i = 0;
  1263                 for (Type t : type.getParameterTypes()) {
  1264                     Name paramName;
  1265                     if (remaining.isEmpty()) {
  1266                         // no names for any parameters available
  1267                         paramName = createArgName(i, paramNames);
  1268                     } else {
  1269                         paramName = remaining.head;
  1270                         remaining = remaining.tail;
  1271                         if (paramName.isEmpty()) {
  1272                             // no name for this specific parameter
  1273                             paramName = createArgName(i, paramNames);
  1276                     buf.append(new VarSymbol(PARAMETER, paramName, t, this));
  1277                     i++;
  1279                 params = buf.toList();
  1281             return params;
  1284         // Create a name for the argument at position 'index' that is not in
  1285         // the exclude list. In normal use, either no names will have been
  1286         // provided, in which case the exclude list is empty, or all the names
  1287         // will have been provided, in which case this method will not be called.
  1288         private Name createArgName(int index, List<Name> exclude) {
  1289             String prefix = "arg";
  1290             while (true) {
  1291                 Name argName = name.table.fromString(prefix + index);
  1292                 if (!exclude.contains(argName))
  1293                     return argName;
  1294                 prefix += "$";
  1298         public Symbol asMemberOf(Type site, Types types) {
  1299             return new MethodSymbol(flags_field, name, types.memberType(site, this), owner);
  1302         public ElementKind getKind() {
  1303             if (name == name.table.names.init)
  1304                 return ElementKind.CONSTRUCTOR;
  1305             else if (name == name.table.names.clinit)
  1306                 return ElementKind.STATIC_INIT;
  1307             else
  1308                 return ElementKind.METHOD;
  1311         public Attribute getDefaultValue() {
  1312             return defaultValue;
  1315         public List<VarSymbol> getParameters() {
  1316             return params();
  1319         public boolean isVarArgs() {
  1320             return (flags() & VARARGS) != 0;
  1323         public <R, P> R accept(ElementVisitor<R, P> v, P p) {
  1324             return v.visitExecutable(this, p);
  1327         public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
  1328             return v.visitMethodSymbol(this, p);
  1331         public Type getReturnType() {
  1332             return asType().getReturnType();
  1335         public List<Type> getThrownTypes() {
  1336             return asType().getThrownTypes();
  1340     /** A class for predefined operators.
  1341      */
  1342     public static class OperatorSymbol extends MethodSymbol {
  1344         public int opcode;
  1346         public OperatorSymbol(Name name, Type type, int opcode, Symbol owner) {
  1347             super(PUBLIC | STATIC, name, type, owner);
  1348             this.opcode = opcode;
  1351         public <R, P> R accept(Symbol.Visitor<R, P> v, P p) {
  1352             return v.visitOperatorSymbol(this, p);
  1356     /** Symbol completer interface.
  1357      */
  1358     public static interface Completer {
  1359         void complete(Symbol sym) throws CompletionFailure;
  1362     public static class CompletionFailure extends RuntimeException {
  1363         private static final long serialVersionUID = 0;
  1364         public Symbol sym;
  1366         /** A diagnostic object describing the failure
  1367          */
  1368         public JCDiagnostic diag;
  1370         /** A localized string describing the failure.
  1371          * @deprecated Use {@code getDetail()} or {@code getMessage()}
  1372          */
  1373         @Deprecated
  1374         public String errmsg;
  1376         public CompletionFailure(Symbol sym, String errmsg) {
  1377             this.sym = sym;
  1378             this.errmsg = errmsg;
  1379 //          this.printStackTrace();//DEBUG
  1382         public CompletionFailure(Symbol sym, JCDiagnostic diag) {
  1383             this.sym = sym;
  1384             this.diag = diag;
  1385 //          this.printStackTrace();//DEBUG
  1388         public JCDiagnostic getDiagnostic() {
  1389             return diag;
  1392         @Override
  1393         public String getMessage() {
  1394             if (diag != null)
  1395                 return diag.getMessage(null);
  1396             else
  1397                 return errmsg;
  1400         public Object getDetailValue() {
  1401             return (diag != null ? diag : errmsg);
  1404         @Override
  1405         public CompletionFailure initCause(Throwable cause) {
  1406             super.initCause(cause);
  1407             return this;
  1412     /**
  1413      * A visitor for symbols.  A visitor is used to implement operations
  1414      * (or relations) on symbols.  Most common operations on types are
  1415      * binary relations and this interface is designed for binary
  1416      * relations, that is, operations on the form
  1417      * Symbol&nbsp;&times;&nbsp;P&nbsp;&rarr;&nbsp;R.
  1418      * <!-- In plain text: Type x P -> R -->
  1420      * @param <R> the return type of the operation implemented by this
  1421      * visitor; use Void if no return type is needed.
  1422      * @param <P> the type of the second argument (the first being the
  1423      * symbol itself) of the operation implemented by this visitor; use
  1424      * Void if a second argument is not needed.
  1425      */
  1426     public interface Visitor<R,P> {
  1427         R visitClassSymbol(ClassSymbol s, P arg);
  1428         R visitMethodSymbol(MethodSymbol s, P arg);
  1429         R visitPackageSymbol(PackageSymbol s, P arg);
  1430         R visitOperatorSymbol(OperatorSymbol s, P arg);
  1431         R visitVarSymbol(VarSymbol s, P arg);
  1432         R visitTypeSymbol(TypeSymbol s, P arg);
  1433         R visitSymbol(Symbol s, P arg);

mercurial