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

Wed, 15 May 2013 14:00:31 +0100

author
mcimadamore
date
Wed, 15 May 2013 14:00:31 +0100
changeset 1759
05ec778794d0
parent 1755
ddb4a2bfcd82
child 1791
e9855150c5b0
permissions
-rw-r--r--

8012003: Method diagnostics resolution need to be simplified in some cases
Summary: Unfold method resolution diagnostics when they mention errors in poly expressions
Reviewed-by: jjg, vromero

     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     }
   114     /** A queue for classes whose members still need to be entered into the
   115      *  symbol table.
   116      */
   117     ListBuffer<Env<AttrContext>> halfcompleted = new ListBuffer<Env<AttrContext>>();
   119     /** Set to true only when the first of a set of classes is
   120      *  processed from the halfcompleted queue.
   121      */
   122     boolean isFirst = true;
   124     /** A flag to disable completion from time to time during member
   125      *  enter, as we only need to look up types.  This avoids
   126      *  unnecessarily deep recursion.
   127      */
   128     boolean completionEnabled = true;
   130     /* ---------- Processing import clauses ----------------
   131      */
   133     /** Import all classes of a class or package on demand.
   134      *  @param pos           Position to be used for error reporting.
   135      *  @param tsym          The class or package the members of which are imported.
   136      *  @param env           The env in which the imported classes will be entered.
   137      */
   138     private void importAll(int pos,
   139                            final TypeSymbol tsym,
   140                            Env<AttrContext> env) {
   141         // Check that packages imported from exist (JLS ???).
   142         if (tsym.kind == PCK && tsym.members().elems == null && !tsym.exists()) {
   143             // If we can't find java.lang, exit immediately.
   144             if (((PackageSymbol)tsym).fullname.equals(names.java_lang)) {
   145                 JCDiagnostic msg = diags.fragment("fatal.err.no.java.lang");
   146                 throw new FatalError(msg);
   147             } else {
   148                 log.error(DiagnosticFlag.RESOLVE_ERROR, pos, "doesnt.exist", tsym);
   149             }
   150         }
   151         env.toplevel.starImportScope.importAll(tsym.members());
   152     }
   154     /** Import all static members of a class or package on demand.
   155      *  @param pos           Position to be used for error reporting.
   156      *  @param tsym          The class or package the members of which are imported.
   157      *  @param env           The env in which the imported classes will be entered.
   158      */
   159     private void importStaticAll(int pos,
   160                                  final TypeSymbol tsym,
   161                                  Env<AttrContext> env) {
   162         final JavaFileObject sourcefile = env.toplevel.sourcefile;
   163         final Scope toScope = env.toplevel.starImportScope;
   164         final PackageSymbol packge = env.toplevel.packge;
   165         final TypeSymbol origin = tsym;
   167         // enter imported types immediately
   168         new Object() {
   169             Set<Symbol> processed = new HashSet<Symbol>();
   170             void importFrom(TypeSymbol tsym) {
   171                 if (tsym == null || !processed.add(tsym))
   172                     return;
   174                 // also import inherited names
   175                 importFrom(types.supertype(tsym.type).tsym);
   176                 for (Type t : types.interfaces(tsym.type))
   177                     importFrom(t.tsym);
   179                 final Scope fromScope = tsym.members();
   180                 for (Scope.Entry e = fromScope.elems; e != null; e = e.sibling) {
   181                     Symbol sym = e.sym;
   182                     if (sym.kind == TYP &&
   183                         (sym.flags() & STATIC) != 0 &&
   184                         staticImportAccessible(sym, packge) &&
   185                         sym.isMemberOf(origin, types) &&
   186                         !toScope.includes(sym))
   187                         toScope.enter(sym, fromScope, origin.members());
   188                 }
   189             }
   190         }.importFrom(tsym);
   192         // enter non-types before annotations that might use them
   193         annotate.earlier(new Annotate.Annotator() {
   194             Set<Symbol> processed = new HashSet<Symbol>();
   196             public String toString() {
   197                 return "import static " + tsym + ".*" + " in " + sourcefile;
   198             }
   199             void importFrom(TypeSymbol tsym) {
   200                 if (tsym == null || !processed.add(tsym))
   201                     return;
   203                 // also import inherited names
   204                 importFrom(types.supertype(tsym.type).tsym);
   205                 for (Type t : types.interfaces(tsym.type))
   206                     importFrom(t.tsym);
   208                 final Scope fromScope = tsym.members();
   209                 for (Scope.Entry e = fromScope.elems; e != null; e = e.sibling) {
   210                     Symbol sym = e.sym;
   211                     if (sym.isStatic() && sym.kind != TYP &&
   212                         staticImportAccessible(sym, packge) &&
   213                         !toScope.includes(sym) &&
   214                         sym.isMemberOf(origin, types)) {
   215                         toScope.enter(sym, fromScope, origin.members());
   216                     }
   217                 }
   218             }
   219             public void enterAnnotation() {
   220                 importFrom(tsym);
   221             }
   222         });
   223     }
   225     // is the sym accessible everywhere in packge?
   226     boolean staticImportAccessible(Symbol sym, PackageSymbol packge) {
   227         int flags = (int)(sym.flags() & AccessFlags);
   228         switch (flags) {
   229         default:
   230         case PUBLIC:
   231             return true;
   232         case PRIVATE:
   233             return false;
   234         case 0:
   235         case PROTECTED:
   236             return sym.packge() == packge;
   237         }
   238     }
   240     /** Import statics types of a given name.  Non-types are handled in Attr.
   241      *  @param pos           Position to be used for error reporting.
   242      *  @param tsym          The class from which the name is imported.
   243      *  @param name          The (simple) name being imported.
   244      *  @param env           The environment containing the named import
   245      *                  scope to add to.
   246      */
   247     private void importNamedStatic(final DiagnosticPosition pos,
   248                                    final TypeSymbol tsym,
   249                                    final Name name,
   250                                    final Env<AttrContext> env) {
   251         if (tsym.kind != TYP) {
   252             log.error(DiagnosticFlag.RECOVERABLE, pos, "static.imp.only.classes.and.interfaces");
   253             return;
   254         }
   256         final Scope toScope = env.toplevel.namedImportScope;
   257         final PackageSymbol packge = env.toplevel.packge;
   258         final TypeSymbol origin = tsym;
   260         // enter imported types immediately
   261         new Object() {
   262             Set<Symbol> processed = new HashSet<Symbol>();
   263             void importFrom(TypeSymbol tsym) {
   264                 if (tsym == null || !processed.add(tsym))
   265                     return;
   267                 // also import inherited names
   268                 importFrom(types.supertype(tsym.type).tsym);
   269                 for (Type t : types.interfaces(tsym.type))
   270                     importFrom(t.tsym);
   272                 for (Scope.Entry e = tsym.members().lookup(name);
   273                      e.scope != null;
   274                      e = e.next()) {
   275                     Symbol sym = e.sym;
   276                     if (sym.isStatic() &&
   277                         sym.kind == TYP &&
   278                         staticImportAccessible(sym, packge) &&
   279                         sym.isMemberOf(origin, types) &&
   280                         chk.checkUniqueStaticImport(pos, sym, toScope))
   281                         toScope.enter(sym, sym.owner.members(), origin.members());
   282                 }
   283             }
   284         }.importFrom(tsym);
   286         // enter non-types before annotations that might use them
   287         annotate.earlier(new Annotate.Annotator() {
   288             Set<Symbol> processed = new HashSet<Symbol>();
   289             boolean found = false;
   291             public String toString() {
   292                 return "import static " + tsym + "." + name;
   293             }
   294             void importFrom(TypeSymbol tsym) {
   295                 if (tsym == null || !processed.add(tsym))
   296                     return;
   298                 // also import inherited names
   299                 importFrom(types.supertype(tsym.type).tsym);
   300                 for (Type t : types.interfaces(tsym.type))
   301                     importFrom(t.tsym);
   303                 for (Scope.Entry e = tsym.members().lookup(name);
   304                      e.scope != null;
   305                      e = e.next()) {
   306                     Symbol sym = e.sym;
   307                     if (sym.isStatic() &&
   308                         staticImportAccessible(sym, packge) &&
   309                         sym.isMemberOf(origin, types)) {
   310                         found = true;
   311                         if (sym.kind == MTH ||
   312                             sym.kind != TYP && chk.checkUniqueStaticImport(pos, sym, toScope))
   313                             toScope.enter(sym, sym.owner.members(), origin.members());
   314                     }
   315                 }
   316             }
   317             public void enterAnnotation() {
   318                 JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   319                 try {
   320                     importFrom(tsym);
   321                     if (!found) {
   322                         log.error(pos, "cant.resolve.location",
   323                                   KindName.STATIC,
   324                                   name, List.<Type>nil(), List.<Type>nil(),
   325                                   Kinds.typeKindName(tsym.type),
   326                                   tsym.type);
   327                     }
   328                 } finally {
   329                     log.useSource(prev);
   330                 }
   331             }
   332         });
   333     }
   334     /** Import given class.
   335      *  @param pos           Position to be used for error reporting.
   336      *  @param tsym          The class to be imported.
   337      *  @param env           The environment containing the named import
   338      *                  scope to add to.
   339      */
   340     private void importNamed(DiagnosticPosition pos, Symbol tsym, Env<AttrContext> env) {
   341         if (tsym.kind == TYP &&
   342             chk.checkUniqueImport(pos, tsym, env.toplevel.namedImportScope))
   343             env.toplevel.namedImportScope.enter(tsym, tsym.owner.members());
   344     }
   346     /** Construct method type from method signature.
   347      *  @param typarams    The method's type parameters.
   348      *  @param params      The method's value parameters.
   349      *  @param res             The method's result type,
   350      *                 null if it is a constructor.
   351      *  @param recvparam       The method's receiver parameter,
   352      *                 null if none given; TODO: or already set here?
   353      *  @param thrown      The method's thrown exceptions.
   354      *  @param env             The method's (local) environment.
   355      */
   356     Type signature(List<JCTypeParameter> typarams,
   357                    List<JCVariableDecl> params,
   358                    JCTree res,
   359                    JCVariableDecl recvparam,
   360                    List<JCExpression> thrown,
   361                    Env<AttrContext> env) {
   363         // Enter and attribute type parameters.
   364         List<Type> tvars = enter.classEnter(typarams, env);
   365         attr.attribTypeVariables(typarams, env);
   367         // Enter and attribute value parameters.
   368         ListBuffer<Type> argbuf = new ListBuffer<Type>();
   369         for (List<JCVariableDecl> l = params; l.nonEmpty(); l = l.tail) {
   370             memberEnter(l.head, env);
   371             argbuf.append(l.head.vartype.type);
   372         }
   374         // Attribute result type, if one is given.
   375         Type restype = res == null ? syms.voidType : attr.attribType(res, env);
   377         // Attribute receiver type, if one is given.
   378         Type recvtype;
   379         if (recvparam!=null) {
   380             memberEnter(recvparam, env);
   381             recvtype = recvparam.vartype.type;
   382         } else {
   383             recvtype = null;
   384         }
   386         // Attribute thrown exceptions.
   387         ListBuffer<Type> thrownbuf = new ListBuffer<Type>();
   388         for (List<JCExpression> l = thrown; l.nonEmpty(); l = l.tail) {
   389             Type exc = attr.attribType(l.head, env);
   390             if (!exc.hasTag(TYPEVAR))
   391                 exc = chk.checkClassType(l.head.pos(), exc);
   392             thrownbuf.append(exc);
   393         }
   394         MethodType mtype = new MethodType(argbuf.toList(),
   395                                     restype,
   396                                     thrownbuf.toList(),
   397                                     syms.methodClass);
   398         mtype.recvtype = recvtype;
   400         return tvars.isEmpty() ? mtype : new ForAll(tvars, mtype);
   401     }
   403 /* ********************************************************************
   404  * Visitor methods for member enter
   405  *********************************************************************/
   407     /** Visitor argument: the current environment
   408      */
   409     protected Env<AttrContext> env;
   411     /** Enter field and method definitions and process import
   412      *  clauses, catching any completion failure exceptions.
   413      */
   414     protected void memberEnter(JCTree tree, Env<AttrContext> env) {
   415         Env<AttrContext> prevEnv = this.env;
   416         try {
   417             this.env = env;
   418             tree.accept(this);
   419         }  catch (CompletionFailure ex) {
   420             chk.completionError(tree.pos(), ex);
   421         } finally {
   422             this.env = prevEnv;
   423         }
   424     }
   426     /** Enter members from a list of trees.
   427      */
   428     void memberEnter(List<? extends JCTree> trees, Env<AttrContext> env) {
   429         for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
   430             memberEnter(l.head, env);
   431     }
   433     /** Enter members for a class.
   434      */
   435     void finishClass(JCClassDecl tree, Env<AttrContext> env) {
   436         if ((tree.mods.flags & Flags.ENUM) != 0 &&
   437             (types.supertype(tree.sym.type).tsym.flags() & Flags.ENUM) == 0) {
   438             addEnumMembers(tree, env);
   439         }
   440         memberEnter(tree.defs, env);
   441     }
   443     /** Add the implicit members for an enum type
   444      *  to the symbol table.
   445      */
   446     private void addEnumMembers(JCClassDecl tree, Env<AttrContext> env) {
   447         JCExpression valuesType = make.Type(new ArrayType(tree.sym.type, syms.arrayClass));
   449         // public static T[] values() { return ???; }
   450         JCMethodDecl values = make.
   451             MethodDef(make.Modifiers(Flags.PUBLIC|Flags.STATIC),
   452                       names.values,
   453                       valuesType,
   454                       List.<JCTypeParameter>nil(),
   455                       List.<JCVariableDecl>nil(),
   456                       List.<JCExpression>nil(), // thrown
   457                       null, //make.Block(0, Tree.emptyList.prepend(make.Return(make.Ident(names._null)))),
   458                       null);
   459         memberEnter(values, env);
   461         // public static T valueOf(String name) { return ???; }
   462         JCMethodDecl valueOf = make.
   463             MethodDef(make.Modifiers(Flags.PUBLIC|Flags.STATIC),
   464                       names.valueOf,
   465                       make.Type(tree.sym.type),
   466                       List.<JCTypeParameter>nil(),
   467                       List.of(make.VarDef(make.Modifiers(Flags.PARAMETER |
   468                                                          Flags.MANDATED),
   469                                             names.fromString("name"),
   470                                             make.Type(syms.stringType), null)),
   471                       List.<JCExpression>nil(), // thrown
   472                       null, //make.Block(0, Tree.emptyList.prepend(make.Return(make.Ident(names._null)))),
   473                       null);
   474         memberEnter(valueOf, env);
   475     }
   477     public void visitTopLevel(JCCompilationUnit tree) {
   478         if (tree.starImportScope.elems != null) {
   479             // we must have already processed this toplevel
   480             return;
   481         }
   483         // check that no class exists with same fully qualified name as
   484         // toplevel package
   485         if (checkClash && tree.pid != null) {
   486             Symbol p = tree.packge;
   487             while (p.owner != syms.rootPackage) {
   488                 p.owner.complete(); // enter all class members of p
   489                 if (syms.classes.get(p.getQualifiedName()) != null) {
   490                     log.error(tree.pos,
   491                               "pkg.clashes.with.class.of.same.name",
   492                               p);
   493                 }
   494                 p = p.owner;
   495             }
   496         }
   498         // process package annotations
   499         annotateLater(tree.packageAnnotations, env, tree.packge);
   501         // Import-on-demand java.lang.
   502         importAll(tree.pos, reader.enterPackage(names.java_lang), env);
   504         // Process all import clauses.
   505         memberEnter(tree.defs, env);
   506     }
   508     // process the non-static imports and the static imports of types.
   509     public void visitImport(JCImport tree) {
   510         JCFieldAccess imp = (JCFieldAccess)tree.qualid;
   511         Name name = TreeInfo.name(imp);
   513         // Create a local environment pointing to this tree to disable
   514         // effects of other imports in Resolve.findGlobalType
   515         Env<AttrContext> localEnv = env.dup(tree);
   517         TypeSymbol p = attr.attribImportQualifier(tree, localEnv).tsym;
   518         if (name == names.asterisk) {
   519             // Import on demand.
   520             chk.checkCanonical(imp.selected);
   521             if (tree.staticImport)
   522                 importStaticAll(tree.pos, p, env);
   523             else
   524                 importAll(tree.pos, p, env);
   525         } else {
   526             // Named type import.
   527             if (tree.staticImport) {
   528                 importNamedStatic(tree.pos(), p, name, localEnv);
   529                 chk.checkCanonical(imp.selected);
   530             } else {
   531                 TypeSymbol c = attribImportType(imp, localEnv).tsym;
   532                 chk.checkCanonical(imp);
   533                 importNamed(tree.pos(), c, env);
   534             }
   535         }
   536     }
   538     public void visitMethodDef(JCMethodDecl tree) {
   539         Scope enclScope = enter.enterScope(env);
   540         MethodSymbol m = new MethodSymbol(0, tree.name, null, enclScope.owner);
   541         m.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, m, tree);
   542         tree.sym = m;
   544         //if this is a default method, add the DEFAULT flag to the enclosing interface
   545         if ((tree.mods.flags & DEFAULT) != 0) {
   546             m.enclClass().flags_field |= DEFAULT;
   547         }
   549         Env<AttrContext> localEnv = methodEnv(tree, env);
   551         DeferredLintHandler prevLintHandler =
   552                 chk.setDeferredLintHandler(deferredLintHandler.setPos(tree.pos()));
   553         try {
   554             // Compute the method type
   555             m.type = signature(tree.typarams, tree.params,
   556                                tree.restype, tree.recvparam,
   557                                tree.thrown,
   558                                localEnv);
   559         } finally {
   560             chk.setDeferredLintHandler(prevLintHandler);
   561         }
   563         // Set m.params
   564         ListBuffer<VarSymbol> params = new ListBuffer<VarSymbol>();
   565         JCVariableDecl lastParam = null;
   566         for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
   567             JCVariableDecl param = lastParam = l.head;
   568             params.append(Assert.checkNonNull(param.sym));
   569         }
   570         m.params = params.toList();
   572         // mark the method varargs, if necessary
   573         if (lastParam != null && (lastParam.mods.flags & Flags.VARARGS) != 0)
   574             m.flags_field |= Flags.VARARGS;
   576         localEnv.info.scope.leave();
   577         if (chk.checkUnique(tree.pos(), m, enclScope)) {
   578             enclScope.enter(m);
   579         }
   580         annotateLater(tree.mods.annotations, localEnv, m);
   581         // Visit the signature of the method. Note that
   582         // TypeAnnotate doesn't descend into the body.
   583         typeAnnotate(tree, localEnv, m);
   585         if (tree.defaultValue != null)
   586             annotateDefaultValueLater(tree.defaultValue, localEnv, m);
   587     }
   589     /** Create a fresh environment for method bodies.
   590      *  @param tree     The method definition.
   591      *  @param env      The environment current outside of the method definition.
   592      */
   593     Env<AttrContext> methodEnv(JCMethodDecl tree, Env<AttrContext> env) {
   594         Env<AttrContext> localEnv =
   595             env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
   596         localEnv.enclMethod = tree;
   597         localEnv.info.scope.owner = tree.sym;
   598         if (tree.sym.type != null) {
   599             //when this is called in the enter stage, there's no type to be set
   600             localEnv.info.returnResult = attr.new ResultInfo(VAL, tree.sym.type.getReturnType());
   601         }
   602         if ((tree.mods.flags & STATIC) != 0) localEnv.info.staticLevel++;
   603         return localEnv;
   604     }
   606     public void visitVarDef(JCVariableDecl tree) {
   607         Env<AttrContext> localEnv = env;
   608         if ((tree.mods.flags & STATIC) != 0 ||
   609             (env.info.scope.owner.flags() & INTERFACE) != 0) {
   610             localEnv = env.dup(tree, env.info.dup());
   611             localEnv.info.staticLevel++;
   612         }
   613         DeferredLintHandler prevLintHandler =
   614                 chk.setDeferredLintHandler(deferredLintHandler.setPos(tree.pos()));
   615         try {
   616             if (TreeInfo.isEnumInit(tree)) {
   617                 attr.attribIdentAsEnumType(localEnv, (JCIdent)tree.vartype);
   618             } else {
   619                 // Make sure type annotations are processed.
   620                 // But we don't have a symbol to attach them to yet - use null.
   621                 typeAnnotate(tree.vartype, env, null);
   622                 attr.attribType(tree.vartype, localEnv);
   623                 if (tree.nameexpr != null) {
   624                     attr.attribExpr(tree.nameexpr, localEnv);
   625                     MethodSymbol m = localEnv.enclMethod.sym;
   626                     if (m.isConstructor()) {
   627                         Type outertype = m.owner.owner.type;
   628                         if (outertype.hasTag(TypeTag.CLASS)) {
   629                             checkType(tree.vartype, outertype, "incorrect.constructor.receiver.type");
   630                             checkType(tree.nameexpr, outertype, "incorrect.constructor.receiver.name");
   631                         } else {
   632                             log.error(tree, "receiver.parameter.not.applicable.constructor.toplevel.class");
   633                         }
   634                     } else {
   635                         checkType(tree.vartype, m.owner.type, "incorrect.receiver.type");
   636                         checkType(tree.nameexpr, m.owner.type, "incorrect.receiver.name");
   637                     }
   638                 }
   639             }
   640         } finally {
   641             chk.setDeferredLintHandler(prevLintHandler);
   642         }
   644         if ((tree.mods.flags & VARARGS) != 0) {
   645             //if we are entering a varargs parameter, we need to replace its type
   646             //(a plain array type) with the more precise VarargsType --- we need
   647             //to do it this way because varargs is represented in the tree as a modifier
   648             //on the parameter declaration, and not as a distinct type of array node.
   649             ArrayType atype = (ArrayType)tree.vartype.type.unannotatedType();
   650             tree.vartype.type = atype.makeVarargs();
   651         }
   652         Scope enclScope = enter.enterScope(env);
   653         VarSymbol v =
   654             new VarSymbol(0, tree.name, tree.vartype.type, enclScope.owner);
   655         v.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, v, tree);
   656         tree.sym = v;
   657         if (tree.init != null) {
   658             v.flags_field |= HASINIT;
   659             if ((v.flags_field & FINAL) != 0 &&
   660                     !tree.init.hasTag(NEWCLASS) &&
   661                     !tree.init.hasTag(LAMBDA)) {
   662                 Env<AttrContext> initEnv = getInitEnv(tree, env);
   663                 initEnv.info.enclVar = v;
   664                 v.setLazyConstValue(initEnv(tree, initEnv), attr, tree.init);
   665             }
   666         }
   667         if (chk.checkUnique(tree.pos(), v, enclScope)) {
   668             chk.checkTransparentVar(tree.pos(), v, enclScope);
   669             enclScope.enter(v);
   670         }
   671         annotateLater(tree.mods.annotations, localEnv, v);
   672         typeAnnotate(tree.vartype, env, v);
   673         annotate.flush();
   674         v.pos = tree.pos;
   675     }
   676     // where
   677     void checkType(JCTree tree, Type type, String diag) {
   678         if (!tree.type.isErroneous() && !types.isSameType(tree.type, type)) {
   679             log.error(tree, diag, type, tree.type);
   680         }
   681     }
   683     /** Create a fresh environment for a variable's initializer.
   684      *  If the variable is a field, the owner of the environment's scope
   685      *  is be the variable itself, otherwise the owner is the method
   686      *  enclosing the variable definition.
   687      *
   688      *  @param tree     The variable definition.
   689      *  @param env      The environment current outside of the variable definition.
   690      */
   691     Env<AttrContext> initEnv(JCVariableDecl tree, Env<AttrContext> env) {
   692         Env<AttrContext> localEnv = env.dupto(new AttrContextEnv(tree, env.info.dup()));
   693         if (tree.sym.owner.kind == TYP) {
   694             localEnv.info.scope = env.info.scope.dupUnshared();
   695             localEnv.info.scope.owner = tree.sym;
   696         }
   697         if ((tree.mods.flags & STATIC) != 0 ||
   698                 ((env.enclClass.sym.flags() & INTERFACE) != 0 && env.enclMethod == null))
   699             localEnv.info.staticLevel++;
   700         return localEnv;
   701     }
   703     /** Default member enter visitor method: do nothing
   704      */
   705     public void visitTree(JCTree tree) {
   706     }
   708     public void visitErroneous(JCErroneous tree) {
   709         if (tree.errs != null)
   710             memberEnter(tree.errs, env);
   711     }
   713     public Env<AttrContext> getMethodEnv(JCMethodDecl tree, Env<AttrContext> env) {
   714         Env<AttrContext> mEnv = methodEnv(tree, env);
   715         mEnv.info.lint = mEnv.info.lint.augment(tree.sym.annotations, tree.sym.flags());
   716         for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
   717             mEnv.info.scope.enterIfAbsent(l.head.type.tsym);
   718         for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail)
   719             mEnv.info.scope.enterIfAbsent(l.head.sym);
   720         return mEnv;
   721     }
   723     public Env<AttrContext> getInitEnv(JCVariableDecl tree, Env<AttrContext> env) {
   724         Env<AttrContext> iEnv = initEnv(tree, env);
   725         return iEnv;
   726     }
   728 /* ********************************************************************
   729  * Type completion
   730  *********************************************************************/
   732     Type attribImportType(JCTree tree, Env<AttrContext> env) {
   733         Assert.check(completionEnabled);
   734         try {
   735             // To prevent deep recursion, suppress completion of some
   736             // types.
   737             completionEnabled = false;
   738             return attr.attribType(tree, env);
   739         } finally {
   740             completionEnabled = true;
   741         }
   742     }
   744 /* ********************************************************************
   745  * Annotation processing
   746  *********************************************************************/
   748     /** Queue annotations for later processing. */
   749     void annotateLater(final List<JCAnnotation> annotations,
   750                        final Env<AttrContext> localEnv,
   751                        final Symbol s) {
   752         if (annotations.isEmpty()) {
   753             return;
   754         }
   755         if (s.kind != PCK) {
   756             s.annotations.reset(); // mark Annotations as incomplete for now
   757         }
   758         annotate.normal(new Annotate.Annotator() {
   759                 @Override
   760                 public String toString() {
   761                     return "annotate " + annotations + " onto " + s + " in " + s.owner;
   762                 }
   764                 @Override
   765                 public void enterAnnotation() {
   766                     Assert.check(s.kind == PCK || s.annotations.pendingCompletion());
   767                     JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile);
   768                     try {
   769                         if (!s.annotations.isEmpty() &&
   770                             annotations.nonEmpty())
   771                             log.error(annotations.head.pos,
   772                                       "already.annotated",
   773                                       kindName(s), s);
   774                         actualEnterAnnotations(annotations, localEnv, s);
   775                     } finally {
   776                         log.useSource(prev);
   777                     }
   778                 }
   779             });
   780     }
   782     /**
   783      * Check if a list of annotations contains a reference to
   784      * java.lang.Deprecated.
   785      **/
   786     private boolean hasDeprecatedAnnotation(List<JCAnnotation> annotations) {
   787         for (List<JCAnnotation> al = annotations; !al.isEmpty(); al = al.tail) {
   788             JCAnnotation a = al.head;
   789             if (a.annotationType.type == syms.deprecatedType && a.args.isEmpty())
   790                 return true;
   791         }
   792         return false;
   793     }
   795     /** Enter a set of annotations. */
   796     private void actualEnterAnnotations(List<JCAnnotation> annotations,
   797                           Env<AttrContext> env,
   798                           Symbol s) {
   799         Map<TypeSymbol, ListBuffer<Attribute.Compound>> annotated =
   800                 new LinkedHashMap<TypeSymbol, ListBuffer<Attribute.Compound>>();
   801         Map<Attribute.Compound, DiagnosticPosition> pos =
   802                 new HashMap<Attribute.Compound, DiagnosticPosition>();
   804         for (List<JCAnnotation> al = annotations; !al.isEmpty(); al = al.tail) {
   805             JCAnnotation a = al.head;
   806             Attribute.Compound c = annotate.enterAnnotation(a,
   807                                                             syms.annotationType,
   808                                                             env);
   809             if (c == null) {
   810                 continue;
   811             }
   813             if (annotated.containsKey(a.type.tsym)) {
   814                 if (source.allowRepeatedAnnotations()) {
   815                     ListBuffer<Attribute.Compound> l = annotated.get(a.type.tsym);
   816                     l = l.append(c);
   817                     annotated.put(a.type.tsym, l);
   818                     pos.put(c, a.pos());
   819                 } else {
   820                     log.error(a.pos(), "duplicate.annotation");
   821                 }
   822             } else {
   823                 annotated.put(a.type.tsym, ListBuffer.of(c));
   824                 pos.put(c, a.pos());
   825             }
   827             // Note: @Deprecated has no effect on local variables and parameters
   828             if (!c.type.isErroneous()
   829                 && s.owner.kind != MTH
   830                 && types.isSameType(c.type, syms.deprecatedType)) {
   831                 s.flags_field |= Flags.DEPRECATED;
   832             }
   833         }
   835         s.annotations.setDeclarationAttributesWithCompletion(
   836                 annotate.new AnnotateRepeatedContext<Attribute.Compound>(env, annotated, pos, log, false));
   837     }
   839     /** Queue processing of an attribute default value. */
   840     void annotateDefaultValueLater(final JCExpression defaultValue,
   841                                    final Env<AttrContext> localEnv,
   842                                    final MethodSymbol m) {
   843         annotate.normal(new Annotate.Annotator() {
   844                 @Override
   845                 public String toString() {
   846                     return "annotate " + m.owner + "." +
   847                         m + " default " + defaultValue;
   848                 }
   850                 @Override
   851                 public void enterAnnotation() {
   852                     JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile);
   853                     try {
   854                         enterDefaultValue(defaultValue, localEnv, m);
   855                     } finally {
   856                         log.useSource(prev);
   857                     }
   858                 }
   859             });
   860     }
   862     /** Enter a default value for an attribute method. */
   863     private void enterDefaultValue(final JCExpression defaultValue,
   864                                    final Env<AttrContext> localEnv,
   865                                    final MethodSymbol m) {
   866         m.defaultValue = annotate.enterAttributeValue(m.type.getReturnType(),
   867                                                       defaultValue,
   868                                                       localEnv);
   869     }
   871 /* ********************************************************************
   872  * Source completer
   873  *********************************************************************/
   875     /** Complete entering a class.
   876      *  @param sym         The symbol of the class to be completed.
   877      */
   878     public void complete(Symbol sym) throws CompletionFailure {
   879         // Suppress some (recursive) MemberEnter invocations
   880         if (!completionEnabled) {
   881             // Re-install same completer for next time around and return.
   882             Assert.check((sym.flags() & Flags.COMPOUND) == 0);
   883             sym.completer = this;
   884             return;
   885         }
   887         ClassSymbol c = (ClassSymbol)sym;
   888         ClassType ct = (ClassType)c.type;
   889         Env<AttrContext> env = enter.typeEnvs.get(c);
   890         JCClassDecl tree = (JCClassDecl)env.tree;
   891         boolean wasFirst = isFirst;
   892         isFirst = false;
   894         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   895         try {
   896             // Save class environment for later member enter (2) processing.
   897             halfcompleted.append(env);
   899             // Mark class as not yet attributed.
   900             c.flags_field |= UNATTRIBUTED;
   902             // If this is a toplevel-class, make sure any preceding import
   903             // clauses have been seen.
   904             if (c.owner.kind == PCK) {
   905                 memberEnter(env.toplevel, env.enclosing(TOPLEVEL));
   906                 todo.append(env);
   907             }
   909             if (c.owner.kind == TYP)
   910                 c.owner.complete();
   912             // create an environment for evaluating the base clauses
   913             Env<AttrContext> baseEnv = baseEnv(tree, env);
   915             if (tree.extending != null)
   916                 typeAnnotate(tree.extending, baseEnv, sym);
   917             for (JCExpression impl : tree.implementing)
   918                 typeAnnotate(impl, baseEnv, sym);
   919             annotate.flush();
   921             // Determine supertype.
   922             Type supertype =
   923                 (tree.extending != null)
   924                 ? attr.attribBase(tree.extending, baseEnv, true, false, true)
   925                 : ((tree.mods.flags & Flags.ENUM) != 0)
   926                 ? attr.attribBase(enumBase(tree.pos, c), baseEnv,
   927                                   true, false, false)
   928                 : (c.fullname == names.java_lang_Object)
   929                 ? Type.noType
   930                 : syms.objectType;
   931             ct.supertype_field = modelMissingTypes(supertype, tree.extending, false);
   933             // Determine interfaces.
   934             ListBuffer<Type> interfaces = new ListBuffer<Type>();
   935             ListBuffer<Type> all_interfaces = null; // lazy init
   936             Set<Type> interfaceSet = new HashSet<Type>();
   937             List<JCExpression> interfaceTrees = tree.implementing;
   938             for (JCExpression iface : interfaceTrees) {
   939                 Type i = attr.attribBase(iface, baseEnv, false, true, true);
   940                 if (i.hasTag(CLASS)) {
   941                     interfaces.append(i);
   942                     if (all_interfaces != null) all_interfaces.append(i);
   943                     chk.checkNotRepeated(iface.pos(), types.erasure(i), interfaceSet);
   944                 } else {
   945                     if (all_interfaces == null)
   946                         all_interfaces = new ListBuffer<Type>().appendList(interfaces);
   947                     all_interfaces.append(modelMissingTypes(i, iface, true));
   948                 }
   949             }
   950             if ((c.flags_field & ANNOTATION) != 0) {
   951                 ct.interfaces_field = List.of(syms.annotationType);
   952                 ct.all_interfaces_field = ct.interfaces_field;
   953             }  else {
   954                 ct.interfaces_field = interfaces.toList();
   955                 ct.all_interfaces_field = (all_interfaces == null)
   956                         ? ct.interfaces_field : all_interfaces.toList();
   957             }
   959             if (c.fullname == names.java_lang_Object) {
   960                 if (tree.extending != null) {
   961                     chk.checkNonCyclic(tree.extending.pos(),
   962                                        supertype);
   963                     ct.supertype_field = Type.noType;
   964                 }
   965                 else if (tree.implementing.nonEmpty()) {
   966                     chk.checkNonCyclic(tree.implementing.head.pos(),
   967                                        ct.interfaces_field.head);
   968                     ct.interfaces_field = List.nil();
   969                 }
   970             }
   972             // Annotations.
   973             // In general, we cannot fully process annotations yet,  but we
   974             // can attribute the annotation types and then check to see if the
   975             // @Deprecated annotation is present.
   976             attr.attribAnnotationTypes(tree.mods.annotations, baseEnv);
   977             if (hasDeprecatedAnnotation(tree.mods.annotations))
   978                 c.flags_field |= DEPRECATED;
   979             annotateLater(tree.mods.annotations, baseEnv, c);
   980             // class type parameters use baseEnv but everything uses env
   982             chk.checkNonCyclicDecl(tree);
   984             attr.attribTypeVariables(tree.typarams, baseEnv);
   985             // Do this here, where we have the symbol.
   986             for (JCTypeParameter tp : tree.typarams)
   987                 typeAnnotate(tp, baseEnv, sym);
   988             annotate.flush();
   990             // Add default constructor if needed.
   991             if ((c.flags() & INTERFACE) == 0 &&
   992                 !TreeInfo.hasConstructors(tree.defs)) {
   993                 List<Type> argtypes = List.nil();
   994                 List<Type> typarams = List.nil();
   995                 List<Type> thrown = List.nil();
   996                 long ctorFlags = 0;
   997                 boolean based = false;
   998                 boolean addConstructor = true;
   999                 if (c.name.isEmpty()) {
  1000                     JCNewClass nc = (JCNewClass)env.next.tree;
  1001                     if (nc.constructor != null) {
  1002                         addConstructor = nc.constructor.kind != ERR;
  1003                         Type superConstrType = types.memberType(c.type,
  1004                                                                 nc.constructor);
  1005                         argtypes = superConstrType.getParameterTypes();
  1006                         typarams = superConstrType.getTypeArguments();
  1007                         ctorFlags = nc.constructor.flags() & VARARGS;
  1008                         if (nc.encl != null) {
  1009                             argtypes = argtypes.prepend(nc.encl.type);
  1010                             based = true;
  1012                         thrown = superConstrType.getThrownTypes();
  1015                 if (addConstructor) {
  1016                     JCTree constrDef = DefaultConstructor(make.at(tree.pos), c,
  1017                                                         typarams, argtypes, thrown,
  1018                                                         ctorFlags, based);
  1019                     tree.defs = tree.defs.prepend(constrDef);
  1023             // enter symbols for 'this' into current scope.
  1024             VarSymbol thisSym =
  1025                 new VarSymbol(FINAL | HASINIT, names._this, c.type, c);
  1026             thisSym.pos = Position.FIRSTPOS;
  1027             env.info.scope.enter(thisSym);
  1028             // if this is a class, enter symbol for 'super' into current scope.
  1029             if ((c.flags_field & INTERFACE) == 0 &&
  1030                     ct.supertype_field.hasTag(CLASS)) {
  1031                 VarSymbol superSym =
  1032                     new VarSymbol(FINAL | HASINIT, names._super,
  1033                                   ct.supertype_field, c);
  1034                 superSym.pos = Position.FIRSTPOS;
  1035                 env.info.scope.enter(superSym);
  1038             // check that no package exists with same fully qualified name,
  1039             // but admit classes in the unnamed package which have the same
  1040             // name as a top-level package.
  1041             if (checkClash &&
  1042                 c.owner.kind == PCK && c.owner != syms.unnamedPackage &&
  1043                 reader.packageExists(c.fullname)) {
  1044                 log.error(tree.pos, "clash.with.pkg.of.same.name", Kinds.kindName(sym), c);
  1046             if (c.owner.kind == PCK && (c.flags_field & PUBLIC) == 0 &&
  1047                 !env.toplevel.sourcefile.isNameCompatible(c.name.toString(),JavaFileObject.Kind.SOURCE)) {
  1048                 c.flags_field |= AUXILIARY;
  1050         } catch (CompletionFailure ex) {
  1051             chk.completionError(tree.pos(), ex);
  1052         } finally {
  1053             log.useSource(prev);
  1056         // Enter all member fields and methods of a set of half completed
  1057         // classes in a second phase.
  1058         if (wasFirst) {
  1059             try {
  1060                 while (halfcompleted.nonEmpty()) {
  1061                     finish(halfcompleted.next());
  1063             } finally {
  1064                 isFirst = true;
  1067         TypeAnnotations.organizeTypeAnnotationsSignatures(syms, names, log, tree, annotate);
  1070     /*
  1071      * If the symbol is non-null, attach the type annotation to it.
  1072      */
  1073     private void actualEnterTypeAnnotations(final List<JCAnnotation> annotations,
  1074             final Env<AttrContext> env,
  1075             final Symbol s) {
  1076         Map<TypeSymbol, ListBuffer<Attribute.TypeCompound>> annotated =
  1077                 new LinkedHashMap<TypeSymbol, ListBuffer<Attribute.TypeCompound>>();
  1078         Map<Attribute.TypeCompound, DiagnosticPosition> pos =
  1079                 new HashMap<Attribute.TypeCompound, DiagnosticPosition>();
  1081         for (List<JCAnnotation> al = annotations; !al.isEmpty(); al = al.tail) {
  1082             JCAnnotation a = al.head;
  1083             Attribute.TypeCompound tc = annotate.enterTypeAnnotation(a,
  1084                     syms.annotationType,
  1085                     env);
  1086             if (tc == null) {
  1087                 continue;
  1090             if (annotated.containsKey(a.type.tsym)) {
  1091                 if (source.allowRepeatedAnnotations()) {
  1092                     ListBuffer<Attribute.TypeCompound> l = annotated.get(a.type.tsym);
  1093                     l = l.append(tc);
  1094                     annotated.put(a.type.tsym, l);
  1095                     pos.put(tc, a.pos());
  1096                 } else {
  1097                     log.error(a.pos(), "duplicate.annotation");
  1099             } else {
  1100                 annotated.put(a.type.tsym, ListBuffer.of(tc));
  1101                 pos.put(tc, a.pos());
  1105         if (s != null) {
  1106             s.annotations.appendTypeAttributesWithCompletion(
  1107                     annotate.new AnnotateRepeatedContext<Attribute.TypeCompound>(env, annotated, pos, log, true));
  1111     public void typeAnnotate(final JCTree tree, final Env<AttrContext> env, final Symbol sym) {
  1112         tree.accept(new TypeAnnotate(env, sym));
  1115     /**
  1116      * We need to use a TreeScanner, because it is not enough to visit the top-level
  1117      * annotations. We also need to visit type arguments, etc.
  1118      */
  1119     private class TypeAnnotate extends TreeScanner {
  1120         private Env<AttrContext> env;
  1121         private Symbol sym;
  1123         public TypeAnnotate(final Env<AttrContext> env, final Symbol sym) {
  1124             this.env = env;
  1125             this.sym = sym;
  1128         void annotateTypeLater(final List<JCAnnotation> annotations) {
  1129             if (annotations.isEmpty()) {
  1130                 return;
  1133             annotate.normal(new Annotate.Annotator() {
  1134                 @Override
  1135                 public String toString() {
  1136                     return "type annotate " + annotations + " onto " + sym + " in " + sym.owner;
  1138                 @Override
  1139                 public void enterAnnotation() {
  1140                     JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
  1141                     try {
  1142                         actualEnterTypeAnnotations(annotations, env, sym);
  1143                     } finally {
  1144                         log.useSource(prev);
  1147             });
  1150         @Override
  1151         public void visitAnnotatedType(final JCAnnotatedType tree) {
  1152             annotateTypeLater(tree.annotations);
  1153             super.visitAnnotatedType(tree);
  1156         @Override
  1157         public void visitTypeParameter(final JCTypeParameter tree) {
  1158             annotateTypeLater(tree.annotations);
  1159             super.visitTypeParameter(tree);
  1162         @Override
  1163         public void visitNewArray(final JCNewArray tree) {
  1164             annotateTypeLater(tree.annotations);
  1165             for (List<JCAnnotation> dimAnnos : tree.dimAnnotations)
  1166                 annotateTypeLater(dimAnnos);
  1167             super.visitNewArray(tree);
  1170         @Override
  1171         public void visitMethodDef(final JCMethodDecl tree) {
  1172             scan(tree.mods);
  1173             scan(tree.restype);
  1174             scan(tree.typarams);
  1175             scan(tree.recvparam);
  1176             scan(tree.params);
  1177             scan(tree.thrown);
  1178             scan(tree.defaultValue);
  1179             // Do not annotate the body, just the signature.
  1180             // scan(tree.body);
  1183         @Override
  1184         public void visitVarDef(final JCVariableDecl tree) {
  1185             if (sym != null && sym.kind == Kinds.VAR) {
  1186                 // Don't visit a parameter once when the sym is the method
  1187                 // and once when the sym is the parameter.
  1188                 scan(tree.mods);
  1189                 scan(tree.vartype);
  1191             scan(tree.init);
  1194         @Override
  1195         public void visitClassDef(JCClassDecl tree) {
  1196             // We can only hit a classdef if it is declared within
  1197             // a method. Ignore it - the class will be visited
  1198             // separately later.
  1201         @Override
  1202         public void visitNewClass(JCNewClass tree) {
  1203             if (tree.def == null) {
  1204                 // For an anonymous class instantiation the class
  1205                 // will be visited separately.
  1206                 super.visitNewClass(tree);
  1212     private Env<AttrContext> baseEnv(JCClassDecl tree, Env<AttrContext> env) {
  1213         Scope baseScope = new Scope(tree.sym);
  1214         //import already entered local classes into base scope
  1215         for (Scope.Entry e = env.outer.info.scope.elems ; e != null ; e = e.sibling) {
  1216             if (e.sym.isLocal()) {
  1217                 baseScope.enter(e.sym);
  1220         //import current type-parameters into base scope
  1221         if (tree.typarams != null)
  1222             for (List<JCTypeParameter> typarams = tree.typarams;
  1223                  typarams.nonEmpty();
  1224                  typarams = typarams.tail)
  1225                 baseScope.enter(typarams.head.type.tsym);
  1226         Env<AttrContext> outer = env.outer; // the base clause can't see members of this class
  1227         Env<AttrContext> localEnv = outer.dup(tree, outer.info.dup(baseScope));
  1228         localEnv.baseClause = true;
  1229         localEnv.outer = outer;
  1230         localEnv.info.isSelfCall = false;
  1231         return localEnv;
  1234     /** Enter member fields and methods of a class
  1235      *  @param env        the environment current for the class block.
  1236      */
  1237     private void finish(Env<AttrContext> env) {
  1238         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
  1239         try {
  1240             JCClassDecl tree = (JCClassDecl)env.tree;
  1241             finishClass(tree, env);
  1242         } finally {
  1243             log.useSource(prev);
  1247     /** Generate a base clause for an enum type.
  1248      *  @param pos              The position for trees and diagnostics, if any
  1249      *  @param c                The class symbol of the enum
  1250      */
  1251     private JCExpression enumBase(int pos, ClassSymbol c) {
  1252         JCExpression result = make.at(pos).
  1253             TypeApply(make.QualIdent(syms.enumSym),
  1254                       List.<JCExpression>of(make.Type(c.type)));
  1255         return result;
  1258     Type modelMissingTypes(Type t, final JCExpression tree, final boolean interfaceExpected) {
  1259         if (!t.hasTag(ERROR))
  1260             return t;
  1262         return new ErrorType(((ErrorType) t).getOriginalType(), t.tsym) {
  1263             private Type modelType;
  1265             @Override
  1266             public Type getModelType() {
  1267                 if (modelType == null)
  1268                     modelType = new Synthesizer(getOriginalType(), interfaceExpected).visit(tree);
  1269                 return modelType;
  1271         };
  1273     // where
  1274     private class Synthesizer extends JCTree.Visitor {
  1275         Type originalType;
  1276         boolean interfaceExpected;
  1277         List<ClassSymbol> synthesizedSymbols = List.nil();
  1278         Type result;
  1280         Synthesizer(Type originalType, boolean interfaceExpected) {
  1281             this.originalType = originalType;
  1282             this.interfaceExpected = interfaceExpected;
  1285         Type visit(JCTree tree) {
  1286             tree.accept(this);
  1287             return result;
  1290         List<Type> visit(List<? extends JCTree> trees) {
  1291             ListBuffer<Type> lb = new ListBuffer<Type>();
  1292             for (JCTree t: trees)
  1293                 lb.append(visit(t));
  1294             return lb.toList();
  1297         @Override
  1298         public void visitTree(JCTree tree) {
  1299             result = syms.errType;
  1302         @Override
  1303         public void visitIdent(JCIdent tree) {
  1304             if (!tree.type.hasTag(ERROR)) {
  1305                 result = tree.type;
  1306             } else {
  1307                 result = synthesizeClass(tree.name, syms.unnamedPackage).type;
  1311         @Override
  1312         public void visitSelect(JCFieldAccess tree) {
  1313             if (!tree.type.hasTag(ERROR)) {
  1314                 result = tree.type;
  1315             } else {
  1316                 Type selectedType;
  1317                 boolean prev = interfaceExpected;
  1318                 try {
  1319                     interfaceExpected = false;
  1320                     selectedType = visit(tree.selected);
  1321                 } finally {
  1322                     interfaceExpected = prev;
  1324                 ClassSymbol c = synthesizeClass(tree.name, selectedType.tsym);
  1325                 result = c.type;
  1329         @Override
  1330         public void visitTypeApply(JCTypeApply tree) {
  1331             if (!tree.type.hasTag(ERROR)) {
  1332                 result = tree.type;
  1333             } else {
  1334                 ClassType clazzType = (ClassType) visit(tree.clazz);
  1335                 if (synthesizedSymbols.contains(clazzType.tsym))
  1336                     synthesizeTyparams((ClassSymbol) clazzType.tsym, tree.arguments.size());
  1337                 final List<Type> actuals = visit(tree.arguments);
  1338                 result = new ErrorType(tree.type, clazzType.tsym) {
  1339                     @Override
  1340                     public List<Type> getTypeArguments() {
  1341                         return actuals;
  1343                 };
  1347         ClassSymbol synthesizeClass(Name name, Symbol owner) {
  1348             int flags = interfaceExpected ? INTERFACE : 0;
  1349             ClassSymbol c = new ClassSymbol(flags, name, owner);
  1350             c.members_field = new Scope.ErrorScope(c);
  1351             c.type = new ErrorType(originalType, c) {
  1352                 @Override
  1353                 public List<Type> getTypeArguments() {
  1354                     return typarams_field;
  1356             };
  1357             synthesizedSymbols = synthesizedSymbols.prepend(c);
  1358             return c;
  1361         void synthesizeTyparams(ClassSymbol sym, int n) {
  1362             ClassType ct = (ClassType) sym.type;
  1363             Assert.check(ct.typarams_field.isEmpty());
  1364             if (n == 1) {
  1365                 TypeVar v = new TypeVar(names.fromString("T"), sym, syms.botType);
  1366                 ct.typarams_field = ct.typarams_field.prepend(v);
  1367             } else {
  1368                 for (int i = n; i > 0; i--) {
  1369                     TypeVar v = new TypeVar(names.fromString("T" + i), sym, syms.botType);
  1370                     ct.typarams_field = ct.typarams_field.prepend(v);
  1377 /* ***************************************************************************
  1378  * tree building
  1379  ****************************************************************************/
  1381     /** Generate default constructor for given class. For classes different
  1382      *  from java.lang.Object, this is:
  1384      *    c(argtype_0 x_0, ..., argtype_n x_n) throws thrown {
  1385      *      super(x_0, ..., x_n)
  1386      *    }
  1388      *  or, if based == true:
  1390      *    c(argtype_0 x_0, ..., argtype_n x_n) throws thrown {
  1391      *      x_0.super(x_1, ..., x_n)
  1392      *    }
  1394      *  @param make     The tree factory.
  1395      *  @param c        The class owning the default constructor.
  1396      *  @param argtypes The parameter types of the constructor.
  1397      *  @param thrown   The thrown exceptions of the constructor.
  1398      *  @param based    Is first parameter a this$n?
  1399      */
  1400     JCTree DefaultConstructor(TreeMaker make,
  1401                             ClassSymbol c,
  1402                             List<Type> typarams,
  1403                             List<Type> argtypes,
  1404                             List<Type> thrown,
  1405                             long flags,
  1406                             boolean based) {
  1407         List<JCVariableDecl> params = make.Params(argtypes, syms.noSymbol);
  1408         List<JCStatement> stats = List.nil();
  1409         if (c.type != syms.objectType)
  1410             stats = stats.prepend(SuperCall(make, typarams, params, based));
  1411         if ((c.flags() & ENUM) != 0 &&
  1412             (types.supertype(c.type).tsym == syms.enumSym)) {
  1413             // constructors of true enums are private
  1414             flags = (flags & ~AccessFlags) | PRIVATE | GENERATEDCONSTR;
  1415         } else
  1416             flags |= (c.flags() & AccessFlags) | GENERATEDCONSTR;
  1417         if (c.name.isEmpty()) flags |= ANONCONSTR;
  1418         JCTree result = make.MethodDef(
  1419             make.Modifiers(flags),
  1420             names.init,
  1421             null,
  1422             make.TypeParams(typarams),
  1423             params,
  1424             make.Types(thrown),
  1425             make.Block(0, stats),
  1426             null);
  1427         return result;
  1430     /** Generate call to superclass constructor. This is:
  1432      *    super(id_0, ..., id_n)
  1434      * or, if based == true
  1436      *    id_0.super(id_1,...,id_n)
  1438      *  where id_0, ..., id_n are the names of the given parameters.
  1440      *  @param make    The tree factory
  1441      *  @param params  The parameters that need to be passed to super
  1442      *  @param typarams  The type parameters that need to be passed to super
  1443      *  @param based   Is first parameter a this$n?
  1444      */
  1445     JCExpressionStatement SuperCall(TreeMaker make,
  1446                    List<Type> typarams,
  1447                    List<JCVariableDecl> params,
  1448                    boolean based) {
  1449         JCExpression meth;
  1450         if (based) {
  1451             meth = make.Select(make.Ident(params.head), names._super);
  1452             params = params.tail;
  1453         } else {
  1454             meth = make.Ident(names._super);
  1456         List<JCExpression> typeargs = typarams.nonEmpty() ? make.Types(typarams) : null;
  1457         return make.Exec(make.Apply(typeargs, meth, make.Idents(params)));

mercurial