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

Tue, 05 Aug 2008 12:54:40 +0100

author
mcimadamore
date
Tue, 05 Aug 2008 12:54:40 +0100
changeset 89
b6d5f53b3b29
parent 80
5c9cdeb740f2
child 92
d635feaf3747
permissions
-rw-r--r--

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

mercurial