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

Mon, 06 Dec 2010 11:51:02 +0000

author
mcimadamore
date
Mon, 06 Dec 2010 11:51:02 +0000
changeset 775
536ee9f126b1
parent 767
7e3e9f6d013f
child 795
7b99f98b3035
permissions
-rw-r--r--

5088429: varargs overloading problem
Summary: compiler implementation for overload resolution w/ varargs method does not match JLS
Reviewed-by: jjg

     1 /*
     2  * Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    26 package com.sun.tools.javac.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 supported API.
    52  *  If 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 Names 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 Scope.ScopeCounter scopeCounter;
    71     private final TreeMaker make;
    72     private final ClassReader reader;
    73     private final Todo todo;
    74     private final Annotate annotate;
    75     private final Types types;
    76     private final JCDiagnostic.Factory diags;
    77     private final Target target;
    79     private final boolean skipAnnotations;
    81     public static MemberEnter instance(Context context) {
    82         MemberEnter instance = context.get(memberEnterKey);
    83         if (instance == null)
    84             instance = new MemberEnter(context);
    85         return instance;
    86     }
    88     protected MemberEnter(Context context) {
    89         context.put(memberEnterKey, this);
    90         names = Names.instance(context);
    91         enter = Enter.instance(context);
    92         log = Log.instance(context);
    93         chk = Check.instance(context);
    94         attr = Attr.instance(context);
    95         syms = Symtab.instance(context);
    96         scopeCounter = Scope.ScopeCounter.instance(context);
    97         make = TreeMaker.instance(context);
    98         reader = ClassReader.instance(context);
    99         todo = Todo.instance(context);
   100         annotate = Annotate.instance(context);
   101         types = Types.instance(context);
   102         diags = JCDiagnostic.Factory.instance(context);
   103         target = Target.instance(context);
   104         Options options = Options.instance(context);
   105         skipAnnotations = options.isSet("skipAnnotations");
   106     }
   108     /** A queue for classes whose members still need to be entered into the
   109      *  symbol table.
   110      */
   111     ListBuffer<Env<AttrContext>> halfcompleted = new ListBuffer<Env<AttrContext>>();
   113     /** Set to true only when the first of a set of classes is
   114      *  processed from the halfcompleted queue.
   115      */
   116     boolean isFirst = true;
   118     /** A flag to disable completion from time to time during member
   119      *  enter, as we only need to look up types.  This avoids
   120      *  unnecessarily deep recursion.
   121      */
   122     boolean completionEnabled = true;
   124     /* ---------- Processing import clauses ----------------
   125      */
   127     /** Import all classes of a class or package on demand.
   128      *  @param pos           Position to be used for error reporting.
   129      *  @param tsym          The class or package the members of which are imported.
   130      *  @param toScope   The (import) scope in which imported classes
   131      *               are entered.
   132      */
   133     private void importAll(int pos,
   134                            final TypeSymbol tsym,
   135                            Env<AttrContext> env) {
   136         // Check that packages imported from exist (JLS ???).
   137         if (tsym.kind == PCK && tsym.members().elems == null && !tsym.exists()) {
   138             // If we can't find java.lang, exit immediately.
   139             if (((PackageSymbol)tsym).fullname.equals(names.java_lang)) {
   140                 JCDiagnostic msg = diags.fragment("fatal.err.no.java.lang");
   141                 throw new FatalError(msg);
   142             } else {
   143                 log.error(pos, "doesnt.exist", tsym);
   144             }
   145         }
   146         env.toplevel.starImportScope.importAll(tsym.members());
   147     }
   149     /** Import all static members of a class or package on demand.
   150      *  @param pos           Position to be used for error reporting.
   151      *  @param tsym          The class or package the members of which are imported.
   152      *  @param toScope   The (import) scope in which imported classes
   153      *               are entered.
   154      */
   155     private void importStaticAll(int pos,
   156                                  final TypeSymbol tsym,
   157                                  Env<AttrContext> env) {
   158         final JavaFileObject sourcefile = env.toplevel.sourcefile;
   159         final Scope toScope = env.toplevel.starImportScope;
   160         final PackageSymbol packge = env.toplevel.packge;
   161         final TypeSymbol origin = tsym;
   163         // enter imported types immediately
   164         new Object() {
   165             Set<Symbol> processed = new HashSet<Symbol>();
   166             void importFrom(TypeSymbol tsym) {
   167                 if (tsym == null || !processed.add(tsym))
   168                     return;
   170                 // also import inherited names
   171                 importFrom(types.supertype(tsym.type).tsym);
   172                 for (Type t : types.interfaces(tsym.type))
   173                     importFrom(t.tsym);
   175                 final Scope fromScope = tsym.members();
   176                 for (Scope.Entry e = fromScope.elems; e != null; e = e.sibling) {
   177                     Symbol sym = e.sym;
   178                     if (sym.kind == TYP &&
   179                         (sym.flags() & STATIC) != 0 &&
   180                         staticImportAccessible(sym, packge) &&
   181                         sym.isMemberOf(origin, types) &&
   182                         !toScope.includes(sym))
   183                         toScope.enter(sym, fromScope, origin.members());
   184                 }
   185             }
   186         }.importFrom(tsym);
   188         // enter non-types before annotations that might use them
   189         annotate.earlier(new Annotate.Annotator() {
   190             Set<Symbol> processed = new HashSet<Symbol>();
   192             public String toString() {
   193                 return "import static " + tsym + ".*" + " in " + sourcefile;
   194             }
   195             void importFrom(TypeSymbol tsym) {
   196                 if (tsym == null || !processed.add(tsym))
   197                     return;
   199                 // also import inherited names
   200                 importFrom(types.supertype(tsym.type).tsym);
   201                 for (Type t : types.interfaces(tsym.type))
   202                     importFrom(t.tsym);
   204                 final Scope fromScope = tsym.members();
   205                 for (Scope.Entry e = fromScope.elems; e != null; e = e.sibling) {
   206                     Symbol sym = e.sym;
   207                     if (sym.isStatic() && sym.kind != TYP &&
   208                         staticImportAccessible(sym, packge) &&
   209                         !toScope.includes(sym) &&
   210                         sym.isMemberOf(origin, types)) {
   211                         toScope.enter(sym, fromScope, origin.members());
   212                     }
   213                 }
   214             }
   215             public void enterAnnotation() {
   216                 importFrom(tsym);
   217             }
   218         });
   219     }
   221     // is the sym accessible everywhere in packge?
   222     boolean staticImportAccessible(Symbol sym, PackageSymbol packge) {
   223         int flags = (int)(sym.flags() & AccessFlags);
   224         switch (flags) {
   225         default:
   226         case PUBLIC:
   227             return true;
   228         case PRIVATE:
   229             return false;
   230         case 0:
   231         case PROTECTED:
   232             return sym.packge() == packge;
   233         }
   234     }
   236     /** Import statics types of a given name.  Non-types are handled in Attr.
   237      *  @param pos           Position to be used for error reporting.
   238      *  @param tsym          The class from which the name is imported.
   239      *  @param name          The (simple) name being imported.
   240      *  @param env           The environment containing the named import
   241      *                  scope to add to.
   242      */
   243     private void importNamedStatic(final DiagnosticPosition pos,
   244                                    final TypeSymbol tsym,
   245                                    final Name name,
   246                                    final Env<AttrContext> env) {
   247         if (tsym.kind != TYP) {
   248             log.error(pos, "static.imp.only.classes.and.interfaces");
   249             return;
   250         }
   252         final Scope toScope = env.toplevel.namedImportScope;
   253         final PackageSymbol packge = env.toplevel.packge;
   254         final TypeSymbol origin = tsym;
   256         // enter imported types immediately
   257         new Object() {
   258             Set<Symbol> processed = new HashSet<Symbol>();
   259             void importFrom(TypeSymbol tsym) {
   260                 if (tsym == null || !processed.add(tsym))
   261                     return;
   263                 // also import inherited names
   264                 importFrom(types.supertype(tsym.type).tsym);
   265                 for (Type t : types.interfaces(tsym.type))
   266                     importFrom(t.tsym);
   268                 for (Scope.Entry e = tsym.members().lookup(name);
   269                      e.scope != null;
   270                      e = e.next()) {
   271                     Symbol sym = e.sym;
   272                     if (sym.isStatic() &&
   273                         sym.kind == TYP &&
   274                         staticImportAccessible(sym, packge) &&
   275                         sym.isMemberOf(origin, types) &&
   276                         chk.checkUniqueStaticImport(pos, sym, toScope))
   277                         toScope.enter(sym, sym.owner.members(), origin.members());
   278                 }
   279             }
   280         }.importFrom(tsym);
   282         // enter non-types before annotations that might use them
   283         annotate.earlier(new Annotate.Annotator() {
   284             Set<Symbol> processed = new HashSet<Symbol>();
   285             boolean found = false;
   287             public String toString() {
   288                 return "import static " + tsym + "." + name;
   289             }
   290             void importFrom(TypeSymbol tsym) {
   291                 if (tsym == null || !processed.add(tsym))
   292                     return;
   294                 // also import inherited names
   295                 importFrom(types.supertype(tsym.type).tsym);
   296                 for (Type t : types.interfaces(tsym.type))
   297                     importFrom(t.tsym);
   299                 for (Scope.Entry e = tsym.members().lookup(name);
   300                      e.scope != null;
   301                      e = e.next()) {
   302                     Symbol sym = e.sym;
   303                     if (sym.isStatic() &&
   304                         staticImportAccessible(sym, packge) &&
   305                         sym.isMemberOf(origin, types)) {
   306                         found = true;
   307                         if (sym.kind == MTH ||
   308                             sym.kind != TYP && chk.checkUniqueStaticImport(pos, sym, toScope))
   309                             toScope.enter(sym, sym.owner.members(), origin.members());
   310                     }
   311                 }
   312             }
   313             public void enterAnnotation() {
   314                 JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   315                 try {
   316                     importFrom(tsym);
   317                     if (!found) {
   318                         log.error(pos, "cant.resolve.location",
   319                                   KindName.STATIC,
   320                                   name, List.<Type>nil(), List.<Type>nil(),
   321                                   Kinds.typeKindName(tsym.type),
   322                                   tsym.type);
   323                     }
   324                 } finally {
   325                     log.useSource(prev);
   326                 }
   327             }
   328         });
   329     }
   330     /** Import given class.
   331      *  @param pos           Position to be used for error reporting.
   332      *  @param tsym          The class to be imported.
   333      *  @param env           The environment containing the named import
   334      *                  scope to add to.
   335      */
   336     private void importNamed(DiagnosticPosition pos, Symbol tsym, Env<AttrContext> env) {
   337         if (tsym.kind == TYP &&
   338             chk.checkUniqueImport(pos, tsym, env.toplevel.namedImportScope))
   339             env.toplevel.namedImportScope.enter(tsym, tsym.owner.members());
   340     }
   342     /** Construct method type from method signature.
   343      *  @param typarams    The method's type parameters.
   344      *  @param params      The method's value parameters.
   345      *  @param res             The method's result type,
   346      *                 null if it is a constructor.
   347      *  @param thrown      The method's thrown exceptions.
   348      *  @param env             The method's (local) environment.
   349      */
   350     Type signature(List<JCTypeParameter> typarams,
   351                    List<JCVariableDecl> params,
   352                    JCTree res,
   353                    List<JCExpression> thrown,
   354                    Env<AttrContext> env) {
   356         // Enter and attribute type parameters.
   357         List<Type> tvars = enter.classEnter(typarams, env);
   358         attr.attribTypeVariables(typarams, env);
   360         // Enter and attribute value parameters.
   361         ListBuffer<Type> argbuf = new ListBuffer<Type>();
   362         for (List<JCVariableDecl> l = params; l.nonEmpty(); l = l.tail) {
   363             memberEnter(l.head, env);
   364             argbuf.append(l.head.vartype.type);
   365         }
   367         // Attribute result type, if one is given.
   368         Type restype = res == null ? syms.voidType : attr.attribType(res, env);
   370         // Attribute thrown exceptions.
   371         ListBuffer<Type> thrownbuf = new ListBuffer<Type>();
   372         for (List<JCExpression> l = thrown; l.nonEmpty(); l = l.tail) {
   373             Type exc = attr.attribType(l.head, env);
   374             if (exc.tag != TYPEVAR)
   375                 exc = chk.checkClassType(l.head.pos(), exc);
   376             thrownbuf.append(exc);
   377         }
   378         Type mtype = new MethodType(argbuf.toList(),
   379                                     restype,
   380                                     thrownbuf.toList(),
   381                                     syms.methodClass);
   382         return tvars.isEmpty() ? mtype : new ForAll(tvars, mtype);
   383     }
   385 /* ********************************************************************
   386  * Visitor methods for member enter
   387  *********************************************************************/
   389     /** Visitor argument: the current environment
   390      */
   391     protected Env<AttrContext> env;
   393     /** Enter field and method definitions and process import
   394      *  clauses, catching any completion failure exceptions.
   395      */
   396     protected void memberEnter(JCTree tree, Env<AttrContext> env) {
   397         Env<AttrContext> prevEnv = this.env;
   398         try {
   399             this.env = env;
   400             tree.accept(this);
   401         }  catch (CompletionFailure ex) {
   402             chk.completionError(tree.pos(), ex);
   403         } finally {
   404             this.env = prevEnv;
   405         }
   406     }
   408     /** Enter members from a list of trees.
   409      */
   410     void memberEnter(List<? extends JCTree> trees, Env<AttrContext> env) {
   411         for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
   412             memberEnter(l.head, env);
   413     }
   415     /** Enter members for a class.
   416      */
   417     void finishClass(JCClassDecl tree, Env<AttrContext> env) {
   418         if ((tree.mods.flags & Flags.ENUM) != 0 &&
   419             (types.supertype(tree.sym.type).tsym.flags() & Flags.ENUM) == 0) {
   420             addEnumMembers(tree, env);
   421         }
   422         memberEnter(tree.defs, env);
   423     }
   425     /** Add the implicit members for an enum type
   426      *  to the symbol table.
   427      */
   428     private void addEnumMembers(JCClassDecl tree, Env<AttrContext> env) {
   429         JCExpression valuesType = make.Type(new ArrayType(tree.sym.type, syms.arrayClass));
   431         // public static T[] values() { return ???; }
   432         JCMethodDecl values = make.
   433             MethodDef(make.Modifiers(Flags.PUBLIC|Flags.STATIC),
   434                       names.values,
   435                       valuesType,
   436                       List.<JCTypeParameter>nil(),
   437                       List.<JCVariableDecl>nil(),
   438                       List.<JCExpression>nil(), // thrown
   439                       null, //make.Block(0, Tree.emptyList.prepend(make.Return(make.Ident(names._null)))),
   440                       null);
   441         memberEnter(values, env);
   443         // public static T valueOf(String name) { return ???; }
   444         JCMethodDecl valueOf = make.
   445             MethodDef(make.Modifiers(Flags.PUBLIC|Flags.STATIC),
   446                       names.valueOf,
   447                       make.Type(tree.sym.type),
   448                       List.<JCTypeParameter>nil(),
   449                       List.of(make.VarDef(make.Modifiers(Flags.PARAMETER),
   450                                             names.fromString("name"),
   451                                             make.Type(syms.stringType), null)),
   452                       List.<JCExpression>nil(), // thrown
   453                       null, //make.Block(0, Tree.emptyList.prepend(make.Return(make.Ident(names._null)))),
   454                       null);
   455         memberEnter(valueOf, env);
   457         // the remaining members are for bootstrapping only
   458         if (!target.compilerBootstrap(tree.sym)) return;
   460         // public final int ordinal() { return ???; }
   461         JCMethodDecl ordinal = make.at(tree.pos).
   462             MethodDef(make.Modifiers(Flags.PUBLIC|Flags.FINAL),
   463                       names.ordinal,
   464                       make.Type(syms.intType),
   465                       List.<JCTypeParameter>nil(),
   466                       List.<JCVariableDecl>nil(),
   467                       List.<JCExpression>nil(),
   468                       null,
   469                       null);
   470         memberEnter(ordinal, env);
   472         // public final String name() { return ???; }
   473         JCMethodDecl name = make.
   474             MethodDef(make.Modifiers(Flags.PUBLIC|Flags.FINAL),
   475                       names._name,
   476                       make.Type(syms.stringType),
   477                       List.<JCTypeParameter>nil(),
   478                       List.<JCVariableDecl>nil(),
   479                       List.<JCExpression>nil(),
   480                       null,
   481                       null);
   482         memberEnter(name, env);
   484         // public int compareTo(E other) { return ???; }
   485         MethodSymbol compareTo = new
   486             MethodSymbol(Flags.PUBLIC,
   487                          names.compareTo,
   488                          new MethodType(List.of(tree.sym.type),
   489                                         syms.intType,
   490                                         List.<Type>nil(),
   491                                         syms.methodClass),
   492                          tree.sym);
   493         memberEnter(make.MethodDef(compareTo, null), env);
   494     }
   496     public void visitTopLevel(JCCompilationUnit tree) {
   497         if (tree.starImportScope.elems != null) {
   498             // we must have already processed this toplevel
   499             return;
   500         }
   502         // check that no class exists with same fully qualified name as
   503         // toplevel package
   504         if (checkClash && tree.pid != null) {
   505             Symbol p = tree.packge;
   506             while (p.owner != syms.rootPackage) {
   507                 p.owner.complete(); // enter all class members of p
   508                 if (syms.classes.get(p.getQualifiedName()) != null) {
   509                     log.error(tree.pos,
   510                               "pkg.clashes.with.class.of.same.name",
   511                               p);
   512                 }
   513                 p = p.owner;
   514             }
   515         }
   517         // process package annotations
   518         annotateLater(tree.packageAnnotations, env, tree.packge);
   520         // Import-on-demand java.lang.
   521         importAll(tree.pos, reader.enterPackage(names.java_lang), env);
   523         // Process all import clauses.
   524         memberEnter(tree.defs, env);
   525     }
   527     // process the non-static imports and the static imports of types.
   528     public void visitImport(JCImport tree) {
   529         JCTree imp = tree.qualid;
   530         Name name = TreeInfo.name(imp);
   531         TypeSymbol p;
   533         // Create a local environment pointing to this tree to disable
   534         // effects of other imports in Resolve.findGlobalType
   535         Env<AttrContext> localEnv = env.dup(tree);
   537         // Attribute qualifying package or class.
   538         JCFieldAccess s = (JCFieldAccess) imp;
   539         p = attr.
   540             attribTree(s.selected,
   541                        localEnv,
   542                        tree.staticImport ? TYP : (TYP | PCK),
   543                        Type.noType).tsym;
   544         if (name == names.asterisk) {
   545             // Import on demand.
   546             chk.checkCanonical(s.selected);
   547             if (tree.staticImport)
   548                 importStaticAll(tree.pos, p, env);
   549             else
   550                 importAll(tree.pos, p, env);
   551         } else {
   552             // Named type import.
   553             if (tree.staticImport) {
   554                 importNamedStatic(tree.pos(), p, name, localEnv);
   555                 chk.checkCanonical(s.selected);
   556             } else {
   557                 TypeSymbol c = attribImportType(imp, localEnv).tsym;
   558                 chk.checkCanonical(imp);
   559                 importNamed(tree.pos(), c, env);
   560             }
   561         }
   562     }
   564     public void visitMethodDef(JCMethodDecl tree) {
   565         Scope enclScope = enter.enterScope(env);
   566         MethodSymbol m = new MethodSymbol(0, tree.name, null, enclScope.owner);
   567         m.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, m, tree);
   568         tree.sym = m;
   569         Env<AttrContext> localEnv = methodEnv(tree, env);
   571         // Compute the method type
   572         m.type = signature(tree.typarams, tree.params,
   573                            tree.restype, tree.thrown,
   574                            localEnv);
   576         // Set m.params
   577         ListBuffer<VarSymbol> params = new ListBuffer<VarSymbol>();
   578         JCVariableDecl lastParam = null;
   579         for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
   580             JCVariableDecl param = lastParam = l.head;
   581             assert param.sym != null;
   582             params.append(param.sym);
   583         }
   584         m.params = params.toList();
   586         // mark the method varargs, if necessary
   587         if (lastParam != null && (lastParam.mods.flags & Flags.VARARGS) != 0)
   588             m.flags_field |= Flags.VARARGS;
   590         localEnv.info.scope.leave();
   591         if (chk.checkUnique(tree.pos(), m, enclScope)) {
   592             enclScope.enter(m);
   593         }
   594         annotateLater(tree.mods.annotations, localEnv, m);
   595         if (tree.defaultValue != null)
   596             annotateDefaultValueLater(tree.defaultValue, localEnv, m);
   597     }
   599     /** Create a fresh environment for method bodies.
   600      *  @param tree     The method definition.
   601      *  @param env      The environment current outside of the method definition.
   602      */
   603     Env<AttrContext> methodEnv(JCMethodDecl tree, Env<AttrContext> env) {
   604         Env<AttrContext> localEnv =
   605             env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
   606         localEnv.enclMethod = tree;
   607         localEnv.info.scope.owner = tree.sym;
   608         if ((tree.mods.flags & STATIC) != 0) localEnv.info.staticLevel++;
   609         return localEnv;
   610     }
   612     public void visitVarDef(JCVariableDecl tree) {
   613         Env<AttrContext> localEnv = env;
   614         if ((tree.mods.flags & STATIC) != 0 ||
   615             (env.info.scope.owner.flags() & INTERFACE) != 0) {
   616             localEnv = env.dup(tree, env.info.dup());
   617             localEnv.info.staticLevel++;
   618         }
   619         attr.attribType(tree.vartype, localEnv);
   620         Scope enclScope = enter.enterScope(env);
   621         VarSymbol v =
   622             new VarSymbol(0, tree.name, tree.vartype.type, enclScope.owner);
   623         v.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, v, tree);
   624         tree.sym = v;
   625         if (tree.init != null) {
   626             v.flags_field |= HASINIT;
   627             if ((v.flags_field & FINAL) != 0 && tree.init.getTag() != JCTree.NEWCLASS) {
   628                 Env<AttrContext> initEnv = getInitEnv(tree, env);
   629                 initEnv.info.enclVar = v;
   630                 v.setLazyConstValue(initEnv(tree, initEnv), log, attr, tree.init);
   631             }
   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     }
   666     public void visitErroneous(JCErroneous tree) {
   667         if (tree.errs != null)
   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             // Internally to java.dyn, a @PolymorphicSignature annotation
   769             // acts like a classfile attribute.
   770             if (!c.type.isErroneous() &&
   771                     types.isSameType(c.type, syms.polymorphicSignatureType)) {
   772                 if (!target.hasMethodHandles()) {
   773                     // Somebody is compiling JDK7 source code to a JDK6 target.
   774                     // Make it a strict warning, since it is unlikely but important.
   775                     log.strictWarning(env.tree.pos(),
   776                             "wrong.target.for.polymorphic.signature.definition",
   777                             target.name);
   778                 }
   779                 // Pull the flag through for better diagnostics, even on a bad target.
   780                 s.flags_field |= Flags.POLYMORPHIC_SIGNATURE;
   781             }
   782             if (!annotated.add(a.type.tsym))
   783                 log.error(a.pos, "duplicate.annotation");
   784         }
   785         s.attributes_field = buf.toList();
   786     }
   788     /** Queue processing of an attribute default value. */
   789     void annotateDefaultValueLater(final JCExpression defaultValue,
   790                                    final Env<AttrContext> localEnv,
   791                                    final MethodSymbol m) {
   792         annotate.later(new Annotate.Annotator() {
   793                 public String toString() {
   794                     return "annotate " + m.owner + "." +
   795                         m + " default " + defaultValue;
   796                 }
   797                 public void enterAnnotation() {
   798                     JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile);
   799                     try {
   800                         enterDefaultValue(defaultValue, localEnv, m);
   801                     } finally {
   802                         log.useSource(prev);
   803                     }
   804                 }
   805             });
   806     }
   808     /** Enter a default value for an attribute method. */
   809     private void enterDefaultValue(final JCExpression defaultValue,
   810                                    final Env<AttrContext> localEnv,
   811                                    final MethodSymbol m) {
   812         m.defaultValue = annotate.enterAttributeValue(m.type.getReturnType(),
   813                                                       defaultValue,
   814                                                       localEnv);
   815     }
   817 /* ********************************************************************
   818  * Source completer
   819  *********************************************************************/
   821     /** Complete entering a class.
   822      *  @param sym         The symbol of the class to be completed.
   823      */
   824     public void complete(Symbol sym) throws CompletionFailure {
   825         // Suppress some (recursive) MemberEnter invocations
   826         if (!completionEnabled) {
   827             // Re-install same completer for next time around and return.
   828             assert (sym.flags() & Flags.COMPOUND) == 0;
   829             sym.completer = this;
   830             return;
   831         }
   833         ClassSymbol c = (ClassSymbol)sym;
   834         ClassType ct = (ClassType)c.type;
   835         Env<AttrContext> env = enter.typeEnvs.get(c);
   836         JCClassDecl tree = (JCClassDecl)env.tree;
   837         boolean wasFirst = isFirst;
   838         isFirst = false;
   840         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   841         try {
   842             // Save class environment for later member enter (2) processing.
   843             halfcompleted.append(env);
   845             // Mark class as not yet attributed.
   846             c.flags_field |= UNATTRIBUTED;
   848             // If this is a toplevel-class, make sure any preceding import
   849             // clauses have been seen.
   850             if (c.owner.kind == PCK) {
   851                 memberEnter(env.toplevel, env.enclosing(JCTree.TOPLEVEL));
   852                 todo.append(env);
   853             }
   855             if (c.owner.kind == TYP)
   856                 c.owner.complete();
   858             // create an environment for evaluating the base clauses
   859             Env<AttrContext> baseEnv = baseEnv(tree, env);
   861             // Determine supertype.
   862             Type supertype =
   863                 (tree.extending != null)
   864                 ? attr.attribBase(tree.extending, baseEnv, true, false, true)
   865                 : ((tree.mods.flags & Flags.ENUM) != 0 && !target.compilerBootstrap(c))
   866                 ? attr.attribBase(enumBase(tree.pos, c), baseEnv,
   867                                   true, false, false)
   868                 : (c.fullname == names.java_lang_Object)
   869                 ? Type.noType
   870                 : syms.objectType;
   871             ct.supertype_field = supertype;
   873             // Determine interfaces.
   874             ListBuffer<Type> interfaces = new ListBuffer<Type>();
   875             Set<Type> interfaceSet = new HashSet<Type>();
   876             List<JCExpression> interfaceTrees = tree.implementing;
   877             if ((tree.mods.flags & Flags.ENUM) != 0 && target.compilerBootstrap(c)) {
   878                 // add interface Comparable<T>
   879                 interfaceTrees =
   880                     interfaceTrees.prepend(make.Type(new ClassType(syms.comparableType.getEnclosingType(),
   881                                                                    List.of(c.type),
   882                                                                    syms.comparableType.tsym)));
   883                 // add interface Serializable
   884                 interfaceTrees =
   885                     interfaceTrees.prepend(make.Type(syms.serializableType));
   886             }
   887             for (JCExpression iface : interfaceTrees) {
   888                 Type i = attr.attribBase(iface, baseEnv, false, true, true);
   889                 if (i.tag == CLASS) {
   890                     interfaces.append(i);
   891                     chk.checkNotRepeated(iface.pos(), types.erasure(i), interfaceSet);
   892                 }
   893             }
   894             if ((c.flags_field & ANNOTATION) != 0)
   895                 ct.interfaces_field = List.of(syms.annotationType);
   896             else
   897                 ct.interfaces_field = interfaces.toList();
   899             if (c.fullname == names.java_lang_Object) {
   900                 if (tree.extending != null) {
   901                     chk.checkNonCyclic(tree.extending.pos(),
   902                                        supertype);
   903                     ct.supertype_field = Type.noType;
   904                 }
   905                 else if (tree.implementing.nonEmpty()) {
   906                     chk.checkNonCyclic(tree.implementing.head.pos(),
   907                                        ct.interfaces_field.head);
   908                     ct.interfaces_field = List.nil();
   909                 }
   910             }
   912             // Annotations.
   913             // In general, we cannot fully process annotations yet,  but we
   914             // can attribute the annotation types and then check to see if the
   915             // @Deprecated annotation is present.
   916             attr.attribAnnotationTypes(tree.mods.annotations, baseEnv);
   917             if (hasDeprecatedAnnotation(tree.mods.annotations))
   918                 c.flags_field |= DEPRECATED;
   919             annotateLater(tree.mods.annotations, baseEnv, c);
   920             // class type parameters use baseEnv but everything uses env
   921             for (JCTypeParameter tp : tree.typarams)
   922                 tp.accept(new TypeAnnotate(baseEnv));
   923             tree.accept(new TypeAnnotate(env));
   925             chk.checkNonCyclicDecl(tree);
   927             attr.attribTypeVariables(tree.typarams, baseEnv);
   929             // Add default constructor if needed.
   930             if ((c.flags() & INTERFACE) == 0 &&
   931                 !TreeInfo.hasConstructors(tree.defs)) {
   932                 List<Type> argtypes = List.nil();
   933                 List<Type> typarams = List.nil();
   934                 List<Type> thrown = List.nil();
   935                 long ctorFlags = 0;
   936                 boolean based = false;
   937                 if (c.name.isEmpty()) {
   938                     JCNewClass nc = (JCNewClass)env.next.tree;
   939                     if (nc.constructor != null) {
   940                         Type superConstrType = types.memberType(c.type,
   941                                                                 nc.constructor);
   942                         argtypes = superConstrType.getParameterTypes();
   943                         typarams = superConstrType.getTypeArguments();
   944                         ctorFlags = nc.constructor.flags() & VARARGS;
   945                         if (nc.encl != null) {
   946                             argtypes = argtypes.prepend(nc.encl.type);
   947                             based = true;
   948                         }
   949                         thrown = superConstrType.getThrownTypes();
   950                     }
   951                 }
   952                 JCTree constrDef = DefaultConstructor(make.at(tree.pos), c,
   953                                                     typarams, argtypes, thrown,
   954                                                     ctorFlags, based);
   955                 tree.defs = tree.defs.prepend(constrDef);
   956             }
   958             // If this is a class, enter symbols for this and super into
   959             // current scope.
   960             if ((c.flags_field & INTERFACE) == 0) {
   961                 VarSymbol thisSym =
   962                     new VarSymbol(FINAL | HASINIT, names._this, c.type, c);
   963                 thisSym.pos = Position.FIRSTPOS;
   964                 env.info.scope.enter(thisSym);
   965                 if (ct.supertype_field.tag == CLASS) {
   966                     VarSymbol superSym =
   967                         new VarSymbol(FINAL | HASINIT, names._super,
   968                                       ct.supertype_field, c);
   969                     superSym.pos = Position.FIRSTPOS;
   970                     env.info.scope.enter(superSym);
   971                 }
   972             }
   974             // check that no package exists with same fully qualified name,
   975             // but admit classes in the unnamed package which have the same
   976             // name as a top-level package.
   977             if (checkClash &&
   978                 c.owner.kind == PCK && c.owner != syms.unnamedPackage &&
   979                 reader.packageExists(c.fullname))
   980                 {
   981                     log.error(tree.pos, "clash.with.pkg.of.same.name", c);
   982                 }
   984         } catch (CompletionFailure ex) {
   985             chk.completionError(tree.pos(), ex);
   986         } finally {
   987             log.useSource(prev);
   988         }
   990         // Enter all member fields and methods of a set of half completed
   991         // classes in a second phase.
   992         if (wasFirst) {
   993             try {
   994                 while (halfcompleted.nonEmpty()) {
   995                     finish(halfcompleted.next());
   996                 }
   997             } finally {
   998                 isFirst = true;
   999             }
  1001             // commit pending annotations
  1002             annotate.flush();
  1006     // A sub-phase that "compiles" annotations in annotated types.
  1007     private class TypeAnnotate extends TreeScanner {
  1008         private Env<AttrContext> env;
  1009         public TypeAnnotate(Env<AttrContext> env) { this.env = env; }
  1011         private void enterTypeAnnotations(List<JCTypeAnnotation> annotations) {
  1012             Set<TypeSymbol> annotated = new HashSet<TypeSymbol>();
  1013             if (!skipAnnotations)
  1014                 for (List<JCTypeAnnotation> al = annotations; al.nonEmpty(); al = al.tail) {
  1015                     JCTypeAnnotation a = al.head;
  1016                     Attribute.Compound c = annotate.enterAnnotation(a,
  1017                             syms.annotationType,
  1018                             env);
  1019                     if (c == null) continue;
  1020                     Attribute.TypeCompound tc = new Attribute.TypeCompound(c.type, c.values, a.annotation_position);
  1021                     a.attribute_field = tc;
  1022                     // Note: @Deprecated has no effect on local variables and parameters
  1023                     if (!annotated.add(a.type.tsym))
  1024                         log.error(a.pos, "duplicate.annotation");
  1028         // each class (including enclosed inner classes) should be visited
  1029         // separately through MemberEnter.complete(Symbol)
  1030         // this flag is used to prevent from visiting inner classes.
  1031         private boolean isEnclosingClass = false;
  1032         @Override
  1033         public void visitClassDef(final JCClassDecl tree) {
  1034             if (isEnclosingClass)
  1035                 return;
  1036             isEnclosingClass = true;
  1037             scan(tree.mods);
  1038             // type parameter need to be visited with a separate env
  1039             // scan(tree.typarams);
  1040             scan(tree.extending);
  1041             scan(tree.implementing);
  1042             scan(tree.defs);
  1045         private void annotate(final JCTree tree, final List<JCTypeAnnotation> annotations) {
  1046             annotate.later(new Annotate.Annotator() {
  1047                 public String toString() {
  1048                     return "annotate " + annotations + " onto " + tree;
  1050                 public void enterAnnotation() {
  1051                     JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
  1052                     try {
  1053                         enterTypeAnnotations(annotations);
  1054                     } finally {
  1055                         log.useSource(prev);
  1058             });
  1061         @Override
  1062         public void visitAnnotatedType(final JCAnnotatedType tree) {
  1063             annotate(tree, tree.annotations);
  1064             super.visitAnnotatedType(tree);
  1066         @Override
  1067         public void visitTypeParameter(final JCTypeParameter tree) {
  1068             annotate(tree, tree.annotations);
  1069             super.visitTypeParameter(tree);
  1071         @Override
  1072         public void visitNewArray(final JCNewArray tree) {
  1073             annotate(tree, tree.annotations);
  1074             for (List<JCTypeAnnotation> dimAnnos : tree.dimAnnotations)
  1075                 annotate(tree, dimAnnos);
  1076             super.visitNewArray(tree);
  1078         @Override
  1079         public void visitMethodDef(JCMethodDecl tree) {
  1080             annotate(tree, tree.receiverAnnotations);
  1081             super.visitMethodDef(tree);
  1086     private Env<AttrContext> baseEnv(JCClassDecl tree, Env<AttrContext> env) {
  1087         Scope baseScope = new Scope.ClassScope(tree.sym, scopeCounter);
  1088         //import already entered local classes into base scope
  1089         for (Scope.Entry e = env.outer.info.scope.elems ; e != null ; e = e.sibling) {
  1090             if (e.sym.isLocal()) {
  1091                 baseScope.enter(e.sym);
  1094         //import current type-parameters into base scope
  1095         if (tree.typarams != null)
  1096             for (List<JCTypeParameter> typarams = tree.typarams;
  1097                  typarams.nonEmpty();
  1098                  typarams = typarams.tail)
  1099                 baseScope.enter(typarams.head.type.tsym);
  1100         Env<AttrContext> outer = env.outer; // the base clause can't see members of this class
  1101         Env<AttrContext> localEnv = outer.dup(tree, outer.info.dup(baseScope));
  1102         localEnv.baseClause = true;
  1103         localEnv.outer = outer;
  1104         localEnv.info.isSelfCall = false;
  1105         return localEnv;
  1108     /** Enter member fields and methods of a class
  1109      *  @param env        the environment current for the class block.
  1110      */
  1111     private void finish(Env<AttrContext> env) {
  1112         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
  1113         try {
  1114             JCClassDecl tree = (JCClassDecl)env.tree;
  1115             finishClass(tree, env);
  1116         } finally {
  1117             log.useSource(prev);
  1121     /** Generate a base clause for an enum type.
  1122      *  @param pos              The position for trees and diagnostics, if any
  1123      *  @param c                The class symbol of the enum
  1124      */
  1125     private JCExpression enumBase(int pos, ClassSymbol c) {
  1126         JCExpression result = make.at(pos).
  1127             TypeApply(make.QualIdent(syms.enumSym),
  1128                       List.<JCExpression>of(make.Type(c.type)));
  1129         return result;
  1132 /* ***************************************************************************
  1133  * tree building
  1134  ****************************************************************************/
  1136     /** Generate default constructor for given class. For classes different
  1137      *  from java.lang.Object, this is:
  1139      *    c(argtype_0 x_0, ..., argtype_n x_n) throws thrown {
  1140      *      super(x_0, ..., x_n)
  1141      *    }
  1143      *  or, if based == true:
  1145      *    c(argtype_0 x_0, ..., argtype_n x_n) throws thrown {
  1146      *      x_0.super(x_1, ..., x_n)
  1147      *    }
  1149      *  @param make     The tree factory.
  1150      *  @param c        The class owning the default constructor.
  1151      *  @param argtypes The parameter types of the constructor.
  1152      *  @param thrown   The thrown exceptions of the constructor.
  1153      *  @param based    Is first parameter a this$n?
  1154      */
  1155     JCTree DefaultConstructor(TreeMaker make,
  1156                             ClassSymbol c,
  1157                             List<Type> typarams,
  1158                             List<Type> argtypes,
  1159                             List<Type> thrown,
  1160                             long flags,
  1161                             boolean based) {
  1162         List<JCVariableDecl> params = make.Params(argtypes, syms.noSymbol);
  1163         List<JCStatement> stats = List.nil();
  1164         if (c.type != syms.objectType)
  1165             stats = stats.prepend(SuperCall(make, typarams, params, based));
  1166         if ((c.flags() & ENUM) != 0 &&
  1167             (types.supertype(c.type).tsym == syms.enumSym ||
  1168              target.compilerBootstrap(c))) {
  1169             // constructors of true enums are private
  1170             flags = (flags & ~AccessFlags) | PRIVATE | GENERATEDCONSTR;
  1171         } else
  1172             flags |= (c.flags() & AccessFlags) | GENERATEDCONSTR;
  1173         if (c.name.isEmpty()) flags |= ANONCONSTR;
  1174         JCTree result = make.MethodDef(
  1175             make.Modifiers(flags),
  1176             names.init,
  1177             null,
  1178             make.TypeParams(typarams),
  1179             params,
  1180             make.Types(thrown),
  1181             make.Block(0, stats),
  1182             null);
  1183         return result;
  1186     /** Generate call to superclass constructor. This is:
  1188      *    super(id_0, ..., id_n)
  1190      * or, if based == true
  1192      *    id_0.super(id_1,...,id_n)
  1194      *  where id_0, ..., id_n are the names of the given parameters.
  1196      *  @param make    The tree factory
  1197      *  @param params  The parameters that need to be passed to super
  1198      *  @param typarams  The type parameters that need to be passed to super
  1199      *  @param based   Is first parameter a this$n?
  1200      */
  1201     JCExpressionStatement SuperCall(TreeMaker make,
  1202                    List<Type> typarams,
  1203                    List<JCVariableDecl> params,
  1204                    boolean based) {
  1205         JCExpression meth;
  1206         if (based) {
  1207             meth = make.Select(make.Ident(params.head), names._super);
  1208             params = params.tail;
  1209         } else {
  1210             meth = make.Ident(names._super);
  1212         List<JCExpression> typeargs = typarams.nonEmpty() ? make.Types(typarams) : null;
  1213         return make.Exec(make.Apply(typeargs, meth, make.Idents(params)));

mercurial