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

Thu, 25 Jul 2013 14:49:16 +0100

author
mcimadamore
date
Thu, 25 Jul 2013 14:49:16 +0100
changeset 1920
b02f28bf7f1c
parent 1906
10711bd8bb2d
child 1945
f7f271bd74a2
permissions
-rw-r--r--

8016081: field initialized with lambda in annotation types doesn't compile
Summary: check for annotation attributes should skip over synthetic methods
Reviewed-by: jjg

     1 /*
     2  * Copyright (c) 2003, 2013, 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.HashMap;
    29 import java.util.HashSet;
    30 import java.util.LinkedHashMap;
    31 import java.util.Map;
    32 import java.util.Set;
    34 import javax.tools.JavaFileObject;
    36 import com.sun.tools.javac.code.*;
    37 import com.sun.tools.javac.jvm.*;
    38 import com.sun.tools.javac.tree.*;
    39 import com.sun.tools.javac.util.*;
    41 import com.sun.tools.javac.code.Type.*;
    42 import com.sun.tools.javac.code.Symbol.*;
    43 import com.sun.tools.javac.tree.JCTree.*;
    45 import static com.sun.tools.javac.code.Flags.*;
    46 import static com.sun.tools.javac.code.Flags.ANNOTATION;
    47 import static com.sun.tools.javac.code.Kinds.*;
    48 import static com.sun.tools.javac.code.TypeTag.CLASS;
    49 import static com.sun.tools.javac.code.TypeTag.ERROR;
    50 import static com.sun.tools.javac.code.TypeTag.TYPEVAR;
    51 import static com.sun.tools.javac.tree.JCTree.Tag.*;
    52 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
    53 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    55 /** This is the second phase of Enter, in which classes are completed
    56  *  by entering their members into the class scope using
    57  *  MemberEnter.complete().  See Enter for an overview.
    58  *
    59  *  <p><b>This is NOT part of any supported API.
    60  *  If you write code that depends on this, you do so at your own risk.
    61  *  This code and its internal interfaces are subject to change or
    62  *  deletion without notice.</b>
    63  */
    64 public class MemberEnter extends JCTree.Visitor implements Completer {
    65     protected static final Context.Key<MemberEnter> memberEnterKey =
    66         new Context.Key<MemberEnter>();
    68     /** A switch to determine whether we check for package/class conflicts
    69      */
    70     final static boolean checkClash = true;
    72     private final Names names;
    73     private final Enter enter;
    74     private final Log log;
    75     private final Check chk;
    76     private final Attr attr;
    77     private final Symtab syms;
    78     private final TreeMaker make;
    79     private final ClassReader reader;
    80     private final Todo todo;
    81     private final Annotate annotate;
    82     private final Types types;
    83     private final JCDiagnostic.Factory diags;
    84     private final Source source;
    85     private final Target target;
    86     private final DeferredLintHandler deferredLintHandler;
    88     public static MemberEnter instance(Context context) {
    89         MemberEnter instance = context.get(memberEnterKey);
    90         if (instance == null)
    91             instance = new MemberEnter(context);
    92         return instance;
    93     }
    95     protected MemberEnter(Context context) {
    96         context.put(memberEnterKey, this);
    97         names = Names.instance(context);
    98         enter = Enter.instance(context);
    99         log = Log.instance(context);
   100         chk = Check.instance(context);
   101         attr = Attr.instance(context);
   102         syms = Symtab.instance(context);
   103         make = TreeMaker.instance(context);
   104         reader = ClassReader.instance(context);
   105         todo = Todo.instance(context);
   106         annotate = Annotate.instance(context);
   107         types = Types.instance(context);
   108         diags = JCDiagnostic.Factory.instance(context);
   109         source = Source.instance(context);
   110         target = Target.instance(context);
   111         deferredLintHandler = DeferredLintHandler.instance(context);
   112         allowTypeAnnos = source.allowTypeAnnotations();
   113     }
   115     /** Switch: support type annotations.
   116      */
   117     boolean allowTypeAnnos;
   119     /** A queue for classes whose members still need to be entered into the
   120      *  symbol table.
   121      */
   122     ListBuffer<Env<AttrContext>> halfcompleted = new ListBuffer<Env<AttrContext>>();
   124     /** Set to true only when the first of a set of classes is
   125      *  processed from the half completed queue.
   126      */
   127     boolean isFirst = true;
   129     /** A flag to disable completion from time to time during member
   130      *  enter, as we only need to look up types.  This avoids
   131      *  unnecessarily deep recursion.
   132      */
   133     boolean completionEnabled = true;
   135     /* ---------- Processing import clauses ----------------
   136      */
   138     /** Import all classes of a class or package on demand.
   139      *  @param pos           Position to be used for error reporting.
   140      *  @param tsym          The class or package the members of which are imported.
   141      *  @param env           The env in which the imported classes will be entered.
   142      */
   143     private void importAll(int pos,
   144                            final TypeSymbol tsym,
   145                            Env<AttrContext> env) {
   146         // Check that packages imported from exist (JLS ???).
   147         if (tsym.kind == PCK && tsym.members().elems == null && !tsym.exists()) {
   148             // If we can't find java.lang, exit immediately.
   149             if (((PackageSymbol)tsym).fullname.equals(names.java_lang)) {
   150                 JCDiagnostic msg = diags.fragment("fatal.err.no.java.lang");
   151                 throw new FatalError(msg);
   152             } else {
   153                 log.error(DiagnosticFlag.RESOLVE_ERROR, pos, "doesnt.exist", tsym);
   154             }
   155         }
   156         env.toplevel.starImportScope.importAll(tsym.members());
   157     }
   159     /** Import all static members of a class or package on demand.
   160      *  @param pos           Position to be used for error reporting.
   161      *  @param tsym          The class or package the members of which are imported.
   162      *  @param env           The env in which the imported classes will be entered.
   163      */
   164     private void importStaticAll(int pos,
   165                                  final TypeSymbol tsym,
   166                                  Env<AttrContext> env) {
   167         final JavaFileObject sourcefile = env.toplevel.sourcefile;
   168         final Scope toScope = env.toplevel.starImportScope;
   169         final PackageSymbol packge = env.toplevel.packge;
   170         final TypeSymbol origin = tsym;
   172         // enter imported types immediately
   173         new Object() {
   174             Set<Symbol> processed = new HashSet<Symbol>();
   175             void importFrom(TypeSymbol tsym) {
   176                 if (tsym == null || !processed.add(tsym))
   177                     return;
   179                 // also import inherited names
   180                 importFrom(types.supertype(tsym.type).tsym);
   181                 for (Type t : types.interfaces(tsym.type))
   182                     importFrom(t.tsym);
   184                 final Scope fromScope = tsym.members();
   185                 for (Scope.Entry e = fromScope.elems; e != null; e = e.sibling) {
   186                     Symbol sym = e.sym;
   187                     if (sym.kind == TYP &&
   188                         (sym.flags() & STATIC) != 0 &&
   189                         staticImportAccessible(sym, packge) &&
   190                         sym.isMemberOf(origin, types) &&
   191                         !toScope.includes(sym))
   192                         toScope.enter(sym, fromScope, origin.members());
   193                 }
   194             }
   195         }.importFrom(tsym);
   197         // enter non-types before annotations that might use them
   198         annotate.earlier(new Annotate.Annotator() {
   199             Set<Symbol> processed = new HashSet<Symbol>();
   201             public String toString() {
   202                 return "import static " + tsym + ".*" + " in " + sourcefile;
   203             }
   204             void importFrom(TypeSymbol tsym) {
   205                 if (tsym == null || !processed.add(tsym))
   206                     return;
   208                 // also import inherited names
   209                 importFrom(types.supertype(tsym.type).tsym);
   210                 for (Type t : types.interfaces(tsym.type))
   211                     importFrom(t.tsym);
   213                 final Scope fromScope = tsym.members();
   214                 for (Scope.Entry e = fromScope.elems; e != null; e = e.sibling) {
   215                     Symbol sym = e.sym;
   216                     if (sym.isStatic() && sym.kind != TYP &&
   217                         staticImportAccessible(sym, packge) &&
   218                         !toScope.includes(sym) &&
   219                         sym.isMemberOf(origin, types)) {
   220                         toScope.enter(sym, fromScope, origin.members());
   221                     }
   222                 }
   223             }
   224             public void enterAnnotation() {
   225                 importFrom(tsym);
   226             }
   227         });
   228     }
   230     // is the sym accessible everywhere in packge?
   231     boolean staticImportAccessible(Symbol sym, PackageSymbol packge) {
   232         int flags = (int)(sym.flags() & AccessFlags);
   233         switch (flags) {
   234         default:
   235         case PUBLIC:
   236             return true;
   237         case PRIVATE:
   238             return false;
   239         case 0:
   240         case PROTECTED:
   241             return sym.packge() == packge;
   242         }
   243     }
   245     /** Import statics types of a given name.  Non-types are handled in Attr.
   246      *  @param pos           Position to be used for error reporting.
   247      *  @param tsym          The class from which the name is imported.
   248      *  @param name          The (simple) name being imported.
   249      *  @param env           The environment containing the named import
   250      *                  scope to add to.
   251      */
   252     private void importNamedStatic(final DiagnosticPosition pos,
   253                                    final TypeSymbol tsym,
   254                                    final Name name,
   255                                    final Env<AttrContext> env) {
   256         if (tsym.kind != TYP) {
   257             log.error(DiagnosticFlag.RECOVERABLE, pos, "static.imp.only.classes.and.interfaces");
   258             return;
   259         }
   261         final Scope toScope = env.toplevel.namedImportScope;
   262         final PackageSymbol packge = env.toplevel.packge;
   263         final TypeSymbol origin = tsym;
   265         // enter imported types immediately
   266         new Object() {
   267             Set<Symbol> processed = new HashSet<Symbol>();
   268             void importFrom(TypeSymbol tsym) {
   269                 if (tsym == null || !processed.add(tsym))
   270                     return;
   272                 // also import inherited names
   273                 importFrom(types.supertype(tsym.type).tsym);
   274                 for (Type t : types.interfaces(tsym.type))
   275                     importFrom(t.tsym);
   277                 for (Scope.Entry e = tsym.members().lookup(name);
   278                      e.scope != null;
   279                      e = e.next()) {
   280                     Symbol sym = e.sym;
   281                     if (sym.isStatic() &&
   282                         sym.kind == TYP &&
   283                         staticImportAccessible(sym, packge) &&
   284                         sym.isMemberOf(origin, types) &&
   285                         chk.checkUniqueStaticImport(pos, sym, toScope))
   286                         toScope.enter(sym, sym.owner.members(), origin.members());
   287                 }
   288             }
   289         }.importFrom(tsym);
   291         // enter non-types before annotations that might use them
   292         annotate.earlier(new Annotate.Annotator() {
   293             Set<Symbol> processed = new HashSet<Symbol>();
   294             boolean found = false;
   296             public String toString() {
   297                 return "import static " + tsym + "." + name;
   298             }
   299             void importFrom(TypeSymbol tsym) {
   300                 if (tsym == null || !processed.add(tsym))
   301                     return;
   303                 // also import inherited names
   304                 importFrom(types.supertype(tsym.type).tsym);
   305                 for (Type t : types.interfaces(tsym.type))
   306                     importFrom(t.tsym);
   308                 for (Scope.Entry e = tsym.members().lookup(name);
   309                      e.scope != null;
   310                      e = e.next()) {
   311                     Symbol sym = e.sym;
   312                     if (sym.isStatic() &&
   313                         staticImportAccessible(sym, packge) &&
   314                         sym.isMemberOf(origin, types)) {
   315                         found = true;
   316                         if (sym.kind == MTH ||
   317                             sym.kind != TYP && chk.checkUniqueStaticImport(pos, sym, toScope))
   318                             toScope.enter(sym, sym.owner.members(), origin.members());
   319                     }
   320                 }
   321             }
   322             public void enterAnnotation() {
   323                 JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   324                 try {
   325                     importFrom(tsym);
   326                     if (!found) {
   327                         log.error(pos, "cant.resolve.location",
   328                                   KindName.STATIC,
   329                                   name, List.<Type>nil(), List.<Type>nil(),
   330                                   Kinds.typeKindName(tsym.type),
   331                                   tsym.type);
   332                     }
   333                 } finally {
   334                     log.useSource(prev);
   335                 }
   336             }
   337         });
   338     }
   339     /** Import given class.
   340      *  @param pos           Position to be used for error reporting.
   341      *  @param tsym          The class to be imported.
   342      *  @param env           The environment containing the named import
   343      *                  scope to add to.
   344      */
   345     private void importNamed(DiagnosticPosition pos, Symbol tsym, Env<AttrContext> env) {
   346         if (tsym.kind == TYP &&
   347             chk.checkUniqueImport(pos, tsym, env.toplevel.namedImportScope))
   348             env.toplevel.namedImportScope.enter(tsym, tsym.owner.members());
   349     }
   351     /** Construct method type from method signature.
   352      *  @param typarams    The method's type parameters.
   353      *  @param params      The method's value parameters.
   354      *  @param res             The method's result type,
   355      *                 null if it is a constructor.
   356      *  @param recvparam       The method's receiver parameter,
   357      *                 null if none given; TODO: or already set here?
   358      *  @param thrown      The method's thrown exceptions.
   359      *  @param env             The method's (local) environment.
   360      */
   361     Type signature(MethodSymbol msym,
   362                    List<JCTypeParameter> typarams,
   363                    List<JCVariableDecl> params,
   364                    JCTree res,
   365                    JCVariableDecl recvparam,
   366                    List<JCExpression> thrown,
   367                    Env<AttrContext> env) {
   369         // Enter and attribute type parameters.
   370         List<Type> tvars = enter.classEnter(typarams, env);
   371         attr.attribTypeVariables(typarams, env);
   373         // Enter and attribute value parameters.
   374         ListBuffer<Type> argbuf = new ListBuffer<Type>();
   375         for (List<JCVariableDecl> l = params; l.nonEmpty(); l = l.tail) {
   376             memberEnter(l.head, env);
   377             argbuf.append(l.head.vartype.type);
   378         }
   380         // Attribute result type, if one is given.
   381         Type restype = res == null ? syms.voidType : attr.attribType(res, env);
   383         // Attribute receiver type, if one is given.
   384         Type recvtype;
   385         if (recvparam!=null) {
   386             memberEnter(recvparam, env);
   387             recvtype = recvparam.vartype.type;
   388         } else {
   389             recvtype = null;
   390         }
   392         // Attribute thrown exceptions.
   393         ListBuffer<Type> thrownbuf = new ListBuffer<Type>();
   394         for (List<JCExpression> l = thrown; l.nonEmpty(); l = l.tail) {
   395             Type exc = attr.attribType(l.head, env);
   396             if (!exc.hasTag(TYPEVAR)) {
   397                 exc = chk.checkClassType(l.head.pos(), exc);
   398             } else if (exc.tsym.owner == msym) {
   399                 //mark inference variables in 'throws' clause
   400                 exc.tsym.flags_field |= THROWS;
   401             }
   402             thrownbuf.append(exc);
   403         }
   404         MethodType mtype = new MethodType(argbuf.toList(),
   405                                     restype,
   406                                     thrownbuf.toList(),
   407                                     syms.methodClass);
   408         mtype.recvtype = recvtype;
   410         return tvars.isEmpty() ? mtype : new ForAll(tvars, mtype);
   411     }
   413 /* ********************************************************************
   414  * Visitor methods for member enter
   415  *********************************************************************/
   417     /** Visitor argument: the current environment
   418      */
   419     protected Env<AttrContext> env;
   421     /** Enter field and method definitions and process import
   422      *  clauses, catching any completion failure exceptions.
   423      */
   424     protected void memberEnter(JCTree tree, Env<AttrContext> env) {
   425         Env<AttrContext> prevEnv = this.env;
   426         try {
   427             this.env = env;
   428             tree.accept(this);
   429         }  catch (CompletionFailure ex) {
   430             chk.completionError(tree.pos(), ex);
   431         } finally {
   432             this.env = prevEnv;
   433         }
   434     }
   436     /** Enter members from a list of trees.
   437      */
   438     void memberEnter(List<? extends JCTree> trees, Env<AttrContext> env) {
   439         for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
   440             memberEnter(l.head, env);
   441     }
   443     /** Enter members for a class.
   444      */
   445     void finishClass(JCClassDecl tree, Env<AttrContext> env) {
   446         if ((tree.mods.flags & Flags.ENUM) != 0 &&
   447             (types.supertype(tree.sym.type).tsym.flags() & Flags.ENUM) == 0) {
   448             addEnumMembers(tree, env);
   449         }
   450         memberEnter(tree.defs, env);
   451     }
   453     /** Add the implicit members for an enum type
   454      *  to the symbol table.
   455      */
   456     private void addEnumMembers(JCClassDecl tree, Env<AttrContext> env) {
   457         JCExpression valuesType = make.Type(new ArrayType(tree.sym.type, syms.arrayClass));
   459         // public static T[] values() { return ???; }
   460         JCMethodDecl values = make.
   461             MethodDef(make.Modifiers(Flags.PUBLIC|Flags.STATIC),
   462                       names.values,
   463                       valuesType,
   464                       List.<JCTypeParameter>nil(),
   465                       List.<JCVariableDecl>nil(),
   466                       List.<JCExpression>nil(), // thrown
   467                       null, //make.Block(0, Tree.emptyList.prepend(make.Return(make.Ident(names._null)))),
   468                       null);
   469         memberEnter(values, env);
   471         // public static T valueOf(String name) { return ???; }
   472         JCMethodDecl valueOf = make.
   473             MethodDef(make.Modifiers(Flags.PUBLIC|Flags.STATIC),
   474                       names.valueOf,
   475                       make.Type(tree.sym.type),
   476                       List.<JCTypeParameter>nil(),
   477                       List.of(make.VarDef(make.Modifiers(Flags.PARAMETER |
   478                                                          Flags.MANDATED),
   479                                             names.fromString("name"),
   480                                             make.Type(syms.stringType), null)),
   481                       List.<JCExpression>nil(), // thrown
   482                       null, //make.Block(0, Tree.emptyList.prepend(make.Return(make.Ident(names._null)))),
   483                       null);
   484         memberEnter(valueOf, env);
   485     }
   487     public void visitTopLevel(JCCompilationUnit tree) {
   488         if (tree.starImportScope.elems != null) {
   489             // we must have already processed this toplevel
   490             return;
   491         }
   493         // check that no class exists with same fully qualified name as
   494         // toplevel package
   495         if (checkClash && tree.pid != null) {
   496             Symbol p = tree.packge;
   497             while (p.owner != syms.rootPackage) {
   498                 p.owner.complete(); // enter all class members of p
   499                 if (syms.classes.get(p.getQualifiedName()) != null) {
   500                     log.error(tree.pos,
   501                               "pkg.clashes.with.class.of.same.name",
   502                               p);
   503                 }
   504                 p = p.owner;
   505             }
   506         }
   508         // process package annotations
   509         annotateLater(tree.packageAnnotations, env, tree.packge);
   511         DeferredLintHandler prevLintHandler = chk.setDeferredLintHandler(DeferredLintHandler.immediateHandler);
   513         try {
   514             // Import-on-demand java.lang.
   515             importAll(tree.pos, reader.enterPackage(names.java_lang), env);
   517             // Process all import clauses.
   518             memberEnter(tree.defs, env);
   519         } finally {
   520             chk.setDeferredLintHandler(prevLintHandler);
   521         }
   522     }
   524     // process the non-static imports and the static imports of types.
   525     public void visitImport(JCImport tree) {
   526         JCFieldAccess imp = (JCFieldAccess)tree.qualid;
   527         Name name = TreeInfo.name(imp);
   529         // Create a local environment pointing to this tree to disable
   530         // effects of other imports in Resolve.findGlobalType
   531         Env<AttrContext> localEnv = env.dup(tree);
   533         TypeSymbol p = attr.attribImportQualifier(tree, localEnv).tsym;
   534         if (name == names.asterisk) {
   535             // Import on demand.
   536             chk.checkCanonical(imp.selected);
   537             if (tree.staticImport)
   538                 importStaticAll(tree.pos, p, env);
   539             else
   540                 importAll(tree.pos, p, env);
   541         } else {
   542             // Named type import.
   543             if (tree.staticImport) {
   544                 importNamedStatic(tree.pos(), p, name, localEnv);
   545                 chk.checkCanonical(imp.selected);
   546             } else {
   547                 TypeSymbol c = attribImportType(imp, localEnv).tsym;
   548                 chk.checkCanonical(imp);
   549                 importNamed(tree.pos(), c, env);
   550             }
   551         }
   552     }
   554     public void visitMethodDef(JCMethodDecl tree) {
   555         Scope enclScope = enter.enterScope(env);
   556         MethodSymbol m = new MethodSymbol(0, tree.name, null, enclScope.owner);
   557         m.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, m, tree);
   558         tree.sym = m;
   560         //if this is a default method, add the DEFAULT flag to the enclosing interface
   561         if ((tree.mods.flags & DEFAULT) != 0) {
   562             m.enclClass().flags_field |= DEFAULT;
   563         }
   565         Env<AttrContext> localEnv = methodEnv(tree, env);
   567         DeferredLintHandler prevLintHandler =
   568                 chk.setDeferredLintHandler(deferredLintHandler.setPos(tree.pos()));
   569         try {
   570             // Compute the method type
   571             m.type = signature(m, tree.typarams, tree.params,
   572                                tree.restype, tree.recvparam,
   573                                tree.thrown,
   574                                localEnv);
   575         } finally {
   576             chk.setDeferredLintHandler(prevLintHandler);
   577         }
   579         if (types.isSignaturePolymorphic(m)) {
   580             m.flags_field |= SIGNATURE_POLYMORPHIC;
   581         }
   583         // Set m.params
   584         ListBuffer<VarSymbol> params = new ListBuffer<VarSymbol>();
   585         JCVariableDecl lastParam = null;
   586         for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
   587             JCVariableDecl param = lastParam = l.head;
   588             params.append(Assert.checkNonNull(param.sym));
   589         }
   590         m.params = params.toList();
   592         // mark the method varargs, if necessary
   593         if (lastParam != null && (lastParam.mods.flags & Flags.VARARGS) != 0)
   594             m.flags_field |= Flags.VARARGS;
   596         localEnv.info.scope.leave();
   597         if (chk.checkUnique(tree.pos(), m, enclScope)) {
   598             enclScope.enter(m);
   599         }
   600         annotateLater(tree.mods.annotations, localEnv, m);
   601         // Visit the signature of the method. Note that
   602         // TypeAnnotate doesn't descend into the body.
   603         typeAnnotate(tree, localEnv, m);
   605         if (tree.defaultValue != null)
   606             annotateDefaultValueLater(tree.defaultValue, localEnv, m);
   607     }
   609     /** Create a fresh environment for method bodies.
   610      *  @param tree     The method definition.
   611      *  @param env      The environment current outside of the method definition.
   612      */
   613     Env<AttrContext> methodEnv(JCMethodDecl tree, Env<AttrContext> env) {
   614         Env<AttrContext> localEnv =
   615             env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
   616         localEnv.enclMethod = tree;
   617         localEnv.info.scope.owner = tree.sym;
   618         if (tree.sym.type != null) {
   619             //when this is called in the enter stage, there's no type to be set
   620             localEnv.info.returnResult = attr.new ResultInfo(VAL, tree.sym.type.getReturnType());
   621         }
   622         if ((tree.mods.flags & STATIC) != 0) localEnv.info.staticLevel++;
   623         return localEnv;
   624     }
   626     public void visitVarDef(JCVariableDecl tree) {
   627         Env<AttrContext> localEnv = env;
   628         if ((tree.mods.flags & STATIC) != 0 ||
   629             (env.info.scope.owner.flags() & INTERFACE) != 0) {
   630             localEnv = env.dup(tree, env.info.dup());
   631             localEnv.info.staticLevel++;
   632         }
   633         DeferredLintHandler prevLintHandler =
   634                 chk.setDeferredLintHandler(deferredLintHandler.setPos(tree.pos()));
   635         try {
   636             if (TreeInfo.isEnumInit(tree)) {
   637                 attr.attribIdentAsEnumType(localEnv, (JCIdent)tree.vartype);
   638             } else {
   639                 // Make sure type annotations are processed.
   640                 // But we don't have a symbol to attach them to yet - use null.
   641                 typeAnnotate(tree.vartype, env, null);
   642                 attr.attribType(tree.vartype, localEnv);
   643                 if (tree.nameexpr != null) {
   644                     attr.attribExpr(tree.nameexpr, localEnv);
   645                     MethodSymbol m = localEnv.enclMethod.sym;
   646                     if (m.isConstructor()) {
   647                         Type outertype = m.owner.owner.type;
   648                         if (outertype.hasTag(TypeTag.CLASS)) {
   649                             checkType(tree.vartype, outertype, "incorrect.constructor.receiver.type");
   650                             checkType(tree.nameexpr, outertype, "incorrect.constructor.receiver.name");
   651                         } else {
   652                             log.error(tree, "receiver.parameter.not.applicable.constructor.toplevel.class");
   653                         }
   654                     } else {
   655                         checkType(tree.vartype, m.owner.type, "incorrect.receiver.type");
   656                         checkType(tree.nameexpr, m.owner.type, "incorrect.receiver.name");
   657                     }
   658                 }
   659             }
   660         } finally {
   661             chk.setDeferredLintHandler(prevLintHandler);
   662         }
   664         if ((tree.mods.flags & VARARGS) != 0) {
   665             //if we are entering a varargs parameter, we need to replace its type
   666             //(a plain array type) with the more precise VarargsType --- we need
   667             //to do it this way because varargs is represented in the tree as a modifier
   668             //on the parameter declaration, and not as a distinct type of array node.
   669             ArrayType atype = (ArrayType)tree.vartype.type.unannotatedType();
   670             tree.vartype.type = atype.makeVarargs();
   671         }
   672         Scope enclScope = enter.enterScope(env);
   673         VarSymbol v =
   674             new VarSymbol(0, tree.name, tree.vartype.type, enclScope.owner);
   675         v.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, v, tree);
   676         tree.sym = v;
   677         if (tree.init != null) {
   678             v.flags_field |= HASINIT;
   679             if ((v.flags_field & FINAL) != 0 &&
   680                     !tree.init.hasTag(NEWCLASS) &&
   681                     !tree.init.hasTag(LAMBDA)) {
   682                 Env<AttrContext> initEnv = getInitEnv(tree, env);
   683                 initEnv.info.enclVar = v;
   684                 v.setLazyConstValue(initEnv(tree, initEnv), attr, tree.init);
   685             }
   686         }
   687         if (chk.checkUnique(tree.pos(), v, enclScope)) {
   688             chk.checkTransparentVar(tree.pos(), v, enclScope);
   689             enclScope.enter(v);
   690         }
   691         annotateLater(tree.mods.annotations, localEnv, v);
   692         typeAnnotate(tree.vartype, env, v);
   693         annotate.flush();
   694         v.pos = tree.pos;
   695     }
   696     // where
   697     void checkType(JCTree tree, Type type, String diag) {
   698         if (!tree.type.isErroneous() && !types.isSameType(tree.type, type)) {
   699             log.error(tree, diag, type, tree.type);
   700         }
   701     }
   703     /** Create a fresh environment for a variable's initializer.
   704      *  If the variable is a field, the owner of the environment's scope
   705      *  is be the variable itself, otherwise the owner is the method
   706      *  enclosing the variable definition.
   707      *
   708      *  @param tree     The variable definition.
   709      *  @param env      The environment current outside of the variable definition.
   710      */
   711     Env<AttrContext> initEnv(JCVariableDecl tree, Env<AttrContext> env) {
   712         Env<AttrContext> localEnv = env.dupto(new AttrContextEnv(tree, env.info.dup()));
   713         if (tree.sym.owner.kind == TYP) {
   714             localEnv.info.scope = env.info.scope.dupUnshared();
   715             localEnv.info.scope.owner = tree.sym;
   716         }
   717         if ((tree.mods.flags & STATIC) != 0 ||
   718                 ((env.enclClass.sym.flags() & INTERFACE) != 0 && env.enclMethod == null))
   719             localEnv.info.staticLevel++;
   720         return localEnv;
   721     }
   723     /** Default member enter visitor method: do nothing
   724      */
   725     public void visitTree(JCTree tree) {
   726     }
   728     public void visitErroneous(JCErroneous tree) {
   729         if (tree.errs != null)
   730             memberEnter(tree.errs, env);
   731     }
   733     public Env<AttrContext> getMethodEnv(JCMethodDecl tree, Env<AttrContext> env) {
   734         Env<AttrContext> mEnv = methodEnv(tree, env);
   735         mEnv.info.lint = mEnv.info.lint.augment(tree.sym);
   736         for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
   737             mEnv.info.scope.enterIfAbsent(l.head.type.tsym);
   738         for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail)
   739             mEnv.info.scope.enterIfAbsent(l.head.sym);
   740         return mEnv;
   741     }
   743     public Env<AttrContext> getInitEnv(JCVariableDecl tree, Env<AttrContext> env) {
   744         Env<AttrContext> iEnv = initEnv(tree, env);
   745         return iEnv;
   746     }
   748 /* ********************************************************************
   749  * Type completion
   750  *********************************************************************/
   752     Type attribImportType(JCTree tree, Env<AttrContext> env) {
   753         Assert.check(completionEnabled);
   754         try {
   755             // To prevent deep recursion, suppress completion of some
   756             // types.
   757             completionEnabled = false;
   758             return attr.attribType(tree, env);
   759         } finally {
   760             completionEnabled = true;
   761         }
   762     }
   764 /* ********************************************************************
   765  * Annotation processing
   766  *********************************************************************/
   768     /** Queue annotations for later processing. */
   769     void annotateLater(final List<JCAnnotation> annotations,
   770                        final Env<AttrContext> localEnv,
   771                        final Symbol s) {
   772         if (annotations.isEmpty()) {
   773             return;
   774         }
   775         if (s.kind != PCK) {
   776             s.resetAnnotations(); // mark Annotations as incomplete for now
   777         }
   778         annotate.normal(new Annotate.Annotator() {
   779                 @Override
   780                 public String toString() {
   781                     return "annotate " + annotations + " onto " + s + " in " + s.owner;
   782                 }
   784                 @Override
   785                 public void enterAnnotation() {
   786                     Assert.check(s.kind == PCK || s.annotationsPendingCompletion());
   787                     JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile);
   788                     try {
   789                         if (s.hasAnnotations() &&
   790                             annotations.nonEmpty())
   791                             log.error(annotations.head.pos,
   792                                       "already.annotated",
   793                                       kindName(s), s);
   794                         actualEnterAnnotations(annotations, localEnv, s);
   795                     } finally {
   796                         log.useSource(prev);
   797                     }
   798                 }
   799             });
   800     }
   802     /**
   803      * Check if a list of annotations contains a reference to
   804      * java.lang.Deprecated.
   805      **/
   806     private boolean hasDeprecatedAnnotation(List<JCAnnotation> annotations) {
   807         for (List<JCAnnotation> al = annotations; !al.isEmpty(); al = al.tail) {
   808             JCAnnotation a = al.head;
   809             if (a.annotationType.type == syms.deprecatedType && a.args.isEmpty())
   810                 return true;
   811         }
   812         return false;
   813     }
   815     /** Enter a set of annotations. */
   816     private void actualEnterAnnotations(List<JCAnnotation> annotations,
   817                           Env<AttrContext> env,
   818                           Symbol s) {
   819         Map<TypeSymbol, ListBuffer<Attribute.Compound>> annotated =
   820                 new LinkedHashMap<TypeSymbol, ListBuffer<Attribute.Compound>>();
   821         Map<Attribute.Compound, DiagnosticPosition> pos =
   822                 new HashMap<Attribute.Compound, DiagnosticPosition>();
   824         for (List<JCAnnotation> al = annotations; !al.isEmpty(); al = al.tail) {
   825             JCAnnotation a = al.head;
   826             Attribute.Compound c = annotate.enterAnnotation(a,
   827                                                             syms.annotationType,
   828                                                             env);
   829             if (c == null) {
   830                 continue;
   831             }
   833             if (annotated.containsKey(a.type.tsym)) {
   834                 if (source.allowRepeatedAnnotations()) {
   835                     ListBuffer<Attribute.Compound> l = annotated.get(a.type.tsym);
   836                     l = l.append(c);
   837                     annotated.put(a.type.tsym, l);
   838                     pos.put(c, a.pos());
   839                 } else {
   840                     log.error(a.pos(), "duplicate.annotation");
   841                 }
   842             } else {
   843                 annotated.put(a.type.tsym, ListBuffer.of(c));
   844                 pos.put(c, a.pos());
   845             }
   847             // Note: @Deprecated has no effect on local variables and parameters
   848             if (!c.type.isErroneous()
   849                 && s.owner.kind != MTH
   850                 && types.isSameType(c.type, syms.deprecatedType)) {
   851                 s.flags_field |= Flags.DEPRECATED;
   852             }
   853         }
   855         s.setDeclarationAttributesWithCompletion(
   856                 annotate.new AnnotateRepeatedContext<Attribute.Compound>(env, annotated, pos, log, false));
   857     }
   859     /** Queue processing of an attribute default value. */
   860     void annotateDefaultValueLater(final JCExpression defaultValue,
   861                                    final Env<AttrContext> localEnv,
   862                                    final MethodSymbol m) {
   863         annotate.normal(new Annotate.Annotator() {
   864                 @Override
   865                 public String toString() {
   866                     return "annotate " + m.owner + "." +
   867                         m + " default " + defaultValue;
   868                 }
   870                 @Override
   871                 public void enterAnnotation() {
   872                     JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile);
   873                     try {
   874                         enterDefaultValue(defaultValue, localEnv, m);
   875                     } finally {
   876                         log.useSource(prev);
   877                     }
   878                 }
   879             });
   880     }
   882     /** Enter a default value for an attribute method. */
   883     private void enterDefaultValue(final JCExpression defaultValue,
   884                                    final Env<AttrContext> localEnv,
   885                                    final MethodSymbol m) {
   886         m.defaultValue = annotate.enterAttributeValue(m.type.getReturnType(),
   887                                                       defaultValue,
   888                                                       localEnv);
   889     }
   891 /* ********************************************************************
   892  * Source completer
   893  *********************************************************************/
   895     /** Complete entering a class.
   896      *  @param sym         The symbol of the class to be completed.
   897      */
   898     public void complete(Symbol sym) throws CompletionFailure {
   899         // Suppress some (recursive) MemberEnter invocations
   900         if (!completionEnabled) {
   901             // Re-install same completer for next time around and return.
   902             Assert.check((sym.flags() & Flags.COMPOUND) == 0);
   903             sym.completer = this;
   904             return;
   905         }
   907         ClassSymbol c = (ClassSymbol)sym;
   908         ClassType ct = (ClassType)c.type;
   909         Env<AttrContext> env = enter.typeEnvs.get(c);
   910         JCClassDecl tree = (JCClassDecl)env.tree;
   911         boolean wasFirst = isFirst;
   912         isFirst = false;
   914         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   915         try {
   916             // Save class environment for later member enter (2) processing.
   917             halfcompleted.append(env);
   919             // Mark class as not yet attributed.
   920             c.flags_field |= UNATTRIBUTED;
   922             // If this is a toplevel-class, make sure any preceding import
   923             // clauses have been seen.
   924             if (c.owner.kind == PCK) {
   925                 memberEnter(env.toplevel, env.enclosing(TOPLEVEL));
   926                 todo.append(env);
   927             }
   929             if (c.owner.kind == TYP)
   930                 c.owner.complete();
   932             // create an environment for evaluating the base clauses
   933             Env<AttrContext> baseEnv = baseEnv(tree, env);
   935             if (tree.extending != null)
   936                 typeAnnotate(tree.extending, baseEnv, sym);
   937             for (JCExpression impl : tree.implementing)
   938                 typeAnnotate(impl, baseEnv, sym);
   939             annotate.flush();
   941             // Determine supertype.
   942             Type supertype =
   943                 (tree.extending != null)
   944                 ? attr.attribBase(tree.extending, baseEnv, true, false, true)
   945                 : ((tree.mods.flags & Flags.ENUM) != 0)
   946                 ? attr.attribBase(enumBase(tree.pos, c), baseEnv,
   947                                   true, false, false)
   948                 : (c.fullname == names.java_lang_Object)
   949                 ? Type.noType
   950                 : syms.objectType;
   951             ct.supertype_field = modelMissingTypes(supertype, tree.extending, false);
   953             // Determine interfaces.
   954             ListBuffer<Type> interfaces = new ListBuffer<Type>();
   955             ListBuffer<Type> all_interfaces = null; // lazy init
   956             Set<Type> interfaceSet = new HashSet<Type>();
   957             List<JCExpression> interfaceTrees = tree.implementing;
   958             for (JCExpression iface : interfaceTrees) {
   959                 Type i = attr.attribBase(iface, baseEnv, false, true, true);
   960                 if (i.hasTag(CLASS)) {
   961                     interfaces.append(i);
   962                     if (all_interfaces != null) all_interfaces.append(i);
   963                     chk.checkNotRepeated(iface.pos(), types.erasure(i), interfaceSet);
   964                 } else {
   965                     if (all_interfaces == null)
   966                         all_interfaces = new ListBuffer<Type>().appendList(interfaces);
   967                     all_interfaces.append(modelMissingTypes(i, iface, true));
   968                 }
   969             }
   970             if ((c.flags_field & ANNOTATION) != 0) {
   971                 ct.interfaces_field = List.of(syms.annotationType);
   972                 ct.all_interfaces_field = ct.interfaces_field;
   973             }  else {
   974                 ct.interfaces_field = interfaces.toList();
   975                 ct.all_interfaces_field = (all_interfaces == null)
   976                         ? ct.interfaces_field : all_interfaces.toList();
   977             }
   979             if (c.fullname == names.java_lang_Object) {
   980                 if (tree.extending != null) {
   981                     chk.checkNonCyclic(tree.extending.pos(),
   982                                        supertype);
   983                     ct.supertype_field = Type.noType;
   984                 }
   985                 else if (tree.implementing.nonEmpty()) {
   986                     chk.checkNonCyclic(tree.implementing.head.pos(),
   987                                        ct.interfaces_field.head);
   988                     ct.interfaces_field = List.nil();
   989                 }
   990             }
   992             // Annotations.
   993             // In general, we cannot fully process annotations yet,  but we
   994             // can attribute the annotation types and then check to see if the
   995             // @Deprecated annotation is present.
   996             attr.attribAnnotationTypes(tree.mods.annotations, baseEnv);
   997             if (hasDeprecatedAnnotation(tree.mods.annotations))
   998                 c.flags_field |= DEPRECATED;
   999             annotateLater(tree.mods.annotations, baseEnv, c);
  1000             // class type parameters use baseEnv but everything uses env
  1002             chk.checkNonCyclicDecl(tree);
  1004             attr.attribTypeVariables(tree.typarams, baseEnv);
  1005             // Do this here, where we have the symbol.
  1006             for (JCTypeParameter tp : tree.typarams)
  1007                 typeAnnotate(tp, baseEnv, sym);
  1008             annotate.flush();
  1010             // Add default constructor if needed.
  1011             if ((c.flags() & INTERFACE) == 0 &&
  1012                 !TreeInfo.hasConstructors(tree.defs)) {
  1013                 List<Type> argtypes = List.nil();
  1014                 List<Type> typarams = List.nil();
  1015                 List<Type> thrown = List.nil();
  1016                 long ctorFlags = 0;
  1017                 boolean based = false;
  1018                 boolean addConstructor = true;
  1019                 JCNewClass nc = null;
  1020                 if (c.name.isEmpty()) {
  1021                     nc = (JCNewClass)env.next.tree;
  1022                     if (nc.constructor != null) {
  1023                         addConstructor = nc.constructor.kind != ERR;
  1024                         Type superConstrType = types.memberType(c.type,
  1025                                                                 nc.constructor);
  1026                         argtypes = superConstrType.getParameterTypes();
  1027                         typarams = superConstrType.getTypeArguments();
  1028                         ctorFlags = nc.constructor.flags() & VARARGS;
  1029                         if (nc.encl != null) {
  1030                             argtypes = argtypes.prepend(nc.encl.type);
  1031                             based = true;
  1033                         thrown = superConstrType.getThrownTypes();
  1036                 if (addConstructor) {
  1037                     MethodSymbol basedConstructor = nc != null ?
  1038                             (MethodSymbol)nc.constructor : null;
  1039                     JCTree constrDef = DefaultConstructor(make.at(tree.pos), c,
  1040                                                         basedConstructor,
  1041                                                         typarams, argtypes, thrown,
  1042                                                         ctorFlags, based);
  1043                     tree.defs = tree.defs.prepend(constrDef);
  1047             // enter symbols for 'this' into current scope.
  1048             VarSymbol thisSym =
  1049                 new VarSymbol(FINAL | HASINIT, names._this, c.type, c);
  1050             thisSym.pos = Position.FIRSTPOS;
  1051             env.info.scope.enter(thisSym);
  1052             // if this is a class, enter symbol for 'super' into current scope.
  1053             if ((c.flags_field & INTERFACE) == 0 &&
  1054                     ct.supertype_field.hasTag(CLASS)) {
  1055                 VarSymbol superSym =
  1056                     new VarSymbol(FINAL | HASINIT, names._super,
  1057                                   ct.supertype_field, c);
  1058                 superSym.pos = Position.FIRSTPOS;
  1059                 env.info.scope.enter(superSym);
  1062             // check that no package exists with same fully qualified name,
  1063             // but admit classes in the unnamed package which have the same
  1064             // name as a top-level package.
  1065             if (checkClash &&
  1066                 c.owner.kind == PCK && c.owner != syms.unnamedPackage &&
  1067                 reader.packageExists(c.fullname)) {
  1068                 log.error(tree.pos, "clash.with.pkg.of.same.name", Kinds.kindName(sym), c);
  1070             if (c.owner.kind == PCK && (c.flags_field & PUBLIC) == 0 &&
  1071                 !env.toplevel.sourcefile.isNameCompatible(c.name.toString(),JavaFileObject.Kind.SOURCE)) {
  1072                 c.flags_field |= AUXILIARY;
  1074         } catch (CompletionFailure ex) {
  1075             chk.completionError(tree.pos(), ex);
  1076         } finally {
  1077             log.useSource(prev);
  1080         // Enter all member fields and methods of a set of half completed
  1081         // classes in a second phase.
  1082         if (wasFirst) {
  1083             try {
  1084                 while (halfcompleted.nonEmpty()) {
  1085                     finish(halfcompleted.next());
  1087             } finally {
  1088                 isFirst = true;
  1091         if (allowTypeAnnos) {
  1092             TypeAnnotations.organizeTypeAnnotationsSignatures(syms, names, log, tree, annotate);
  1096     /*
  1097      * If the symbol is non-null, attach the type annotation to it.
  1098      */
  1099     private void actualEnterTypeAnnotations(final List<JCAnnotation> annotations,
  1100             final Env<AttrContext> env,
  1101             final Symbol s) {
  1102         Map<TypeSymbol, ListBuffer<Attribute.TypeCompound>> annotated =
  1103                 new LinkedHashMap<TypeSymbol, ListBuffer<Attribute.TypeCompound>>();
  1104         Map<Attribute.TypeCompound, DiagnosticPosition> pos =
  1105                 new HashMap<Attribute.TypeCompound, DiagnosticPosition>();
  1107         for (List<JCAnnotation> al = annotations; !al.isEmpty(); al = al.tail) {
  1108             JCAnnotation a = al.head;
  1109             Attribute.TypeCompound tc = annotate.enterTypeAnnotation(a,
  1110                     syms.annotationType,
  1111                     env);
  1112             if (tc == null) {
  1113                 continue;
  1116             if (annotated.containsKey(a.type.tsym)) {
  1117                 if (source.allowRepeatedAnnotations()) {
  1118                     ListBuffer<Attribute.TypeCompound> l = annotated.get(a.type.tsym);
  1119                     l = l.append(tc);
  1120                     annotated.put(a.type.tsym, l);
  1121                     pos.put(tc, a.pos());
  1122                 } else {
  1123                     log.error(a.pos(), "duplicate.annotation");
  1125             } else {
  1126                 annotated.put(a.type.tsym, ListBuffer.of(tc));
  1127                 pos.put(tc, a.pos());
  1131         if (s != null) {
  1132             s.appendTypeAttributesWithCompletion(
  1133                     annotate.new AnnotateRepeatedContext<Attribute.TypeCompound>(env, annotated, pos, log, true));
  1137     public void typeAnnotate(final JCTree tree, final Env<AttrContext> env, final Symbol sym) {
  1138         if (allowTypeAnnos) {
  1139             tree.accept(new TypeAnnotate(env, sym));
  1143     /**
  1144      * We need to use a TreeScanner, because it is not enough to visit the top-level
  1145      * annotations. We also need to visit type arguments, etc.
  1146      */
  1147     private class TypeAnnotate extends TreeScanner {
  1148         private Env<AttrContext> env;
  1149         private Symbol sym;
  1151         public TypeAnnotate(final Env<AttrContext> env, final Symbol sym) {
  1152             this.env = env;
  1153             this.sym = sym;
  1156         void annotateTypeLater(final List<JCAnnotation> annotations) {
  1157             if (annotations.isEmpty()) {
  1158                 return;
  1161             annotate.normal(new Annotate.Annotator() {
  1162                 @Override
  1163                 public String toString() {
  1164                     return "type annotate " + annotations + " onto " + sym + " in " + sym.owner;
  1166                 @Override
  1167                 public void enterAnnotation() {
  1168                     JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
  1169                     try {
  1170                         actualEnterTypeAnnotations(annotations, env, sym);
  1171                     } finally {
  1172                         log.useSource(prev);
  1175             });
  1178         @Override
  1179         public void visitAnnotatedType(final JCAnnotatedType tree) {
  1180             annotateTypeLater(tree.annotations);
  1181             super.visitAnnotatedType(tree);
  1184         @Override
  1185         public void visitTypeParameter(final JCTypeParameter tree) {
  1186             annotateTypeLater(tree.annotations);
  1187             super.visitTypeParameter(tree);
  1190         @Override
  1191         public void visitNewArray(final JCNewArray tree) {
  1192             annotateTypeLater(tree.annotations);
  1193             for (List<JCAnnotation> dimAnnos : tree.dimAnnotations)
  1194                 annotateTypeLater(dimAnnos);
  1195             super.visitNewArray(tree);
  1198         @Override
  1199         public void visitMethodDef(final JCMethodDecl tree) {
  1200             scan(tree.mods);
  1201             scan(tree.restype);
  1202             scan(tree.typarams);
  1203             scan(tree.recvparam);
  1204             scan(tree.params);
  1205             scan(tree.thrown);
  1206             scan(tree.defaultValue);
  1207             // Do not annotate the body, just the signature.
  1208             // scan(tree.body);
  1211         @Override
  1212         public void visitVarDef(final JCVariableDecl tree) {
  1213             if (sym != null && sym.kind == Kinds.VAR) {
  1214                 // Don't visit a parameter once when the sym is the method
  1215                 // and once when the sym is the parameter.
  1216                 scan(tree.mods);
  1217                 scan(tree.vartype);
  1219             scan(tree.init);
  1222         @Override
  1223         public void visitClassDef(JCClassDecl tree) {
  1224             // We can only hit a classdef if it is declared within
  1225             // a method. Ignore it - the class will be visited
  1226             // separately later.
  1229         @Override
  1230         public void visitNewClass(JCNewClass tree) {
  1231             if (tree.def == null) {
  1232                 // For an anonymous class instantiation the class
  1233                 // will be visited separately.
  1234                 super.visitNewClass(tree);
  1240     private Env<AttrContext> baseEnv(JCClassDecl tree, Env<AttrContext> env) {
  1241         Scope baseScope = new Scope(tree.sym);
  1242         //import already entered local classes into base scope
  1243         for (Scope.Entry e = env.outer.info.scope.elems ; e != null ; e = e.sibling) {
  1244             if (e.sym.isLocal()) {
  1245                 baseScope.enter(e.sym);
  1248         //import current type-parameters into base scope
  1249         if (tree.typarams != null)
  1250             for (List<JCTypeParameter> typarams = tree.typarams;
  1251                  typarams.nonEmpty();
  1252                  typarams = typarams.tail)
  1253                 baseScope.enter(typarams.head.type.tsym);
  1254         Env<AttrContext> outer = env.outer; // the base clause can't see members of this class
  1255         Env<AttrContext> localEnv = outer.dup(tree, outer.info.dup(baseScope));
  1256         localEnv.baseClause = true;
  1257         localEnv.outer = outer;
  1258         localEnv.info.isSelfCall = false;
  1259         return localEnv;
  1262     /** Enter member fields and methods of a class
  1263      *  @param env        the environment current for the class block.
  1264      */
  1265     private void finish(Env<AttrContext> env) {
  1266         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
  1267         try {
  1268             JCClassDecl tree = (JCClassDecl)env.tree;
  1269             finishClass(tree, env);
  1270         } finally {
  1271             log.useSource(prev);
  1275     /** Generate a base clause for an enum type.
  1276      *  @param pos              The position for trees and diagnostics, if any
  1277      *  @param c                The class symbol of the enum
  1278      */
  1279     private JCExpression enumBase(int pos, ClassSymbol c) {
  1280         JCExpression result = make.at(pos).
  1281             TypeApply(make.QualIdent(syms.enumSym),
  1282                       List.<JCExpression>of(make.Type(c.type)));
  1283         return result;
  1286     Type modelMissingTypes(Type t, final JCExpression tree, final boolean interfaceExpected) {
  1287         if (!t.hasTag(ERROR))
  1288             return t;
  1290         return new ErrorType(((ErrorType) t).getOriginalType(), t.tsym) {
  1291             private Type modelType;
  1293             @Override
  1294             public Type getModelType() {
  1295                 if (modelType == null)
  1296                     modelType = new Synthesizer(getOriginalType(), interfaceExpected).visit(tree);
  1297                 return modelType;
  1299         };
  1301     // where
  1302     private class Synthesizer extends JCTree.Visitor {
  1303         Type originalType;
  1304         boolean interfaceExpected;
  1305         List<ClassSymbol> synthesizedSymbols = List.nil();
  1306         Type result;
  1308         Synthesizer(Type originalType, boolean interfaceExpected) {
  1309             this.originalType = originalType;
  1310             this.interfaceExpected = interfaceExpected;
  1313         Type visit(JCTree tree) {
  1314             tree.accept(this);
  1315             return result;
  1318         List<Type> visit(List<? extends JCTree> trees) {
  1319             ListBuffer<Type> lb = new ListBuffer<Type>();
  1320             for (JCTree t: trees)
  1321                 lb.append(visit(t));
  1322             return lb.toList();
  1325         @Override
  1326         public void visitTree(JCTree tree) {
  1327             result = syms.errType;
  1330         @Override
  1331         public void visitIdent(JCIdent tree) {
  1332             if (!tree.type.hasTag(ERROR)) {
  1333                 result = tree.type;
  1334             } else {
  1335                 result = synthesizeClass(tree.name, syms.unnamedPackage).type;
  1339         @Override
  1340         public void visitSelect(JCFieldAccess tree) {
  1341             if (!tree.type.hasTag(ERROR)) {
  1342                 result = tree.type;
  1343             } else {
  1344                 Type selectedType;
  1345                 boolean prev = interfaceExpected;
  1346                 try {
  1347                     interfaceExpected = false;
  1348                     selectedType = visit(tree.selected);
  1349                 } finally {
  1350                     interfaceExpected = prev;
  1352                 ClassSymbol c = synthesizeClass(tree.name, selectedType.tsym);
  1353                 result = c.type;
  1357         @Override
  1358         public void visitTypeApply(JCTypeApply tree) {
  1359             if (!tree.type.hasTag(ERROR)) {
  1360                 result = tree.type;
  1361             } else {
  1362                 ClassType clazzType = (ClassType) visit(tree.clazz);
  1363                 if (synthesizedSymbols.contains(clazzType.tsym))
  1364                     synthesizeTyparams((ClassSymbol) clazzType.tsym, tree.arguments.size());
  1365                 final List<Type> actuals = visit(tree.arguments);
  1366                 result = new ErrorType(tree.type, clazzType.tsym) {
  1367                     @Override
  1368                     public List<Type> getTypeArguments() {
  1369                         return actuals;
  1371                 };
  1375         ClassSymbol synthesizeClass(Name name, Symbol owner) {
  1376             int flags = interfaceExpected ? INTERFACE : 0;
  1377             ClassSymbol c = new ClassSymbol(flags, name, owner);
  1378             c.members_field = new Scope.ErrorScope(c);
  1379             c.type = new ErrorType(originalType, c) {
  1380                 @Override
  1381                 public List<Type> getTypeArguments() {
  1382                     return typarams_field;
  1384             };
  1385             synthesizedSymbols = synthesizedSymbols.prepend(c);
  1386             return c;
  1389         void synthesizeTyparams(ClassSymbol sym, int n) {
  1390             ClassType ct = (ClassType) sym.type;
  1391             Assert.check(ct.typarams_field.isEmpty());
  1392             if (n == 1) {
  1393                 TypeVar v = new TypeVar(names.fromString("T"), sym, syms.botType);
  1394                 ct.typarams_field = ct.typarams_field.prepend(v);
  1395             } else {
  1396                 for (int i = n; i > 0; i--) {
  1397                     TypeVar v = new TypeVar(names.fromString("T" + i), sym, syms.botType);
  1398                     ct.typarams_field = ct.typarams_field.prepend(v);
  1405 /* ***************************************************************************
  1406  * tree building
  1407  ****************************************************************************/
  1409     /** Generate default constructor for given class. For classes different
  1410      *  from java.lang.Object, this is:
  1412      *    c(argtype_0 x_0, ..., argtype_n x_n) throws thrown {
  1413      *      super(x_0, ..., x_n)
  1414      *    }
  1416      *  or, if based == true:
  1418      *    c(argtype_0 x_0, ..., argtype_n x_n) throws thrown {
  1419      *      x_0.super(x_1, ..., x_n)
  1420      *    }
  1422      *  @param make     The tree factory.
  1423      *  @param c        The class owning the default constructor.
  1424      *  @param argtypes The parameter types of the constructor.
  1425      *  @param thrown   The thrown exceptions of the constructor.
  1426      *  @param based    Is first parameter a this$n?
  1427      */
  1428     JCTree DefaultConstructor(TreeMaker make,
  1429                             ClassSymbol c,
  1430                             MethodSymbol baseInit,
  1431                             List<Type> typarams,
  1432                             List<Type> argtypes,
  1433                             List<Type> thrown,
  1434                             long flags,
  1435                             boolean based) {
  1436         JCTree result;
  1437         if ((c.flags() & ENUM) != 0 &&
  1438             (types.supertype(c.type).tsym == syms.enumSym)) {
  1439             // constructors of true enums are private
  1440             flags = (flags & ~AccessFlags) | PRIVATE | GENERATEDCONSTR;
  1441         } else
  1442             flags |= (c.flags() & AccessFlags) | GENERATEDCONSTR;
  1443         if (c.name.isEmpty()) {
  1444             flags |= ANONCONSTR;
  1446         Type mType = new MethodType(argtypes, null, thrown, c);
  1447         Type initType = typarams.nonEmpty() ?
  1448                 new ForAll(typarams, mType) :
  1449                 mType;
  1450         MethodSymbol init = new MethodSymbol(flags, names.init,
  1451                 initType, c);
  1452         init.params = createDefaultConstructorParams(make, baseInit, init,
  1453                 argtypes, based);
  1454         List<JCVariableDecl> params = make.Params(argtypes, init);
  1455         List<JCStatement> stats = List.nil();
  1456         if (c.type != syms.objectType) {
  1457             stats = stats.prepend(SuperCall(make, typarams, params, based));
  1459         result = make.MethodDef(init, make.Block(0, stats));
  1460         return result;
  1463     private List<VarSymbol> createDefaultConstructorParams(
  1464             TreeMaker make,
  1465             MethodSymbol baseInit,
  1466             MethodSymbol init,
  1467             List<Type> argtypes,
  1468             boolean based) {
  1469         List<VarSymbol> initParams = null;
  1470         List<Type> argTypesList = argtypes;
  1471         if (based) {
  1472             /*  In this case argtypes will have an extra type, compared to baseInit,
  1473              *  corresponding to the type of the enclosing instance i.e.:
  1475              *  Inner i = outer.new Inner(1){}
  1477              *  in the above example argtypes will be (Outer, int) and baseInit
  1478              *  will have parameter's types (int). So in this case we have to add
  1479              *  first the extra type in argtypes and then get the names of the
  1480              *  parameters from baseInit.
  1481              */
  1482             initParams = List.nil();
  1483             VarSymbol param = new VarSymbol(0, make.paramName(0), argtypes.head, init);
  1484             initParams = initParams.append(param);
  1485             argTypesList = argTypesList.tail;
  1487         if (baseInit != null && baseInit.params != null &&
  1488             baseInit.params.nonEmpty() && argTypesList.nonEmpty()) {
  1489             initParams = (initParams == null) ? List.<VarSymbol>nil() : initParams;
  1490             List<VarSymbol> baseInitParams = baseInit.params;
  1491             while (baseInitParams.nonEmpty() && argTypesList.nonEmpty()) {
  1492                 VarSymbol param = new VarSymbol(baseInitParams.head.flags(),
  1493                         baseInitParams.head.name, argTypesList.head, init);
  1494                 initParams = initParams.append(param);
  1495                 baseInitParams = baseInitParams.tail;
  1496                 argTypesList = argTypesList.tail;
  1499         return initParams;
  1502     /** Generate call to superclass constructor. This is:
  1504      *    super(id_0, ..., id_n)
  1506      * or, if based == true
  1508      *    id_0.super(id_1,...,id_n)
  1510      *  where id_0, ..., id_n are the names of the given parameters.
  1512      *  @param make    The tree factory
  1513      *  @param params  The parameters that need to be passed to super
  1514      *  @param typarams  The type parameters that need to be passed to super
  1515      *  @param based   Is first parameter a this$n?
  1516      */
  1517     JCExpressionStatement SuperCall(TreeMaker make,
  1518                    List<Type> typarams,
  1519                    List<JCVariableDecl> params,
  1520                    boolean based) {
  1521         JCExpression meth;
  1522         if (based) {
  1523             meth = make.Select(make.Ident(params.head), names._super);
  1524             params = params.tail;
  1525         } else {
  1526             meth = make.Ident(names._super);
  1528         List<JCExpression> typeargs = typarams.nonEmpty() ? make.Types(typarams) : null;
  1529         return make.Exec(make.Apply(typeargs, meth, make.Idents(params)));

mercurial