src/share/classes/com/sun/tools/javac/comp/MemberEnter.java

Sat, 01 Dec 2007 00:00:00 +0000

author
duke
date
Sat, 01 Dec 2007 00:00:00 +0000
changeset 1
9a66ca7c79fa
child 8
38bd6375f37d
permissions
-rw-r--r--

Initial load

     1 /*
     2  * Copyright 2003-2006 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  */
    26 package com.sun.tools.javac.comp;
    28 import java.util.*;
    29 import java.util.Set;
    30 import javax.tools.JavaFileObject;
    32 import com.sun.tools.javac.code.*;
    33 import com.sun.tools.javac.jvm.*;
    34 import com.sun.tools.javac.tree.*;
    35 import com.sun.tools.javac.util.*;
    36 import com.sun.tools.javac.util.List;
    38 import com.sun.tools.javac.code.Type.*;
    39 import com.sun.tools.javac.code.Symbol.*;
    40 import com.sun.tools.javac.tree.JCTree.*;
    42 import static com.sun.tools.javac.code.Flags.*;
    43 import static com.sun.tools.javac.code.Kinds.*;
    44 import static com.sun.tools.javac.code.TypeTags.*;
    45 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    47 /** This is the second phase of Enter, in which classes are completed
    48  *  by entering their members into the class scope using
    49  *  MemberEnter.complete().  See Enter for an overview.
    50  *
    51  *  <p><b>This is NOT part of any API supported by Sun Microsystems.  If
    52  *  you write code that depends on this, you do so at your own risk.
    53  *  This code and its internal interfaces are subject to change or
    54  *  deletion without notice.</b>
    55  */
    56 public class MemberEnter extends JCTree.Visitor implements Completer {
    57     protected static final Context.Key<MemberEnter> memberEnterKey =
    58         new Context.Key<MemberEnter>();
    60     /** A switch to determine whether we check for package/class conflicts
    61      */
    62     final static boolean checkClash = true;
    64     private final Name.Table names;
    65     private final Enter enter;
    66     private final Log log;
    67     private final Check chk;
    68     private final Attr attr;
    69     private final Symtab syms;
    70     private final TreeMaker make;
    71     private final ClassReader reader;
    72     private final Todo todo;
    73     private final Annotate annotate;
    74     private final Types types;
    75     private final Target target;
    77     private final boolean skipAnnotations;
    79     public static MemberEnter instance(Context context) {
    80         MemberEnter instance = context.get(memberEnterKey);
    81         if (instance == null)
    82             instance = new MemberEnter(context);
    83         return instance;
    84     }
    86     protected MemberEnter(Context context) {
    87         context.put(memberEnterKey, this);
    88         names = Name.Table.instance(context);
    89         enter = Enter.instance(context);
    90         log = Log.instance(context);
    91         chk = Check.instance(context);
    92         attr = Attr.instance(context);
    93         syms = Symtab.instance(context);
    94         make = TreeMaker.instance(context);
    95         reader = ClassReader.instance(context);
    96         todo = Todo.instance(context);
    97         annotate = Annotate.instance(context);
    98         types = Types.instance(context);
    99         target = Target.instance(context);
   100         skipAnnotations =
   101             Options.instance(context).get("skipAnnotations") != null;
   102     }
   104     /** A queue for classes whose members still need to be entered into the
   105      *  symbol table.
   106      */
   107     ListBuffer<Env<AttrContext>> halfcompleted = new ListBuffer<Env<AttrContext>>();
   109     /** Set to true only when the first of a set of classes is
   110      *  processed from the halfcompleted queue.
   111      */
   112     boolean isFirst = true;
   114     /** A flag to disable completion from time to time during member
   115      *  enter, as we only need to look up types.  This avoids
   116      *  unnecessarily deep recursion.
   117      */
   118     boolean completionEnabled = true;
   120     /* ---------- Processing import clauses ----------------
   121      */
   123     /** Import all classes of a class or package on demand.
   124      *  @param pos           Position to be used for error reporting.
   125      *  @param tsym          The class or package the members of which are imported.
   126      *  @param toScope   The (import) scope in which imported classes
   127      *               are entered.
   128      */
   129     private void importAll(int pos,
   130                            final TypeSymbol tsym,
   131                            Env<AttrContext> env) {
   132         // Check that packages imported from exist (JLS ???).
   133         if (tsym.kind == PCK && tsym.members().elems == null && !tsym.exists()) {
   134             // If we can't find java.lang, exit immediately.
   135             if (((PackageSymbol)tsym).fullname.equals(names.java_lang)) {
   136                 JCDiagnostic msg = JCDiagnostic.fragment("fatal.err.no.java.lang");
   137                 throw new FatalError(msg);
   138             } else {
   139                 log.error(pos, "doesnt.exist", tsym);
   140             }
   141         }
   142         final Scope fromScope = tsym.members();
   143         final Scope toScope = env.toplevel.starImportScope;
   144         for (Scope.Entry e = fromScope.elems; e != null; e = e.sibling) {
   145             if (e.sym.kind == TYP && !toScope.includes(e.sym))
   146                 toScope.enter(e.sym, fromScope);
   147         }
   148     }
   150     /** Import all static members of a class or package on demand.
   151      *  @param pos           Position to be used for error reporting.
   152      *  @param tsym          The class or package the members of which are imported.
   153      *  @param toScope   The (import) scope in which imported classes
   154      *               are entered.
   155      */
   156     private void importStaticAll(int pos,
   157                                  final TypeSymbol tsym,
   158                                  Env<AttrContext> env) {
   159         final JavaFileObject sourcefile = env.toplevel.sourcefile;
   160         final Scope toScope = env.toplevel.starImportScope;
   161         final PackageSymbol packge = env.toplevel.packge;
   162         final TypeSymbol origin = tsym;
   164         // enter imported types immediately
   165         new Object() {
   166             Set<Symbol> processed = new HashSet<Symbol>();
   167             void importFrom(TypeSymbol tsym) {
   168                 if (tsym == null || !processed.add(tsym))
   169                     return;
   171                 // also import inherited names
   172                 importFrom(types.supertype(tsym.type).tsym);
   173                 for (Type t : types.interfaces(tsym.type))
   174                     importFrom(t.tsym);
   176                 final Scope fromScope = tsym.members();
   177                 for (Scope.Entry e = fromScope.elems; e != null; e = e.sibling) {
   178                     Symbol sym = e.sym;
   179                     if (sym.kind == TYP &&
   180                         (sym.flags() & STATIC) != 0 &&
   181                         staticImportAccessible(sym, packge) &&
   182                         sym.isMemberOf(origin, types) &&
   183                         !toScope.includes(sym))
   184                         toScope.enter(sym, fromScope, origin.members());
   185                 }
   186             }
   187         }.importFrom(tsym);
   189         // enter non-types before annotations that might use them
   190         annotate.earlier(new Annotate.Annotator() {
   191             Set<Symbol> processed = new HashSet<Symbol>();
   193             public String toString() {
   194                 return "import static " + tsym + ".*" + " in " + sourcefile;
   195             }
   196             void importFrom(TypeSymbol tsym) {
   197                 if (tsym == null || !processed.add(tsym))
   198                     return;
   200                 // also import inherited names
   201                 importFrom(types.supertype(tsym.type).tsym);
   202                 for (Type t : types.interfaces(tsym.type))
   203                     importFrom(t.tsym);
   205                 final Scope fromScope = tsym.members();
   206                 for (Scope.Entry e = fromScope.elems; e != null; e = e.sibling) {
   207                     Symbol sym = e.sym;
   208                     if (sym.isStatic() && sym.kind != TYP &&
   209                         staticImportAccessible(sym, packge) &&
   210                         !toScope.includes(sym) &&
   211                         sym.isMemberOf(origin, types)) {
   212                         toScope.enter(sym, fromScope, origin.members());
   213                     }
   214                 }
   215             }
   216             public void enterAnnotation() {
   217                 importFrom(tsym);
   218             }
   219         });
   220     }
   222     // is the sym accessible everywhere in packge?
   223     boolean staticImportAccessible(Symbol sym, PackageSymbol packge) {
   224         int flags = (int)(sym.flags() & AccessFlags);
   225         switch (flags) {
   226         default:
   227         case PUBLIC:
   228             return true;
   229         case PRIVATE:
   230             return false;
   231         case 0:
   232         case PROTECTED:
   233             return sym.packge() == packge;
   234         }
   235     }
   237     /** Import statics types of a given name.  Non-types are handled in Attr.
   238      *  @param pos           Position to be used for error reporting.
   239      *  @param tsym          The class from which the name is imported.
   240      *  @param name          The (simple) name being imported.
   241      *  @param env           The environment containing the named import
   242      *                  scope to add to.
   243      */
   244     private void importNamedStatic(final DiagnosticPosition pos,
   245                                    final TypeSymbol tsym,
   246                                    final Name name,
   247                                    final Env<AttrContext> env) {
   248         if (tsym.kind != TYP) {
   249             log.error(pos, "static.imp.only.classes.and.interfaces");
   250             return;
   251         }
   253         final Scope toScope = env.toplevel.namedImportScope;
   254         final PackageSymbol packge = env.toplevel.packge;
   255         final TypeSymbol origin = tsym;
   257         // enter imported types immediately
   258         new Object() {
   259             Set<Symbol> processed = new HashSet<Symbol>();
   260             void importFrom(TypeSymbol tsym) {
   261                 if (tsym == null || !processed.add(tsym))
   262                     return;
   264                 // also import inherited names
   265                 importFrom(types.supertype(tsym.type).tsym);
   266                 for (Type t : types.interfaces(tsym.type))
   267                     importFrom(t.tsym);
   269                 for (Scope.Entry e = tsym.members().lookup(name);
   270                      e.scope != null;
   271                      e = e.next()) {
   272                     Symbol sym = e.sym;
   273                     if (sym.isStatic() &&
   274                         sym.kind == TYP &&
   275                         staticImportAccessible(sym, packge) &&
   276                         sym.isMemberOf(origin, types) &&
   277                         chk.checkUniqueStaticImport(pos, sym, toScope))
   278                         toScope.enter(sym, sym.owner.members(), origin.members());
   279                 }
   280             }
   281         }.importFrom(tsym);
   283         // enter non-types before annotations that might use them
   284         annotate.earlier(new Annotate.Annotator() {
   285             Set<Symbol> processed = new HashSet<Symbol>();
   286             boolean found = false;
   288             public String toString() {
   289                 return "import static " + tsym + "." + name;
   290             }
   291             void importFrom(TypeSymbol tsym) {
   292                 if (tsym == null || !processed.add(tsym))
   293                     return;
   295                 // also import inherited names
   296                 importFrom(types.supertype(tsym.type).tsym);
   297                 for (Type t : types.interfaces(tsym.type))
   298                     importFrom(t.tsym);
   300                 for (Scope.Entry e = tsym.members().lookup(name);
   301                      e.scope != null;
   302                      e = e.next()) {
   303                     Symbol sym = e.sym;
   304                     if (sym.isStatic() &&
   305                         staticImportAccessible(sym, packge) &&
   306                         sym.isMemberOf(origin, types)) {
   307                         found = true;
   308                         if (sym.kind == MTH ||
   309                             sym.kind != TYP && chk.checkUniqueStaticImport(pos, sym, toScope))
   310                             toScope.enter(sym, sym.owner.members(), origin.members());
   311                     }
   312                 }
   313             }
   314             public void enterAnnotation() {
   315                 JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   316                 try {
   317                     importFrom(tsym);
   318                     if (!found) {
   319                         log.error(pos, "cant.resolve.location",
   320                                   JCDiagnostic.fragment("kindname.static"),
   321                                   name, "", "", Resolve.typeKindName(tsym.type),
   322                                   tsym.type);
   323                     }
   324                 } finally {
   325                     log.useSource(prev);
   326                 }
   327             }
   328         });
   329     }
   330     /** Import given class.
   331      *  @param pos           Position to be used for error reporting.
   332      *  @param tsym          The class to be imported.
   333      *  @param env           The environment containing the named import
   334      *                  scope to add to.
   335      */
   336     private void importNamed(DiagnosticPosition pos, Symbol tsym, Env<AttrContext> env) {
   337         if (tsym.kind == TYP &&
   338             chk.checkUniqueImport(pos, tsym, env.toplevel.namedImportScope))
   339             env.toplevel.namedImportScope.enter(tsym, tsym.owner.members());
   340     }
   342     /** Construct method type from method signature.
   343      *  @param typarams    The method's type parameters.
   344      *  @param params      The method's value parameters.
   345      *  @param res             The method's result type,
   346      *                 null if it is a constructor.
   347      *  @param thrown      The method's thrown exceptions.
   348      *  @param env             The method's (local) environment.
   349      */
   350     Type signature(List<JCTypeParameter> typarams,
   351                    List<JCVariableDecl> params,
   352                    JCTree res,
   353                    List<JCExpression> thrown,
   354                    Env<AttrContext> env) {
   356         // Enter and attribute type parameters.
   357         List<Type> tvars = enter.classEnter(typarams, env);
   358         attr.attribTypeVariables(typarams, env);
   360         // Enter and attribute value parameters.
   361         ListBuffer<Type> argbuf = new ListBuffer<Type>();
   362         for (List<JCVariableDecl> l = params; l.nonEmpty(); l = l.tail) {
   363             memberEnter(l.head, env);
   364             argbuf.append(l.head.vartype.type);
   365         }
   367         // Attribute result type, if one is given.
   368         Type restype = res == null ? syms.voidType : attr.attribType(res, env);
   370         // Attribute thrown exceptions.
   371         ListBuffer<Type> thrownbuf = new ListBuffer<Type>();
   372         for (List<JCExpression> l = thrown; l.nonEmpty(); l = l.tail) {
   373             Type exc = attr.attribType(l.head, env);
   374             if (exc.tag != TYPEVAR)
   375                 exc = chk.checkClassType(l.head.pos(), exc);
   376             thrownbuf.append(exc);
   377         }
   378         Type mtype = new MethodType(argbuf.toList(),
   379                                     restype,
   380                                     thrownbuf.toList(),
   381                                     syms.methodClass);
   382         return tvars.isEmpty() ? mtype : new ForAll(tvars, mtype);
   383     }
   385 /* ********************************************************************
   386  * Visitor methods for member enter
   387  *********************************************************************/
   389     /** Visitor argument: the current environment
   390      */
   391     protected Env<AttrContext> env;
   393     /** Enter field and method definitions and process import
   394      *  clauses, catching any completion failure exceptions.
   395      */
   396     protected void memberEnter(JCTree tree, Env<AttrContext> env) {
   397         Env<AttrContext> prevEnv = this.env;
   398         try {
   399             this.env = env;
   400             tree.accept(this);
   401         }  catch (CompletionFailure ex) {
   402             chk.completionError(tree.pos(), ex);
   403         } finally {
   404             this.env = prevEnv;
   405         }
   406     }
   408     /** Enter members from a list of trees.
   409      */
   410     void memberEnter(List<? extends JCTree> trees, Env<AttrContext> env) {
   411         for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
   412             memberEnter(l.head, env);
   413     }
   415     /** Enter members for a class.
   416      */
   417     void finishClass(JCClassDecl tree, Env<AttrContext> env) {
   418         if ((tree.mods.flags & Flags.ENUM) != 0 &&
   419             (types.supertype(tree.sym.type).tsym.flags() & Flags.ENUM) == 0) {
   420             addEnumMembers(tree, env);
   421         }
   422         memberEnter(tree.defs, env);
   423     }
   425     /** Add the implicit members for an enum type
   426      *  to the symbol table.
   427      */
   428     private void addEnumMembers(JCClassDecl tree, Env<AttrContext> env) {
   429         JCExpression valuesType = make.Type(new ArrayType(tree.sym.type, syms.arrayClass));
   431         // public static T[] values() { return ???; }
   432         JCMethodDecl values = make.
   433             MethodDef(make.Modifiers(Flags.PUBLIC|Flags.STATIC),
   434                       names.values,
   435                       valuesType,
   436                       List.<JCTypeParameter>nil(),
   437                       List.<JCVariableDecl>nil(),
   438                       List.<JCExpression>nil(), // thrown
   439                       null, //make.Block(0, Tree.emptyList.prepend(make.Return(make.Ident(names._null)))),
   440                       null);
   441         memberEnter(values, env);
   443         // public static T valueOf(String name) { return ???; }
   444         JCMethodDecl valueOf = make.
   445             MethodDef(make.Modifiers(Flags.PUBLIC|Flags.STATIC),
   446                       names.valueOf,
   447                       make.Type(tree.sym.type),
   448                       List.<JCTypeParameter>nil(),
   449                       List.of(make.VarDef(make.Modifiers(Flags.PARAMETER),
   450                                             names.fromString("name"),
   451                                             make.Type(syms.stringType), null)),
   452                       List.<JCExpression>nil(), // thrown
   453                       null, //make.Block(0, Tree.emptyList.prepend(make.Return(make.Ident(names._null)))),
   454                       null);
   455         memberEnter(valueOf, env);
   457         // the remaining members are for bootstrapping only
   458         if (!target.compilerBootstrap(tree.sym)) return;
   460         // public final int ordinal() { return ???; }
   461         JCMethodDecl ordinal = make.at(tree.pos).
   462             MethodDef(make.Modifiers(Flags.PUBLIC|Flags.FINAL),
   463                       names.ordinal,
   464                       make.Type(syms.intType),
   465                       List.<JCTypeParameter>nil(),
   466                       List.<JCVariableDecl>nil(),
   467                       List.<JCExpression>nil(),
   468                       null,
   469                       null);
   470         memberEnter(ordinal, env);
   472         // public final String name() { return ???; }
   473         JCMethodDecl name = make.
   474             MethodDef(make.Modifiers(Flags.PUBLIC|Flags.FINAL),
   475                       names._name,
   476                       make.Type(syms.stringType),
   477                       List.<JCTypeParameter>nil(),
   478                       List.<JCVariableDecl>nil(),
   479                       List.<JCExpression>nil(),
   480                       null,
   481                       null);
   482         memberEnter(name, env);
   484         // public int compareTo(E other) { return ???; }
   485         MethodSymbol compareTo = new
   486             MethodSymbol(Flags.PUBLIC,
   487                          names.compareTo,
   488                          new MethodType(List.of(tree.sym.type),
   489                                         syms.intType,
   490                                         List.<Type>nil(),
   491                                         syms.methodClass),
   492                          tree.sym);
   493         memberEnter(make.MethodDef(compareTo, null), env);
   494     }
   496     public void visitTopLevel(JCCompilationUnit tree) {
   497         if (tree.starImportScope.elems != null) {
   498             // we must have already processed this toplevel
   499             return;
   500         }
   502         // check that no class exists with same fully qualified name as
   503         // toplevel package
   504         if (checkClash && tree.pid != null) {
   505             Symbol p = tree.packge;
   506             while (p.owner != syms.rootPackage) {
   507                 p.owner.complete(); // enter all class members of p
   508                 if (syms.classes.get(p.getQualifiedName()) != null) {
   509                     log.error(tree.pos,
   510                               "pkg.clashes.with.class.of.same.name",
   511                               p);
   512                 }
   513                 p = p.owner;
   514             }
   515         }
   517         // process package annotations
   518         annotateLater(tree.packageAnnotations, env, tree.packge);
   520         // Import-on-demand java.lang.
   521         importAll(tree.pos, reader.enterPackage(names.java_lang), env);
   523         // Process all import clauses.
   524         memberEnter(tree.defs, env);
   525     }
   527     // process the non-static imports and the static imports of types.
   528     public void visitImport(JCImport tree) {
   529         JCTree imp = tree.qualid;
   530         Name name = TreeInfo.name(imp);
   531         TypeSymbol p;
   533         // Create a local environment pointing to this tree to disable
   534         // effects of other imports in Resolve.findGlobalType
   535         Env<AttrContext> localEnv = env.dup(tree);
   537         // Attribute qualifying package or class.
   538         JCFieldAccess s = (JCFieldAccess) imp;
   539         p = attr.
   540             attribTree(s.selected,
   541                        localEnv,
   542                        tree.staticImport ? TYP : (TYP | PCK),
   543                        Type.noType).tsym;
   544         if (name == names.asterisk) {
   545             // Import on demand.
   546             chk.checkCanonical(s.selected);
   547             if (tree.staticImport)
   548                 importStaticAll(tree.pos, p, env);
   549             else
   550                 importAll(tree.pos, p, env);
   551         } else {
   552             // Named type import.
   553             if (tree.staticImport) {
   554                 importNamedStatic(tree.pos(), p, name, localEnv);
   555                 chk.checkCanonical(s.selected);
   556             } else {
   557                 TypeSymbol c = attribImportType(imp, localEnv).tsym;
   558                 chk.checkCanonical(imp);
   559                 importNamed(tree.pos(), c, env);
   560             }
   561         }
   562     }
   564     public void visitMethodDef(JCMethodDecl tree) {
   565         Scope enclScope = enter.enterScope(env);
   566         MethodSymbol m = new MethodSymbol(0, tree.name, null, enclScope.owner);
   567         m.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, m, tree);
   568         tree.sym = m;
   569         Env<AttrContext> localEnv = methodEnv(tree, env);
   571         // Compute the method type
   572         m.type = signature(tree.typarams, tree.params,
   573                            tree.restype, tree.thrown,
   574                            localEnv);
   576         // Set m.params
   577         ListBuffer<VarSymbol> params = new ListBuffer<VarSymbol>();
   578         JCVariableDecl lastParam = null;
   579         for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
   580             JCVariableDecl param = lastParam = l.head;
   581             assert param.sym != null;
   582             params.append(param.sym);
   583         }
   584         m.params = params.toList();
   586         // mark the method varargs, if necessary
   587         if (lastParam != null && (lastParam.mods.flags & Flags.VARARGS) != 0)
   588             m.flags_field |= Flags.VARARGS;
   590         localEnv.info.scope.leave();
   591         if (chk.checkUnique(tree.pos(), m, enclScope)) {
   592             enclScope.enter(m);
   593         }
   594         annotateLater(tree.mods.annotations, localEnv, m);
   595         if (tree.defaultValue != null)
   596             annotateDefaultValueLater(tree.defaultValue, localEnv, m);
   597     }
   599     /** Create a fresh environment for method bodies.
   600      *  @param tree     The method definition.
   601      *  @param env      The environment current outside of the method definition.
   602      */
   603     Env<AttrContext> methodEnv(JCMethodDecl tree, Env<AttrContext> env) {
   604         Env<AttrContext> localEnv =
   605             env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
   606         localEnv.enclMethod = tree;
   607         localEnv.info.scope.owner = tree.sym;
   608         if ((tree.mods.flags & STATIC) != 0) localEnv.info.staticLevel++;
   609         return localEnv;
   610     }
   612     public void visitVarDef(JCVariableDecl tree) {
   613         Env<AttrContext> localEnv = env;
   614         if ((tree.mods.flags & STATIC) != 0 ||
   615             (env.info.scope.owner.flags() & INTERFACE) != 0) {
   616             localEnv = env.dup(tree, env.info.dup());
   617             localEnv.info.staticLevel++;
   618         }
   619         attr.attribType(tree.vartype, localEnv);
   620         Scope enclScope = enter.enterScope(env);
   621         VarSymbol v =
   622             new VarSymbol(0, tree.name, tree.vartype.type, enclScope.owner);
   623         v.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, v, tree);
   624         tree.sym = v;
   625         if (tree.init != null) {
   626             v.flags_field |= HASINIT;
   627             if ((v.flags_field & FINAL) != 0 && tree.init.getTag() != JCTree.NEWCLASS)
   628                 v.setLazyConstValue(initEnv(tree, env), log, attr, tree.init);
   629         }
   630         if (chk.checkUnique(tree.pos(), v, enclScope)) {
   631             chk.checkTransparentVar(tree.pos(), v, enclScope);
   632             enclScope.enter(v);
   633         }
   634         annotateLater(tree.mods.annotations, localEnv, v);
   635         v.pos = tree.pos;
   636     }
   638     /** Create a fresh environment for a variable's initializer.
   639      *  If the variable is a field, the owner of the environment's scope
   640      *  is be the variable itself, otherwise the owner is the method
   641      *  enclosing the variable definition.
   642      *
   643      *  @param tree     The variable definition.
   644      *  @param env      The environment current outside of the variable definition.
   645      */
   646     Env<AttrContext> initEnv(JCVariableDecl tree, Env<AttrContext> env) {
   647         Env<AttrContext> localEnv = env.dupto(new AttrContextEnv(tree, env.info.dup()));
   648         if (tree.sym.owner.kind == TYP) {
   649             localEnv.info.scope = new Scope.DelegatedScope(env.info.scope);
   650             localEnv.info.scope.owner = tree.sym;
   651         }
   652         if ((tree.mods.flags & STATIC) != 0 ||
   653             (env.enclClass.sym.flags() & INTERFACE) != 0)
   654             localEnv.info.staticLevel++;
   655         return localEnv;
   656     }
   658     /** Default member enter visitor method: do nothing
   659      */
   660     public void visitTree(JCTree tree) {
   661     }
   664     public void visitErroneous(JCErroneous tree) {
   665         memberEnter(tree.errs, env);
   666     }
   668     public Env<AttrContext> getMethodEnv(JCMethodDecl tree, Env<AttrContext> env) {
   669         Env<AttrContext> mEnv = methodEnv(tree, env);
   670         mEnv.info.lint = mEnv.info.lint.augment(tree.sym.attributes_field, tree.sym.flags());
   671         for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
   672             mEnv.info.scope.enterIfAbsent(l.head.type.tsym);
   673         for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail)
   674             mEnv.info.scope.enterIfAbsent(l.head.sym);
   675         return mEnv;
   676     }
   678     public Env<AttrContext> getInitEnv(JCVariableDecl tree, Env<AttrContext> env) {
   679         Env<AttrContext> iEnv = initEnv(tree, env);
   680         return iEnv;
   681     }
   683 /* ********************************************************************
   684  * Type completion
   685  *********************************************************************/
   687     Type attribImportType(JCTree tree, Env<AttrContext> env) {
   688         assert completionEnabled;
   689         try {
   690             // To prevent deep recursion, suppress completion of some
   691             // types.
   692             completionEnabled = false;
   693             return attr.attribType(tree, env);
   694         } finally {
   695             completionEnabled = true;
   696         }
   697     }
   699 /* ********************************************************************
   700  * Annotation processing
   701  *********************************************************************/
   703     /** Queue annotations for later processing. */
   704     void annotateLater(final List<JCAnnotation> annotations,
   705                        final Env<AttrContext> localEnv,
   706                        final Symbol s) {
   707         if (annotations.isEmpty()) return;
   708         if (s.kind != PCK) s.attributes_field = null; // mark it incomplete for now
   709         annotate.later(new Annotate.Annotator() {
   710                 public String toString() {
   711                     return "annotate " + annotations + " onto " + s + " in " + s.owner;
   712                 }
   713                 public void enterAnnotation() {
   714                     assert s.kind == PCK || s.attributes_field == null;
   715                     JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile);
   716                     try {
   717                         if (s.attributes_field != null &&
   718                             s.attributes_field.nonEmpty() &&
   719                             annotations.nonEmpty())
   720                             log.error(annotations.head.pos,
   721                                       "already.annotated",
   722                                       Resolve.kindName(s), s);
   723                         enterAnnotations(annotations, localEnv, s);
   724                     } finally {
   725                         log.useSource(prev);
   726                     }
   727                 }
   728             });
   729     }
   731     /**
   732      * Check if a list of annotations contains a reference to
   733      * java.lang.Deprecated.
   734      **/
   735     private boolean hasDeprecatedAnnotation(List<JCAnnotation> annotations) {
   736         for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
   737             JCAnnotation a = al.head;
   738             if (a.annotationType.type == syms.deprecatedType && a.args.isEmpty())
   739                 return true;
   740         }
   741         return false;
   742     }
   745     /** Enter a set of annotations. */
   746     private void enterAnnotations(List<JCAnnotation> annotations,
   747                           Env<AttrContext> env,
   748                           Symbol s) {
   749         ListBuffer<Attribute.Compound> buf =
   750             new ListBuffer<Attribute.Compound>();
   751         Set<TypeSymbol> annotated = new HashSet<TypeSymbol>();
   752         if (!skipAnnotations)
   753         for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
   754             JCAnnotation a = al.head;
   755             Attribute.Compound c = annotate.enterAnnotation(a,
   756                                                             syms.annotationType,
   757                                                             env);
   758             if (c == null) continue;
   759             buf.append(c);
   760             // Note: @Deprecated has no effect on local variables and parameters
   761             if (!c.type.isErroneous()
   762                 && s.owner.kind != MTH
   763                 && types.isSameType(c.type, syms.deprecatedType))
   764                 s.flags_field |= Flags.DEPRECATED;
   765             if (!annotated.add(a.type.tsym))
   766                 log.error(a.pos, "duplicate.annotation");
   767         }
   768         s.attributes_field = buf.toList();
   769     }
   771     /** Queue processing of an attribute default value. */
   772     void annotateDefaultValueLater(final JCExpression defaultValue,
   773                                    final Env<AttrContext> localEnv,
   774                                    final MethodSymbol m) {
   775         annotate.later(new Annotate.Annotator() {
   776                 public String toString() {
   777                     return "annotate " + m.owner + "." +
   778                         m + " default " + defaultValue;
   779                 }
   780                 public void enterAnnotation() {
   781                     JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile);
   782                     try {
   783                         enterDefaultValue(defaultValue, localEnv, m);
   784                     } finally {
   785                         log.useSource(prev);
   786                     }
   787                 }
   788             });
   789     }
   791     /** Enter a default value for an attribute method. */
   792     private void enterDefaultValue(final JCExpression defaultValue,
   793                                    final Env<AttrContext> localEnv,
   794                                    final MethodSymbol m) {
   795         m.defaultValue = annotate.enterAttributeValue(m.type.getReturnType(),
   796                                                       defaultValue,
   797                                                       localEnv);
   798     }
   800 /* ********************************************************************
   801  * Source completer
   802  *********************************************************************/
   804     /** Complete entering a class.
   805      *  @param sym         The symbol of the class to be completed.
   806      */
   807     public void complete(Symbol sym) throws CompletionFailure {
   808         // Suppress some (recursive) MemberEnter invocations
   809         if (!completionEnabled) {
   810             // Re-install same completer for next time around and return.
   811             assert (sym.flags() & Flags.COMPOUND) == 0;
   812             sym.completer = this;
   813             return;
   814         }
   816         ClassSymbol c = (ClassSymbol)sym;
   817         ClassType ct = (ClassType)c.type;
   818         Env<AttrContext> env = enter.typeEnvs.get(c);
   819         JCClassDecl tree = (JCClassDecl)env.tree;
   820         boolean wasFirst = isFirst;
   821         isFirst = false;
   823         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   824         try {
   825             // Save class environment for later member enter (2) processing.
   826             halfcompleted.append(env);
   828             // If this is a toplevel-class, make sure any preceding import
   829             // clauses have been seen.
   830             if (c.owner.kind == PCK) {
   831                 memberEnter(env.toplevel, env.enclosing(JCTree.TOPLEVEL));
   832                 todo.append(env);
   833             }
   835             // Mark class as not yet attributed.
   836             c.flags_field |= UNATTRIBUTED;
   838             if (c.owner.kind == TYP)
   839                 c.owner.complete();
   841             // create an environment for evaluating the base clauses
   842             Env<AttrContext> baseEnv = baseEnv(tree, env);
   844             // Determine supertype.
   845             Type supertype =
   846                 (tree.extending != null)
   847                 ? attr.attribBase(tree.extending, baseEnv, true, false, true)
   848                 : ((tree.mods.flags & Flags.ENUM) != 0 && !target.compilerBootstrap(c))
   849                 ? attr.attribBase(enumBase(tree.pos, c), baseEnv,
   850                                   true, false, false)
   851                 : (c.fullname == names.java_lang_Object)
   852                 ? Type.noType
   853                 : syms.objectType;
   854             ct.supertype_field = supertype;
   856             // Determine interfaces.
   857             ListBuffer<Type> interfaces = new ListBuffer<Type>();
   858             Set<Type> interfaceSet = new HashSet<Type>();
   859             List<JCExpression> interfaceTrees = tree.implementing;
   860             if ((tree.mods.flags & Flags.ENUM) != 0 && target.compilerBootstrap(c)) {
   861                 // add interface Comparable<T>
   862                 interfaceTrees =
   863                     interfaceTrees.prepend(make.Type(new ClassType(syms.comparableType.getEnclosingType(),
   864                                                                    List.of(c.type),
   865                                                                    syms.comparableType.tsym)));
   866                 // add interface Serializable
   867                 interfaceTrees =
   868                     interfaceTrees.prepend(make.Type(syms.serializableType));
   869             }
   870             for (JCExpression iface : interfaceTrees) {
   871                 Type i = attr.attribBase(iface, baseEnv, false, true, true);
   872                 if (i.tag == CLASS) {
   873                     interfaces.append(i);
   874                     chk.checkNotRepeated(iface.pos(), types.erasure(i), interfaceSet);
   875                 }
   876             }
   877             if ((c.flags_field & ANNOTATION) != 0)
   878                 ct.interfaces_field = List.of(syms.annotationType);
   879             else
   880                 ct.interfaces_field = interfaces.toList();
   882             if (c.fullname == names.java_lang_Object) {
   883                 if (tree.extending != null) {
   884                     chk.checkNonCyclic(tree.extending.pos(),
   885                                        supertype);
   886                     ct.supertype_field = Type.noType;
   887                 }
   888                 else if (tree.implementing.nonEmpty()) {
   889                     chk.checkNonCyclic(tree.implementing.head.pos(),
   890                                        ct.interfaces_field.head);
   891                     ct.interfaces_field = List.nil();
   892                 }
   893             }
   895             // Annotations.
   896             // In general, we cannot fully process annotations yet,  but we
   897             // can attribute the annotation types and then check to see if the
   898             // @Deprecated annotation is present.
   899             attr.attribAnnotationTypes(tree.mods.annotations, baseEnv);
   900             if (hasDeprecatedAnnotation(tree.mods.annotations))
   901                 c.flags_field |= DEPRECATED;
   902             annotateLater(tree.mods.annotations, baseEnv, c);
   904             attr.attribTypeVariables(tree.typarams, baseEnv);
   906             chk.checkNonCyclic(tree.pos(), c.type);
   908             // Add default constructor if needed.
   909             if ((c.flags() & INTERFACE) == 0 &&
   910                 !TreeInfo.hasConstructors(tree.defs)) {
   911                 List<Type> argtypes = List.nil();
   912                 List<Type> typarams = List.nil();
   913                 List<Type> thrown = List.nil();
   914                 long ctorFlags = 0;
   915                 boolean based = false;
   916                 if (c.name.len == 0) {
   917                     JCNewClass nc = (JCNewClass)env.next.tree;
   918                     if (nc.constructor != null) {
   919                         Type superConstrType = types.memberType(c.type,
   920                                                                 nc.constructor);
   921                         argtypes = superConstrType.getParameterTypes();
   922                         typarams = superConstrType.getTypeArguments();
   923                         ctorFlags = nc.constructor.flags() & VARARGS;
   924                         if (nc.encl != null) {
   925                             argtypes = argtypes.prepend(nc.encl.type);
   926                             based = true;
   927                         }
   928                         thrown = superConstrType.getThrownTypes();
   929                     }
   930                 }
   931                 JCTree constrDef = DefaultConstructor(make.at(tree.pos), c,
   932                                                     typarams, argtypes, thrown,
   933                                                     ctorFlags, based);
   934                 tree.defs = tree.defs.prepend(constrDef);
   935             }
   937             // If this is a class, enter symbols for this and super into
   938             // current scope.
   939             if ((c.flags_field & INTERFACE) == 0) {
   940                 VarSymbol thisSym =
   941                     new VarSymbol(FINAL | HASINIT, names._this, c.type, c);
   942                 thisSym.pos = Position.FIRSTPOS;
   943                 env.info.scope.enter(thisSym);
   944                 if (ct.supertype_field.tag == CLASS) {
   945                     VarSymbol superSym =
   946                         new VarSymbol(FINAL | HASINIT, names._super,
   947                                       ct.supertype_field, c);
   948                     superSym.pos = Position.FIRSTPOS;
   949                     env.info.scope.enter(superSym);
   950                 }
   951             }
   953             // check that no package exists with same fully qualified name,
   954             // but admit classes in the unnamed package which have the same
   955             // name as a top-level package.
   956             if (checkClash &&
   957                 c.owner.kind == PCK && c.owner != syms.unnamedPackage &&
   958                 reader.packageExists(c.fullname))
   959                 {
   960                     log.error(tree.pos, "clash.with.pkg.of.same.name", c);
   961                 }
   963         } catch (CompletionFailure ex) {
   964             chk.completionError(tree.pos(), ex);
   965         } finally {
   966             log.useSource(prev);
   967         }
   969         // Enter all member fields and methods of a set of half completed
   970         // classes in a second phase.
   971         if (wasFirst) {
   972             try {
   973                 while (halfcompleted.nonEmpty()) {
   974                     finish(halfcompleted.next());
   975                 }
   976             } finally {
   977                 isFirst = true;
   978             }
   980             // commit pending annotations
   981             annotate.flush();
   982         }
   983     }
   985     private Env<AttrContext> baseEnv(JCClassDecl tree, Env<AttrContext> env) {
   986         Scope typaramScope = new Scope(tree.sym);
   987         if (tree.typarams != null)
   988             for (List<JCTypeParameter> typarams = tree.typarams;
   989                  typarams.nonEmpty();
   990                  typarams = typarams.tail)
   991                 typaramScope.enter(typarams.head.type.tsym);
   992         Env<AttrContext> outer = env.outer; // the base clause can't see members of this class
   993         Env<AttrContext> localEnv = outer.dup(tree, outer.info.dup(typaramScope));
   994         localEnv.baseClause = true;
   995         localEnv.outer = outer;
   996         localEnv.info.isSelfCall = false;
   997         return localEnv;
   998     }
  1000     /** Enter member fields and methods of a class
  1001      *  @param env        the environment current for the class block.
  1002      */
  1003     private void finish(Env<AttrContext> env) {
  1004         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
  1005         try {
  1006             JCClassDecl tree = (JCClassDecl)env.tree;
  1007             finishClass(tree, env);
  1008         } finally {
  1009             log.useSource(prev);
  1013     /** Generate a base clause for an enum type.
  1014      *  @param pos              The position for trees and diagnostics, if any
  1015      *  @param c                The class symbol of the enum
  1016      */
  1017     private JCExpression enumBase(int pos, ClassSymbol c) {
  1018         JCExpression result = make.at(pos).
  1019             TypeApply(make.QualIdent(syms.enumSym),
  1020                       List.<JCExpression>of(make.Type(c.type)));
  1021         return result;
  1024 /* ***************************************************************************
  1025  * tree building
  1026  ****************************************************************************/
  1028     /** Generate default constructor for given class. For classes different
  1029      *  from java.lang.Object, this is:
  1031      *    c(argtype_0 x_0, ..., argtype_n x_n) throws thrown {
  1032      *      super(x_0, ..., x_n)
  1033      *    }
  1035      *  or, if based == true:
  1037      *    c(argtype_0 x_0, ..., argtype_n x_n) throws thrown {
  1038      *      x_0.super(x_1, ..., x_n)
  1039      *    }
  1041      *  @param make     The tree factory.
  1042      *  @param c        The class owning the default constructor.
  1043      *  @param argtypes The parameter types of the constructor.
  1044      *  @param thrown   The thrown exceptions of the constructor.
  1045      *  @param based    Is first parameter a this$n?
  1046      */
  1047     JCTree DefaultConstructor(TreeMaker make,
  1048                             ClassSymbol c,
  1049                             List<Type> typarams,
  1050                             List<Type> argtypes,
  1051                             List<Type> thrown,
  1052                             long flags,
  1053                             boolean based) {
  1054         List<JCVariableDecl> params = make.Params(argtypes, syms.noSymbol);
  1055         List<JCStatement> stats = List.nil();
  1056         if (c.type != syms.objectType)
  1057             stats = stats.prepend(SuperCall(make, typarams, params, based));
  1058         if ((c.flags() & ENUM) != 0 &&
  1059             (types.supertype(c.type).tsym == syms.enumSym ||
  1060              target.compilerBootstrap(c))) {
  1061             // constructors of true enums are private
  1062             flags = (flags & ~AccessFlags) | PRIVATE | GENERATEDCONSTR;
  1063         } else
  1064             flags |= (c.flags() & AccessFlags) | GENERATEDCONSTR;
  1065         if (c.name.len == 0) flags |= ANONCONSTR;
  1066         JCTree result = make.MethodDef(
  1067             make.Modifiers(flags),
  1068             names.init,
  1069             null,
  1070             make.TypeParams(typarams),
  1071             params,
  1072             make.Types(thrown),
  1073             make.Block(0, stats),
  1074             null);
  1075         return result;
  1078     /** Generate call to superclass constructor. This is:
  1080      *    super(id_0, ..., id_n)
  1082      * or, if based == true
  1084      *    id_0.super(id_1,...,id_n)
  1086      *  where id_0, ..., id_n are the names of the given parameters.
  1088      *  @param make    The tree factory
  1089      *  @param params  The parameters that need to be passed to super
  1090      *  @param typarams  The type parameters that need to be passed to super
  1091      *  @param based   Is first parameter a this$n?
  1092      */
  1093     JCExpressionStatement SuperCall(TreeMaker make,
  1094                    List<Type> typarams,
  1095                    List<JCVariableDecl> params,
  1096                    boolean based) {
  1097         JCExpression meth;
  1098         if (based) {
  1099             meth = make.Select(make.Ident(params.head), names._super);
  1100             params = params.tail;
  1101         } else {
  1102             meth = make.Ident(names._super);
  1104         List<JCExpression> typeargs = typarams.nonEmpty() ? make.Types(typarams) : null;
  1105         return make.Exec(make.Apply(typeargs, meth, make.Idents(params)));

mercurial