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

Thu, 24 Jul 2008 19:06:57 +0100

author
mcimadamore
date
Thu, 24 Jul 2008 19:06:57 +0100
changeset 80
5c9cdeb740f2
parent 54
eaf608c64fec
child 89
b6d5f53b3b29
permissions
-rw-r--r--

6717241: some diagnostic argument is prematurely converted into a String object
Summary: removed early toString() conversions applied to diagnostic arguments
Reviewed-by: jjg

     1 /*
     2  * Copyright 2003-2008 Sun Microsystems, Inc.  All Rights Reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Sun designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Sun in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
    22  * CA 95054 USA or visit www.sun.com if you need additional information or
    23  * have any questions.
    24  */
    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                                   KindName.STATIC,
   321                                   name, List.<Type>nil(), List.<Type>nil(),
   322                                   typeKindName(tsym.type),
   323                                   tsym.type);
   324                     }
   325                 } finally {
   326                     log.useSource(prev);
   327                 }
   328             }
   329         });
   330     }
   331     /** Import given class.
   332      *  @param pos           Position to be used for error reporting.
   333      *  @param tsym          The class to be imported.
   334      *  @param env           The environment containing the named import
   335      *                  scope to add to.
   336      */
   337     private void importNamed(DiagnosticPosition pos, Symbol tsym, Env<AttrContext> env) {
   338         if (tsym.kind == TYP &&
   339             chk.checkUniqueImport(pos, tsym, env.toplevel.namedImportScope))
   340             env.toplevel.namedImportScope.enter(tsym, tsym.owner.members());
   341     }
   343     /** Construct method type from method signature.
   344      *  @param typarams    The method's type parameters.
   345      *  @param params      The method's value parameters.
   346      *  @param res             The method's result type,
   347      *                 null if it is a constructor.
   348      *  @param thrown      The method's thrown exceptions.
   349      *  @param env             The method's (local) environment.
   350      */
   351     Type signature(List<JCTypeParameter> typarams,
   352                    List<JCVariableDecl> params,
   353                    JCTree res,
   354                    List<JCExpression> thrown,
   355                    Env<AttrContext> env) {
   357         // Enter and attribute type parameters.
   358         List<Type> tvars = enter.classEnter(typarams, env);
   359         attr.attribTypeVariables(typarams, env);
   361         // Enter and attribute value parameters.
   362         ListBuffer<Type> argbuf = new ListBuffer<Type>();
   363         for (List<JCVariableDecl> l = params; l.nonEmpty(); l = l.tail) {
   364             memberEnter(l.head, env);
   365             argbuf.append(l.head.vartype.type);
   366         }
   368         // Attribute result type, if one is given.
   369         Type restype = res == null ? syms.voidType : attr.attribType(res, env);
   371         // Attribute thrown exceptions.
   372         ListBuffer<Type> thrownbuf = new ListBuffer<Type>();
   373         for (List<JCExpression> l = thrown; l.nonEmpty(); l = l.tail) {
   374             Type exc = attr.attribType(l.head, env);
   375             if (exc.tag != TYPEVAR)
   376                 exc = chk.checkClassType(l.head.pos(), exc);
   377             thrownbuf.append(exc);
   378         }
   379         Type mtype = new MethodType(argbuf.toList(),
   380                                     restype,
   381                                     thrownbuf.toList(),
   382                                     syms.methodClass);
   383         return tvars.isEmpty() ? mtype : new ForAll(tvars, mtype);
   384     }
   386 /* ********************************************************************
   387  * Visitor methods for member enter
   388  *********************************************************************/
   390     /** Visitor argument: the current environment
   391      */
   392     protected Env<AttrContext> env;
   394     /** Enter field and method definitions and process import
   395      *  clauses, catching any completion failure exceptions.
   396      */
   397     protected void memberEnter(JCTree tree, Env<AttrContext> env) {
   398         Env<AttrContext> prevEnv = this.env;
   399         try {
   400             this.env = env;
   401             tree.accept(this);
   402         }  catch (CompletionFailure ex) {
   403             chk.completionError(tree.pos(), ex);
   404         } finally {
   405             this.env = prevEnv;
   406         }
   407     }
   409     /** Enter members from a list of trees.
   410      */
   411     void memberEnter(List<? extends JCTree> trees, Env<AttrContext> env) {
   412         for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
   413             memberEnter(l.head, env);
   414     }
   416     /** Enter members for a class.
   417      */
   418     void finishClass(JCClassDecl tree, Env<AttrContext> env) {
   419         if ((tree.mods.flags & Flags.ENUM) != 0 &&
   420             (types.supertype(tree.sym.type).tsym.flags() & Flags.ENUM) == 0) {
   421             addEnumMembers(tree, env);
   422         }
   423         memberEnter(tree.defs, env);
   424     }
   426     /** Add the implicit members for an enum type
   427      *  to the symbol table.
   428      */
   429     private void addEnumMembers(JCClassDecl tree, Env<AttrContext> env) {
   430         JCExpression valuesType = make.Type(new ArrayType(tree.sym.type, syms.arrayClass));
   432         // public static T[] values() { return ???; }
   433         JCMethodDecl values = make.
   434             MethodDef(make.Modifiers(Flags.PUBLIC|Flags.STATIC),
   435                       names.values,
   436                       valuesType,
   437                       List.<JCTypeParameter>nil(),
   438                       List.<JCVariableDecl>nil(),
   439                       List.<JCExpression>nil(), // thrown
   440                       null, //make.Block(0, Tree.emptyList.prepend(make.Return(make.Ident(names._null)))),
   441                       null);
   442         memberEnter(values, env);
   444         // public static T valueOf(String name) { return ???; }
   445         JCMethodDecl valueOf = make.
   446             MethodDef(make.Modifiers(Flags.PUBLIC|Flags.STATIC),
   447                       names.valueOf,
   448                       make.Type(tree.sym.type),
   449                       List.<JCTypeParameter>nil(),
   450                       List.of(make.VarDef(make.Modifiers(Flags.PARAMETER),
   451                                             names.fromString("name"),
   452                                             make.Type(syms.stringType), null)),
   453                       List.<JCExpression>nil(), // thrown
   454                       null, //make.Block(0, Tree.emptyList.prepend(make.Return(make.Ident(names._null)))),
   455                       null);
   456         memberEnter(valueOf, env);
   458         // the remaining members are for bootstrapping only
   459         if (!target.compilerBootstrap(tree.sym)) return;
   461         // public final int ordinal() { return ???; }
   462         JCMethodDecl ordinal = make.at(tree.pos).
   463             MethodDef(make.Modifiers(Flags.PUBLIC|Flags.FINAL),
   464                       names.ordinal,
   465                       make.Type(syms.intType),
   466                       List.<JCTypeParameter>nil(),
   467                       List.<JCVariableDecl>nil(),
   468                       List.<JCExpression>nil(),
   469                       null,
   470                       null);
   471         memberEnter(ordinal, env);
   473         // public final String name() { return ???; }
   474         JCMethodDecl name = make.
   475             MethodDef(make.Modifiers(Flags.PUBLIC|Flags.FINAL),
   476                       names._name,
   477                       make.Type(syms.stringType),
   478                       List.<JCTypeParameter>nil(),
   479                       List.<JCVariableDecl>nil(),
   480                       List.<JCExpression>nil(),
   481                       null,
   482                       null);
   483         memberEnter(name, env);
   485         // public int compareTo(E other) { return ???; }
   486         MethodSymbol compareTo = new
   487             MethodSymbol(Flags.PUBLIC,
   488                          names.compareTo,
   489                          new MethodType(List.of(tree.sym.type),
   490                                         syms.intType,
   491                                         List.<Type>nil(),
   492                                         syms.methodClass),
   493                          tree.sym);
   494         memberEnter(make.MethodDef(compareTo, null), env);
   495     }
   497     public void visitTopLevel(JCCompilationUnit tree) {
   498         if (tree.starImportScope.elems != null) {
   499             // we must have already processed this toplevel
   500             return;
   501         }
   503         // check that no class exists with same fully qualified name as
   504         // toplevel package
   505         if (checkClash && tree.pid != null) {
   506             Symbol p = tree.packge;
   507             while (p.owner != syms.rootPackage) {
   508                 p.owner.complete(); // enter all class members of p
   509                 if (syms.classes.get(p.getQualifiedName()) != null) {
   510                     log.error(tree.pos,
   511                               "pkg.clashes.with.class.of.same.name",
   512                               p);
   513                 }
   514                 p = p.owner;
   515             }
   516         }
   518         // process package annotations
   519         annotateLater(tree.packageAnnotations, env, tree.packge);
   521         // Import-on-demand java.lang.
   522         importAll(tree.pos, reader.enterPackage(names.java_lang), env);
   524         // Process all import clauses.
   525         memberEnter(tree.defs, env);
   526     }
   528     // process the non-static imports and the static imports of types.
   529     public void visitImport(JCImport tree) {
   530         JCTree imp = tree.qualid;
   531         Name name = TreeInfo.name(imp);
   532         TypeSymbol p;
   534         // Create a local environment pointing to this tree to disable
   535         // effects of other imports in Resolve.findGlobalType
   536         Env<AttrContext> localEnv = env.dup(tree);
   538         // Attribute qualifying package or class.
   539         JCFieldAccess s = (JCFieldAccess) imp;
   540         p = attr.
   541             attribTree(s.selected,
   542                        localEnv,
   543                        tree.staticImport ? TYP : (TYP | PCK),
   544                        Type.noType).tsym;
   545         if (name == names.asterisk) {
   546             // Import on demand.
   547             chk.checkCanonical(s.selected);
   548             if (tree.staticImport)
   549                 importStaticAll(tree.pos, p, env);
   550             else
   551                 importAll(tree.pos, p, env);
   552         } else {
   553             // Named type import.
   554             if (tree.staticImport) {
   555                 importNamedStatic(tree.pos(), p, name, localEnv);
   556                 chk.checkCanonical(s.selected);
   557             } else {
   558                 TypeSymbol c = attribImportType(imp, localEnv).tsym;
   559                 chk.checkCanonical(imp);
   560                 importNamed(tree.pos(), c, env);
   561             }
   562         }
   563     }
   565     public void visitMethodDef(JCMethodDecl tree) {
   566         Scope enclScope = enter.enterScope(env);
   567         MethodSymbol m = new MethodSymbol(0, tree.name, null, enclScope.owner);
   568         m.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, m, tree);
   569         tree.sym = m;
   570         Env<AttrContext> localEnv = methodEnv(tree, env);
   572         // Compute the method type
   573         m.type = signature(tree.typarams, tree.params,
   574                            tree.restype, tree.thrown,
   575                            localEnv);
   577         // Set m.params
   578         ListBuffer<VarSymbol> params = new ListBuffer<VarSymbol>();
   579         JCVariableDecl lastParam = null;
   580         for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
   581             JCVariableDecl param = lastParam = l.head;
   582             assert param.sym != null;
   583             params.append(param.sym);
   584         }
   585         m.params = params.toList();
   587         // mark the method varargs, if necessary
   588         if (lastParam != null && (lastParam.mods.flags & Flags.VARARGS) != 0)
   589             m.flags_field |= Flags.VARARGS;
   591         localEnv.info.scope.leave();
   592         if (chk.checkUnique(tree.pos(), m, enclScope)) {
   593             enclScope.enter(m);
   594         }
   595         annotateLater(tree.mods.annotations, localEnv, m);
   596         if (tree.defaultValue != null)
   597             annotateDefaultValueLater(tree.defaultValue, localEnv, m);
   598     }
   600     /** Create a fresh environment for method bodies.
   601      *  @param tree     The method definition.
   602      *  @param env      The environment current outside of the method definition.
   603      */
   604     Env<AttrContext> methodEnv(JCMethodDecl tree, Env<AttrContext> env) {
   605         Env<AttrContext> localEnv =
   606             env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
   607         localEnv.enclMethod = tree;
   608         localEnv.info.scope.owner = tree.sym;
   609         if ((tree.mods.flags & STATIC) != 0) localEnv.info.staticLevel++;
   610         return localEnv;
   611     }
   613     public void visitVarDef(JCVariableDecl tree) {
   614         Env<AttrContext> localEnv = env;
   615         if ((tree.mods.flags & STATIC) != 0 ||
   616             (env.info.scope.owner.flags() & INTERFACE) != 0) {
   617             localEnv = env.dup(tree, env.info.dup());
   618             localEnv.info.staticLevel++;
   619         }
   620         attr.attribType(tree.vartype, localEnv);
   621         Scope enclScope = enter.enterScope(env);
   622         VarSymbol v =
   623             new VarSymbol(0, tree.name, tree.vartype.type, enclScope.owner);
   624         v.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, v, tree);
   625         tree.sym = v;
   626         if (tree.init != null) {
   627             v.flags_field |= HASINIT;
   628             if ((v.flags_field & FINAL) != 0 && tree.init.getTag() != JCTree.NEWCLASS)
   629                 v.setLazyConstValue(initEnv(tree, env), log, attr, tree.init);
   630         }
   631         if (chk.checkUnique(tree.pos(), v, enclScope)) {
   632             chk.checkTransparentVar(tree.pos(), v, enclScope);
   633             enclScope.enter(v);
   634         }
   635         annotateLater(tree.mods.annotations, localEnv, v);
   636         v.pos = tree.pos;
   637     }
   639     /** Create a fresh environment for a variable's initializer.
   640      *  If the variable is a field, the owner of the environment's scope
   641      *  is be the variable itself, otherwise the owner is the method
   642      *  enclosing the variable definition.
   643      *
   644      *  @param tree     The variable definition.
   645      *  @param env      The environment current outside of the variable definition.
   646      */
   647     Env<AttrContext> initEnv(JCVariableDecl tree, Env<AttrContext> env) {
   648         Env<AttrContext> localEnv = env.dupto(new AttrContextEnv(tree, env.info.dup()));
   649         if (tree.sym.owner.kind == TYP) {
   650             localEnv.info.scope = new Scope.DelegatedScope(env.info.scope);
   651             localEnv.info.scope.owner = tree.sym;
   652         }
   653         if ((tree.mods.flags & STATIC) != 0 ||
   654             (env.enclClass.sym.flags() & INTERFACE) != 0)
   655             localEnv.info.staticLevel++;
   656         return localEnv;
   657     }
   659     /** Default member enter visitor method: do nothing
   660      */
   661     public void visitTree(JCTree tree) {
   662     }
   665     public void visitErroneous(JCErroneous tree) {
   666         memberEnter(tree.errs, env);
   667     }
   669     public Env<AttrContext> getMethodEnv(JCMethodDecl tree, Env<AttrContext> env) {
   670         Env<AttrContext> mEnv = methodEnv(tree, env);
   671         mEnv.info.lint = mEnv.info.lint.augment(tree.sym.attributes_field, tree.sym.flags());
   672         for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
   673             mEnv.info.scope.enterIfAbsent(l.head.type.tsym);
   674         for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail)
   675             mEnv.info.scope.enterIfAbsent(l.head.sym);
   676         return mEnv;
   677     }
   679     public Env<AttrContext> getInitEnv(JCVariableDecl tree, Env<AttrContext> env) {
   680         Env<AttrContext> iEnv = initEnv(tree, env);
   681         return iEnv;
   682     }
   684 /* ********************************************************************
   685  * Type completion
   686  *********************************************************************/
   688     Type attribImportType(JCTree tree, Env<AttrContext> env) {
   689         assert completionEnabled;
   690         try {
   691             // To prevent deep recursion, suppress completion of some
   692             // types.
   693             completionEnabled = false;
   694             return attr.attribType(tree, env);
   695         } finally {
   696             completionEnabled = true;
   697         }
   698     }
   700 /* ********************************************************************
   701  * Annotation processing
   702  *********************************************************************/
   704     /** Queue annotations for later processing. */
   705     void annotateLater(final List<JCAnnotation> annotations,
   706                        final Env<AttrContext> localEnv,
   707                        final Symbol s) {
   708         if (annotations.isEmpty()) return;
   709         if (s.kind != PCK) s.attributes_field = null; // mark it incomplete for now
   710         annotate.later(new Annotate.Annotator() {
   711                 public String toString() {
   712                     return "annotate " + annotations + " onto " + s + " in " + s.owner;
   713                 }
   714                 public void enterAnnotation() {
   715                     assert s.kind == PCK || s.attributes_field == null;
   716                     JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile);
   717                     try {
   718                         if (s.attributes_field != null &&
   719                             s.attributes_field.nonEmpty() &&
   720                             annotations.nonEmpty())
   721                             log.error(annotations.head.pos,
   722                                       "already.annotated",
   723                                       kindName(s), s);
   724                         enterAnnotations(annotations, localEnv, s);
   725                     } finally {
   726                         log.useSource(prev);
   727                     }
   728                 }
   729             });
   730     }
   732     /**
   733      * Check if a list of annotations contains a reference to
   734      * java.lang.Deprecated.
   735      **/
   736     private boolean hasDeprecatedAnnotation(List<JCAnnotation> annotations) {
   737         for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
   738             JCAnnotation a = al.head;
   739             if (a.annotationType.type == syms.deprecatedType && a.args.isEmpty())
   740                 return true;
   741         }
   742         return false;
   743     }
   746     /** Enter a set of annotations. */
   747     private void enterAnnotations(List<JCAnnotation> annotations,
   748                           Env<AttrContext> env,
   749                           Symbol s) {
   750         ListBuffer<Attribute.Compound> buf =
   751             new ListBuffer<Attribute.Compound>();
   752         Set<TypeSymbol> annotated = new HashSet<TypeSymbol>();
   753         if (!skipAnnotations)
   754         for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
   755             JCAnnotation a = al.head;
   756             Attribute.Compound c = annotate.enterAnnotation(a,
   757                                                             syms.annotationType,
   758                                                             env);
   759             if (c == null) continue;
   760             buf.append(c);
   761             // Note: @Deprecated has no effect on local variables and parameters
   762             if (!c.type.isErroneous()
   763                 && s.owner.kind != MTH
   764                 && types.isSameType(c.type, syms.deprecatedType))
   765                 s.flags_field |= Flags.DEPRECATED;
   766             if (!annotated.add(a.type.tsym))
   767                 log.error(a.pos, "duplicate.annotation");
   768         }
   769         s.attributes_field = buf.toList();
   770     }
   772     /** Queue processing of an attribute default value. */
   773     void annotateDefaultValueLater(final JCExpression defaultValue,
   774                                    final Env<AttrContext> localEnv,
   775                                    final MethodSymbol m) {
   776         annotate.later(new Annotate.Annotator() {
   777                 public String toString() {
   778                     return "annotate " + m.owner + "." +
   779                         m + " default " + defaultValue;
   780                 }
   781                 public void enterAnnotation() {
   782                     JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile);
   783                     try {
   784                         enterDefaultValue(defaultValue, localEnv, m);
   785                     } finally {
   786                         log.useSource(prev);
   787                     }
   788                 }
   789             });
   790     }
   792     /** Enter a default value for an attribute method. */
   793     private void enterDefaultValue(final JCExpression defaultValue,
   794                                    final Env<AttrContext> localEnv,
   795                                    final MethodSymbol m) {
   796         m.defaultValue = annotate.enterAttributeValue(m.type.getReturnType(),
   797                                                       defaultValue,
   798                                                       localEnv);
   799     }
   801 /* ********************************************************************
   802  * Source completer
   803  *********************************************************************/
   805     /** Complete entering a class.
   806      *  @param sym         The symbol of the class to be completed.
   807      */
   808     public void complete(Symbol sym) throws CompletionFailure {
   809         // Suppress some (recursive) MemberEnter invocations
   810         if (!completionEnabled) {
   811             // Re-install same completer for next time around and return.
   812             assert (sym.flags() & Flags.COMPOUND) == 0;
   813             sym.completer = this;
   814             return;
   815         }
   817         ClassSymbol c = (ClassSymbol)sym;
   818         ClassType ct = (ClassType)c.type;
   819         Env<AttrContext> env = enter.typeEnvs.get(c);
   820         JCClassDecl tree = (JCClassDecl)env.tree;
   821         boolean wasFirst = isFirst;
   822         isFirst = false;
   824         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   825         try {
   826             // Save class environment for later member enter (2) processing.
   827             halfcompleted.append(env);
   829             // If this is a toplevel-class, make sure any preceding import
   830             // clauses have been seen.
   831             if (c.owner.kind == PCK) {
   832                 memberEnter(env.toplevel, env.enclosing(JCTree.TOPLEVEL));
   833                 todo.append(env);
   834             }
   836             // Mark class as not yet attributed.
   837             c.flags_field |= UNATTRIBUTED;
   839             if (c.owner.kind == TYP)
   840                 c.owner.complete();
   842             // create an environment for evaluating the base clauses
   843             Env<AttrContext> baseEnv = baseEnv(tree, env);
   845             // Determine supertype.
   846             Type supertype =
   847                 (tree.extending != null)
   848                 ? attr.attribBase(tree.extending, baseEnv, true, false, true)
   849                 : ((tree.mods.flags & Flags.ENUM) != 0 && !target.compilerBootstrap(c))
   850                 ? attr.attribBase(enumBase(tree.pos, c), baseEnv,
   851                                   true, false, false)
   852                 : (c.fullname == names.java_lang_Object)
   853                 ? Type.noType
   854                 : syms.objectType;
   855             ct.supertype_field = supertype;
   857             // Determine interfaces.
   858             ListBuffer<Type> interfaces = new ListBuffer<Type>();
   859             Set<Type> interfaceSet = new HashSet<Type>();
   860             List<JCExpression> interfaceTrees = tree.implementing;
   861             if ((tree.mods.flags & Flags.ENUM) != 0 && target.compilerBootstrap(c)) {
   862                 // add interface Comparable<T>
   863                 interfaceTrees =
   864                     interfaceTrees.prepend(make.Type(new ClassType(syms.comparableType.getEnclosingType(),
   865                                                                    List.of(c.type),
   866                                                                    syms.comparableType.tsym)));
   867                 // add interface Serializable
   868                 interfaceTrees =
   869                     interfaceTrees.prepend(make.Type(syms.serializableType));
   870             }
   871             for (JCExpression iface : interfaceTrees) {
   872                 Type i = attr.attribBase(iface, baseEnv, false, true, true);
   873                 if (i.tag == CLASS) {
   874                     interfaces.append(i);
   875                     chk.checkNotRepeated(iface.pos(), types.erasure(i), interfaceSet);
   876                 }
   877             }
   878             if ((c.flags_field & ANNOTATION) != 0)
   879                 ct.interfaces_field = List.of(syms.annotationType);
   880             else
   881                 ct.interfaces_field = interfaces.toList();
   883             if (c.fullname == names.java_lang_Object) {
   884                 if (tree.extending != null) {
   885                     chk.checkNonCyclic(tree.extending.pos(),
   886                                        supertype);
   887                     ct.supertype_field = Type.noType;
   888                 }
   889                 else if (tree.implementing.nonEmpty()) {
   890                     chk.checkNonCyclic(tree.implementing.head.pos(),
   891                                        ct.interfaces_field.head);
   892                     ct.interfaces_field = List.nil();
   893                 }
   894             }
   896             // Annotations.
   897             // In general, we cannot fully process annotations yet,  but we
   898             // can attribute the annotation types and then check to see if the
   899             // @Deprecated annotation is present.
   900             attr.attribAnnotationTypes(tree.mods.annotations, baseEnv);
   901             if (hasDeprecatedAnnotation(tree.mods.annotations))
   902                 c.flags_field |= DEPRECATED;
   903             annotateLater(tree.mods.annotations, baseEnv, c);
   905             chk.checkNonCyclic(tree.pos(), c.type);
   907             attr.attribTypeVariables(tree.typarams, baseEnv);
   909             // Add default constructor if needed.
   910             if ((c.flags() & INTERFACE) == 0 &&
   911                 !TreeInfo.hasConstructors(tree.defs)) {
   912                 List<Type> argtypes = List.nil();
   913                 List<Type> typarams = List.nil();
   914                 List<Type> thrown = List.nil();
   915                 long ctorFlags = 0;
   916                 boolean based = false;
   917                 if (c.name.len == 0) {
   918                     JCNewClass nc = (JCNewClass)env.next.tree;
   919                     if (nc.constructor != null) {
   920                         Type superConstrType = types.memberType(c.type,
   921                                                                 nc.constructor);
   922                         argtypes = superConstrType.getParameterTypes();
   923                         typarams = superConstrType.getTypeArguments();
   924                         ctorFlags = nc.constructor.flags() & VARARGS;
   925                         if (nc.encl != null) {
   926                             argtypes = argtypes.prepend(nc.encl.type);
   927                             based = true;
   928                         }
   929                         thrown = superConstrType.getThrownTypes();
   930                     }
   931                 }
   932                 JCTree constrDef = DefaultConstructor(make.at(tree.pos), c,
   933                                                     typarams, argtypes, thrown,
   934                                                     ctorFlags, based);
   935                 tree.defs = tree.defs.prepend(constrDef);
   936             }
   938             // If this is a class, enter symbols for this and super into
   939             // current scope.
   940             if ((c.flags_field & INTERFACE) == 0) {
   941                 VarSymbol thisSym =
   942                     new VarSymbol(FINAL | HASINIT, names._this, c.type, c);
   943                 thisSym.pos = Position.FIRSTPOS;
   944                 env.info.scope.enter(thisSym);
   945                 if (ct.supertype_field.tag == CLASS) {
   946                     VarSymbol superSym =
   947                         new VarSymbol(FINAL | HASINIT, names._super,
   948                                       ct.supertype_field, c);
   949                     superSym.pos = Position.FIRSTPOS;
   950                     env.info.scope.enter(superSym);
   951                 }
   952             }
   954             // check that no package exists with same fully qualified name,
   955             // but admit classes in the unnamed package which have the same
   956             // name as a top-level package.
   957             if (checkClash &&
   958                 c.owner.kind == PCK && c.owner != syms.unnamedPackage &&
   959                 reader.packageExists(c.fullname))
   960                 {
   961                     log.error(tree.pos, "clash.with.pkg.of.same.name", c);
   962                 }
   964         } catch (CompletionFailure ex) {
   965             chk.completionError(tree.pos(), ex);
   966         } finally {
   967             log.useSource(prev);
   968         }
   970         // Enter all member fields and methods of a set of half completed
   971         // classes in a second phase.
   972         if (wasFirst) {
   973             try {
   974                 while (halfcompleted.nonEmpty()) {
   975                     finish(halfcompleted.next());
   976                 }
   977             } finally {
   978                 isFirst = true;
   979             }
   981             // commit pending annotations
   982             annotate.flush();
   983         }
   984     }
   986     private Env<AttrContext> baseEnv(JCClassDecl tree, Env<AttrContext> env) {
   987         Scope typaramScope = new Scope(tree.sym);
   988         if (tree.typarams != null)
   989             for (List<JCTypeParameter> typarams = tree.typarams;
   990                  typarams.nonEmpty();
   991                  typarams = typarams.tail)
   992                 typaramScope.enter(typarams.head.type.tsym);
   993         Env<AttrContext> outer = env.outer; // the base clause can't see members of this class
   994         Env<AttrContext> localEnv = outer.dup(tree, outer.info.dup(typaramScope));
   995         localEnv.baseClause = true;
   996         localEnv.outer = outer;
   997         localEnv.info.isSelfCall = false;
   998         return localEnv;
   999     }
  1001     /** Enter member fields and methods of a class
  1002      *  @param env        the environment current for the class block.
  1003      */
  1004     private void finish(Env<AttrContext> env) {
  1005         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
  1006         try {
  1007             JCClassDecl tree = (JCClassDecl)env.tree;
  1008             finishClass(tree, env);
  1009         } finally {
  1010             log.useSource(prev);
  1014     /** Generate a base clause for an enum type.
  1015      *  @param pos              The position for trees and diagnostics, if any
  1016      *  @param c                The class symbol of the enum
  1017      */
  1018     private JCExpression enumBase(int pos, ClassSymbol c) {
  1019         JCExpression result = make.at(pos).
  1020             TypeApply(make.QualIdent(syms.enumSym),
  1021                       List.<JCExpression>of(make.Type(c.type)));
  1022         return result;
  1025 /* ***************************************************************************
  1026  * tree building
  1027  ****************************************************************************/
  1029     /** Generate default constructor for given class. For classes different
  1030      *  from java.lang.Object, this is:
  1032      *    c(argtype_0 x_0, ..., argtype_n x_n) throws thrown {
  1033      *      super(x_0, ..., x_n)
  1034      *    }
  1036      *  or, if based == true:
  1038      *    c(argtype_0 x_0, ..., argtype_n x_n) throws thrown {
  1039      *      x_0.super(x_1, ..., x_n)
  1040      *    }
  1042      *  @param make     The tree factory.
  1043      *  @param c        The class owning the default constructor.
  1044      *  @param argtypes The parameter types of the constructor.
  1045      *  @param thrown   The thrown exceptions of the constructor.
  1046      *  @param based    Is first parameter a this$n?
  1047      */
  1048     JCTree DefaultConstructor(TreeMaker make,
  1049                             ClassSymbol c,
  1050                             List<Type> typarams,
  1051                             List<Type> argtypes,
  1052                             List<Type> thrown,
  1053                             long flags,
  1054                             boolean based) {
  1055         List<JCVariableDecl> params = make.Params(argtypes, syms.noSymbol);
  1056         List<JCStatement> stats = List.nil();
  1057         if (c.type != syms.objectType)
  1058             stats = stats.prepend(SuperCall(make, typarams, params, based));
  1059         if ((c.flags() & ENUM) != 0 &&
  1060             (types.supertype(c.type).tsym == syms.enumSym ||
  1061              target.compilerBootstrap(c))) {
  1062             // constructors of true enums are private
  1063             flags = (flags & ~AccessFlags) | PRIVATE | GENERATEDCONSTR;
  1064         } else
  1065             flags |= (c.flags() & AccessFlags) | GENERATEDCONSTR;
  1066         if (c.name.len == 0) flags |= ANONCONSTR;
  1067         JCTree result = make.MethodDef(
  1068             make.Modifiers(flags),
  1069             names.init,
  1070             null,
  1071             make.TypeParams(typarams),
  1072             params,
  1073             make.Types(thrown),
  1074             make.Block(0, stats),
  1075             null);
  1076         return result;
  1079     /** Generate call to superclass constructor. This is:
  1081      *    super(id_0, ..., id_n)
  1083      * or, if based == true
  1085      *    id_0.super(id_1,...,id_n)
  1087      *  where id_0, ..., id_n are the names of the given parameters.
  1089      *  @param make    The tree factory
  1090      *  @param params  The parameters that need to be passed to super
  1091      *  @param typarams  The type parameters that need to be passed to super
  1092      *  @param based   Is first parameter a this$n?
  1093      */
  1094     JCExpressionStatement SuperCall(TreeMaker make,
  1095                    List<Type> typarams,
  1096                    List<JCVariableDecl> params,
  1097                    boolean based) {
  1098         JCExpression meth;
  1099         if (based) {
  1100             meth = make.Select(make.Ident(params.head), names._super);
  1101             params = params.tail;
  1102         } else {
  1103             meth = make.Ident(names._super);
  1105         List<JCExpression> typeargs = typarams.nonEmpty() ? make.Types(typarams) : null;
  1106         return make.Exec(make.Apply(typeargs, meth, make.Idents(params)));

mercurial