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

Fri, 12 Jul 2013 13:11:12 -0700

author
jjg
date
Fri, 12 Jul 2013 13:11:12 -0700
changeset 1895
37031963493e
parent 1850
6debfa63a4a1
child 1896
44e27378f523
permissions
-rw-r--r--

8020278: NPE in javadoc
Reviewed-by: mcimadamore, 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         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(List<JCTypeParameter> typarams,
   362                    List<JCVariableDecl> params,
   363                    JCTree res,
   364                    JCVariableDecl recvparam,
   365                    List<JCExpression> thrown,
   366                    Env<AttrContext> env) {
   368         // Enter and attribute type parameters.
   369         List<Type> tvars = enter.classEnter(typarams, env);
   370         attr.attribTypeVariables(typarams, env);
   372         // Enter and attribute value parameters.
   373         ListBuffer<Type> argbuf = new ListBuffer<Type>();
   374         for (List<JCVariableDecl> l = params; l.nonEmpty(); l = l.tail) {
   375             memberEnter(l.head, env);
   376             argbuf.append(l.head.vartype.type);
   377         }
   379         // Attribute result type, if one is given.
   380         Type restype = res == null ? syms.voidType : attr.attribType(res, env);
   382         // Attribute receiver type, if one is given.
   383         Type recvtype;
   384         if (recvparam!=null) {
   385             memberEnter(recvparam, env);
   386             recvtype = recvparam.vartype.type;
   387         } else {
   388             recvtype = null;
   389         }
   391         // Attribute thrown exceptions.
   392         ListBuffer<Type> thrownbuf = new ListBuffer<Type>();
   393         for (List<JCExpression> l = thrown; l.nonEmpty(); l = l.tail) {
   394             Type exc = attr.attribType(l.head, env);
   395             if (!exc.hasTag(TYPEVAR))
   396                 exc = chk.checkClassType(l.head.pos(), exc);
   397             thrownbuf.append(exc);
   398         }
   399         MethodType mtype = new MethodType(argbuf.toList(),
   400                                     restype,
   401                                     thrownbuf.toList(),
   402                                     syms.methodClass);
   403         mtype.recvtype = recvtype;
   405         return tvars.isEmpty() ? mtype : new ForAll(tvars, mtype);
   406     }
   408 /* ********************************************************************
   409  * Visitor methods for member enter
   410  *********************************************************************/
   412     /** Visitor argument: the current environment
   413      */
   414     protected Env<AttrContext> env;
   416     /** Enter field and method definitions and process import
   417      *  clauses, catching any completion failure exceptions.
   418      */
   419     protected void memberEnter(JCTree tree, Env<AttrContext> env) {
   420         Env<AttrContext> prevEnv = this.env;
   421         try {
   422             this.env = env;
   423             tree.accept(this);
   424         }  catch (CompletionFailure ex) {
   425             chk.completionError(tree.pos(), ex);
   426         } finally {
   427             this.env = prevEnv;
   428         }
   429     }
   431     /** Enter members from a list of trees.
   432      */
   433     void memberEnter(List<? extends JCTree> trees, Env<AttrContext> env) {
   434         for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
   435             memberEnter(l.head, env);
   436     }
   438     /** Enter members for a class.
   439      */
   440     void finishClass(JCClassDecl tree, Env<AttrContext> env) {
   441         if ((tree.mods.flags & Flags.ENUM) != 0 &&
   442             (types.supertype(tree.sym.type).tsym.flags() & Flags.ENUM) == 0) {
   443             addEnumMembers(tree, env);
   444         }
   445         memberEnter(tree.defs, env);
   446     }
   448     /** Add the implicit members for an enum type
   449      *  to the symbol table.
   450      */
   451     private void addEnumMembers(JCClassDecl tree, Env<AttrContext> env) {
   452         JCExpression valuesType = make.Type(new ArrayType(tree.sym.type, syms.arrayClass));
   454         // public static T[] values() { return ???; }
   455         JCMethodDecl values = make.
   456             MethodDef(make.Modifiers(Flags.PUBLIC|Flags.STATIC),
   457                       names.values,
   458                       valuesType,
   459                       List.<JCTypeParameter>nil(),
   460                       List.<JCVariableDecl>nil(),
   461                       List.<JCExpression>nil(), // thrown
   462                       null, //make.Block(0, Tree.emptyList.prepend(make.Return(make.Ident(names._null)))),
   463                       null);
   464         memberEnter(values, env);
   466         // public static T valueOf(String name) { return ???; }
   467         JCMethodDecl valueOf = make.
   468             MethodDef(make.Modifiers(Flags.PUBLIC|Flags.STATIC),
   469                       names.valueOf,
   470                       make.Type(tree.sym.type),
   471                       List.<JCTypeParameter>nil(),
   472                       List.of(make.VarDef(make.Modifiers(Flags.PARAMETER |
   473                                                          Flags.MANDATED),
   474                                             names.fromString("name"),
   475                                             make.Type(syms.stringType), null)),
   476                       List.<JCExpression>nil(), // thrown
   477                       null, //make.Block(0, Tree.emptyList.prepend(make.Return(make.Ident(names._null)))),
   478                       null);
   479         memberEnter(valueOf, env);
   480     }
   482     public void visitTopLevel(JCCompilationUnit tree) {
   483         if (tree.starImportScope.elems != null) {
   484             // we must have already processed this toplevel
   485             return;
   486         }
   488         // check that no class exists with same fully qualified name as
   489         // toplevel package
   490         if (checkClash && tree.pid != null) {
   491             Symbol p = tree.packge;
   492             while (p.owner != syms.rootPackage) {
   493                 p.owner.complete(); // enter all class members of p
   494                 if (syms.classes.get(p.getQualifiedName()) != null) {
   495                     log.error(tree.pos,
   496                               "pkg.clashes.with.class.of.same.name",
   497                               p);
   498                 }
   499                 p = p.owner;
   500             }
   501         }
   503         // process package annotations
   504         annotateLater(tree.packageAnnotations, env, tree.packge);
   506         // Import-on-demand java.lang.
   507         importAll(tree.pos, reader.enterPackage(names.java_lang), env);
   509         // Process all import clauses.
   510         memberEnter(tree.defs, env);
   511     }
   513     // process the non-static imports and the static imports of types.
   514     public void visitImport(JCImport tree) {
   515         JCFieldAccess imp = (JCFieldAccess)tree.qualid;
   516         Name name = TreeInfo.name(imp);
   518         // Create a local environment pointing to this tree to disable
   519         // effects of other imports in Resolve.findGlobalType
   520         Env<AttrContext> localEnv = env.dup(tree);
   522         TypeSymbol p = attr.attribImportQualifier(tree, localEnv).tsym;
   523         if (name == names.asterisk) {
   524             // Import on demand.
   525             chk.checkCanonical(imp.selected);
   526             if (tree.staticImport)
   527                 importStaticAll(tree.pos, p, env);
   528             else
   529                 importAll(tree.pos, p, env);
   530         } else {
   531             // Named type import.
   532             if (tree.staticImport) {
   533                 importNamedStatic(tree.pos(), p, name, localEnv);
   534                 chk.checkCanonical(imp.selected);
   535             } else {
   536                 TypeSymbol c = attribImportType(imp, localEnv).tsym;
   537                 chk.checkCanonical(imp);
   538                 importNamed(tree.pos(), c, env);
   539             }
   540         }
   541     }
   543     public void visitMethodDef(JCMethodDecl tree) {
   544         Scope enclScope = enter.enterScope(env);
   545         MethodSymbol m = new MethodSymbol(0, tree.name, null, enclScope.owner);
   546         m.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, m, tree);
   547         tree.sym = m;
   549         //if this is a default method, add the DEFAULT flag to the enclosing interface
   550         if ((tree.mods.flags & DEFAULT) != 0) {
   551             m.enclClass().flags_field |= DEFAULT;
   552         }
   554         Env<AttrContext> localEnv = methodEnv(tree, env);
   556         DeferredLintHandler prevLintHandler =
   557                 chk.setDeferredLintHandler(deferredLintHandler.setPos(tree.pos()));
   558         try {
   559             // Compute the method type
   560             m.type = signature(tree.typarams, tree.params,
   561                                tree.restype, tree.recvparam,
   562                                tree.thrown,
   563                                localEnv);
   564         } finally {
   565             chk.setDeferredLintHandler(prevLintHandler);
   566         }
   568         if (types.isSignaturePolymorphic(m)) {
   569             m.flags_field |= SIGNATURE_POLYMORPHIC;
   570         }
   572         // Set m.params
   573         ListBuffer<VarSymbol> params = new ListBuffer<VarSymbol>();
   574         JCVariableDecl lastParam = null;
   575         for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
   576             JCVariableDecl param = lastParam = l.head;
   577             params.append(Assert.checkNonNull(param.sym));
   578         }
   579         m.params = params.toList();
   581         // mark the method varargs, if necessary
   582         if (lastParam != null && (lastParam.mods.flags & Flags.VARARGS) != 0)
   583             m.flags_field |= Flags.VARARGS;
   585         localEnv.info.scope.leave();
   586         if (chk.checkUnique(tree.pos(), m, enclScope)) {
   587             enclScope.enter(m);
   588         }
   589         annotateLater(tree.mods.annotations, localEnv, m);
   590         // Visit the signature of the method. Note that
   591         // TypeAnnotate doesn't descend into the body.
   592         typeAnnotate(tree, localEnv, m);
   594         if (tree.defaultValue != null)
   595             annotateDefaultValueLater(tree.defaultValue, localEnv, m);
   596     }
   598     /** Create a fresh environment for method bodies.
   599      *  @param tree     The method definition.
   600      *  @param env      The environment current outside of the method definition.
   601      */
   602     Env<AttrContext> methodEnv(JCMethodDecl tree, Env<AttrContext> env) {
   603         Env<AttrContext> localEnv =
   604             env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
   605         localEnv.enclMethod = tree;
   606         localEnv.info.scope.owner = tree.sym;
   607         if (tree.sym.type != null) {
   608             //when this is called in the enter stage, there's no type to be set
   609             localEnv.info.returnResult = attr.new ResultInfo(VAL, tree.sym.type.getReturnType());
   610         }
   611         if ((tree.mods.flags & STATIC) != 0) localEnv.info.staticLevel++;
   612         return localEnv;
   613     }
   615     public void visitVarDef(JCVariableDecl tree) {
   616         Env<AttrContext> localEnv = env;
   617         if ((tree.mods.flags & STATIC) != 0 ||
   618             (env.info.scope.owner.flags() & INTERFACE) != 0) {
   619             localEnv = env.dup(tree, env.info.dup());
   620             localEnv.info.staticLevel++;
   621         }
   622         DeferredLintHandler prevLintHandler =
   623                 chk.setDeferredLintHandler(deferredLintHandler.setPos(tree.pos()));
   624         try {
   625             if (TreeInfo.isEnumInit(tree)) {
   626                 attr.attribIdentAsEnumType(localEnv, (JCIdent)tree.vartype);
   627             } else {
   628                 // Make sure type annotations are processed.
   629                 // But we don't have a symbol to attach them to yet - use null.
   630                 typeAnnotate(tree.vartype, env, null);
   631                 attr.attribType(tree.vartype, localEnv);
   632                 if (tree.nameexpr != null) {
   633                     attr.attribExpr(tree.nameexpr, localEnv);
   634                     MethodSymbol m = localEnv.enclMethod.sym;
   635                     if (m.isConstructor()) {
   636                         Type outertype = m.owner.owner.type;
   637                         if (outertype.hasTag(TypeTag.CLASS)) {
   638                             checkType(tree.vartype, outertype, "incorrect.constructor.receiver.type");
   639                             checkType(tree.nameexpr, outertype, "incorrect.constructor.receiver.name");
   640                         } else {
   641                             log.error(tree, "receiver.parameter.not.applicable.constructor.toplevel.class");
   642                         }
   643                     } else {
   644                         checkType(tree.vartype, m.owner.type, "incorrect.receiver.type");
   645                         checkType(tree.nameexpr, m.owner.type, "incorrect.receiver.name");
   646                     }
   647                 }
   648             }
   649         } finally {
   650             chk.setDeferredLintHandler(prevLintHandler);
   651         }
   653         if ((tree.mods.flags & VARARGS) != 0) {
   654             //if we are entering a varargs parameter, we need to replace its type
   655             //(a plain array type) with the more precise VarargsType --- we need
   656             //to do it this way because varargs is represented in the tree as a modifier
   657             //on the parameter declaration, and not as a distinct type of array node.
   658             ArrayType atype = (ArrayType)tree.vartype.type.unannotatedType();
   659             tree.vartype.type = atype.makeVarargs();
   660         }
   661         Scope enclScope = enter.enterScope(env);
   662         VarSymbol v =
   663             new VarSymbol(0, tree.name, tree.vartype.type, enclScope.owner);
   664         v.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, v, tree);
   665         tree.sym = v;
   666         if (tree.init != null) {
   667             v.flags_field |= HASINIT;
   668             if ((v.flags_field & FINAL) != 0 &&
   669                     !tree.init.hasTag(NEWCLASS) &&
   670                     !tree.init.hasTag(LAMBDA)) {
   671                 Env<AttrContext> initEnv = getInitEnv(tree, env);
   672                 initEnv.info.enclVar = v;
   673                 v.setLazyConstValue(initEnv(tree, initEnv), attr, tree.init);
   674             }
   675         }
   676         if (chk.checkUnique(tree.pos(), v, enclScope)) {
   677             chk.checkTransparentVar(tree.pos(), v, enclScope);
   678             enclScope.enter(v);
   679         }
   680         annotateLater(tree.mods.annotations, localEnv, v);
   681         typeAnnotate(tree.vartype, env, v);
   682         annotate.flush();
   683         v.pos = tree.pos;
   684     }
   685     // where
   686     void checkType(JCTree tree, Type type, String diag) {
   687         if (!tree.type.isErroneous() && !types.isSameType(tree.type, type)) {
   688             log.error(tree, diag, type, tree.type);
   689         }
   690     }
   692     /** Create a fresh environment for a variable's initializer.
   693      *  If the variable is a field, the owner of the environment's scope
   694      *  is be the variable itself, otherwise the owner is the method
   695      *  enclosing the variable definition.
   696      *
   697      *  @param tree     The variable definition.
   698      *  @param env      The environment current outside of the variable definition.
   699      */
   700     Env<AttrContext> initEnv(JCVariableDecl tree, Env<AttrContext> env) {
   701         Env<AttrContext> localEnv = env.dupto(new AttrContextEnv(tree, env.info.dup()));
   702         if (tree.sym.owner.kind == TYP) {
   703             localEnv.info.scope = env.info.scope.dupUnshared();
   704             localEnv.info.scope.owner = tree.sym;
   705         }
   706         if ((tree.mods.flags & STATIC) != 0 ||
   707                 ((env.enclClass.sym.flags() & INTERFACE) != 0 && env.enclMethod == null))
   708             localEnv.info.staticLevel++;
   709         return localEnv;
   710     }
   712     /** Default member enter visitor method: do nothing
   713      */
   714     public void visitTree(JCTree tree) {
   715     }
   717     public void visitErroneous(JCErroneous tree) {
   718         if (tree.errs != null)
   719             memberEnter(tree.errs, env);
   720     }
   722     public Env<AttrContext> getMethodEnv(JCMethodDecl tree, Env<AttrContext> env) {
   723         Env<AttrContext> mEnv = methodEnv(tree, env);
   724         mEnv.info.lint = mEnv.info.lint.augment(tree.sym);
   725         for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
   726             mEnv.info.scope.enterIfAbsent(l.head.type.tsym);
   727         for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail)
   728             mEnv.info.scope.enterIfAbsent(l.head.sym);
   729         return mEnv;
   730     }
   732     public Env<AttrContext> getInitEnv(JCVariableDecl tree, Env<AttrContext> env) {
   733         Env<AttrContext> iEnv = initEnv(tree, env);
   734         return iEnv;
   735     }
   737 /* ********************************************************************
   738  * Type completion
   739  *********************************************************************/
   741     Type attribImportType(JCTree tree, Env<AttrContext> env) {
   742         Assert.check(completionEnabled);
   743         try {
   744             // To prevent deep recursion, suppress completion of some
   745             // types.
   746             completionEnabled = false;
   747             return attr.attribType(tree, env);
   748         } finally {
   749             completionEnabled = true;
   750         }
   751     }
   753 /* ********************************************************************
   754  * Annotation processing
   755  *********************************************************************/
   757     /** Queue annotations for later processing. */
   758     void annotateLater(final List<JCAnnotation> annotations,
   759                        final Env<AttrContext> localEnv,
   760                        final Symbol s) {
   761         if (annotations.isEmpty()) {
   762             return;
   763         }
   764         if (s.kind != PCK) {
   765             s.resetAnnotations(); // mark Annotations as incomplete for now
   766         }
   767         annotate.normal(new Annotate.Annotator() {
   768                 @Override
   769                 public String toString() {
   770                     return "annotate " + annotations + " onto " + s + " in " + s.owner;
   771                 }
   773                 @Override
   774                 public void enterAnnotation() {
   775                     Assert.check(s.kind == PCK || s.annotationsPendingCompletion());
   776                     JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile);
   777                     try {
   778                         if (s.hasAnnotations() &&
   779                             annotations.nonEmpty())
   780                             log.error(annotations.head.pos,
   781                                       "already.annotated",
   782                                       kindName(s), s);
   783                         actualEnterAnnotations(annotations, localEnv, s);
   784                     } finally {
   785                         log.useSource(prev);
   786                     }
   787                 }
   788             });
   789     }
   791     /**
   792      * Check if a list of annotations contains a reference to
   793      * java.lang.Deprecated.
   794      **/
   795     private boolean hasDeprecatedAnnotation(List<JCAnnotation> annotations) {
   796         for (List<JCAnnotation> al = annotations; !al.isEmpty(); al = al.tail) {
   797             JCAnnotation a = al.head;
   798             if (a.annotationType.type == syms.deprecatedType && a.args.isEmpty())
   799                 return true;
   800         }
   801         return false;
   802     }
   804     /** Enter a set of annotations. */
   805     private void actualEnterAnnotations(List<JCAnnotation> annotations,
   806                           Env<AttrContext> env,
   807                           Symbol s) {
   808         Map<TypeSymbol, ListBuffer<Attribute.Compound>> annotated =
   809                 new LinkedHashMap<TypeSymbol, ListBuffer<Attribute.Compound>>();
   810         Map<Attribute.Compound, DiagnosticPosition> pos =
   811                 new HashMap<Attribute.Compound, DiagnosticPosition>();
   813         for (List<JCAnnotation> al = annotations; !al.isEmpty(); al = al.tail) {
   814             JCAnnotation a = al.head;
   815             Attribute.Compound c = annotate.enterAnnotation(a,
   816                                                             syms.annotationType,
   817                                                             env);
   818             if (c == null) {
   819                 continue;
   820             }
   822             if (annotated.containsKey(a.type.tsym)) {
   823                 if (source.allowRepeatedAnnotations()) {
   824                     ListBuffer<Attribute.Compound> l = annotated.get(a.type.tsym);
   825                     l = l.append(c);
   826                     annotated.put(a.type.tsym, l);
   827                     pos.put(c, a.pos());
   828                 } else {
   829                     log.error(a.pos(), "duplicate.annotation");
   830                 }
   831             } else {
   832                 annotated.put(a.type.tsym, ListBuffer.of(c));
   833                 pos.put(c, a.pos());
   834             }
   836             // Note: @Deprecated has no effect on local variables and parameters
   837             if (!c.type.isErroneous()
   838                 && s.owner.kind != MTH
   839                 && types.isSameType(c.type, syms.deprecatedType)) {
   840                 s.flags_field |= Flags.DEPRECATED;
   841             }
   842         }
   844         s.setDeclarationAttributesWithCompletion(
   845                 annotate.new AnnotateRepeatedContext<Attribute.Compound>(env, annotated, pos, log, false));
   846     }
   848     /** Queue processing of an attribute default value. */
   849     void annotateDefaultValueLater(final JCExpression defaultValue,
   850                                    final Env<AttrContext> localEnv,
   851                                    final MethodSymbol m) {
   852         annotate.normal(new Annotate.Annotator() {
   853                 @Override
   854                 public String toString() {
   855                     return "annotate " + m.owner + "." +
   856                         m + " default " + defaultValue;
   857                 }
   859                 @Override
   860                 public void enterAnnotation() {
   861                     JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile);
   862                     try {
   863                         enterDefaultValue(defaultValue, localEnv, m);
   864                     } finally {
   865                         log.useSource(prev);
   866                     }
   867                 }
   868             });
   869     }
   871     /** Enter a default value for an attribute method. */
   872     private void enterDefaultValue(final JCExpression defaultValue,
   873                                    final Env<AttrContext> localEnv,
   874                                    final MethodSymbol m) {
   875         m.defaultValue = annotate.enterAttributeValue(m.type.getReturnType(),
   876                                                       defaultValue,
   877                                                       localEnv);
   878     }
   880 /* ********************************************************************
   881  * Source completer
   882  *********************************************************************/
   884     /** Complete entering a class.
   885      *  @param sym         The symbol of the class to be completed.
   886      */
   887     public void complete(Symbol sym) throws CompletionFailure {
   888         // Suppress some (recursive) MemberEnter invocations
   889         if (!completionEnabled) {
   890             // Re-install same completer for next time around and return.
   891             Assert.check((sym.flags() & Flags.COMPOUND) == 0);
   892             sym.completer = this;
   893             return;
   894         }
   896         ClassSymbol c = (ClassSymbol)sym;
   897         ClassType ct = (ClassType)c.type;
   898         Env<AttrContext> env = enter.typeEnvs.get(c);
   899         JCClassDecl tree = (JCClassDecl)env.tree;
   900         boolean wasFirst = isFirst;
   901         isFirst = false;
   903         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   904         try {
   905             // Save class environment for later member enter (2) processing.
   906             halfcompleted.append(env);
   908             // Mark class as not yet attributed.
   909             c.flags_field |= UNATTRIBUTED;
   911             // If this is a toplevel-class, make sure any preceding import
   912             // clauses have been seen.
   913             if (c.owner.kind == PCK) {
   914                 memberEnter(env.toplevel, env.enclosing(TOPLEVEL));
   915                 todo.append(env);
   916             }
   918             if (c.owner.kind == TYP)
   919                 c.owner.complete();
   921             // create an environment for evaluating the base clauses
   922             Env<AttrContext> baseEnv = baseEnv(tree, env);
   924             if (tree.extending != null)
   925                 typeAnnotate(tree.extending, baseEnv, sym);
   926             for (JCExpression impl : tree.implementing)
   927                 typeAnnotate(impl, baseEnv, sym);
   928             annotate.flush();
   930             // Determine supertype.
   931             Type supertype =
   932                 (tree.extending != null)
   933                 ? attr.attribBase(tree.extending, baseEnv, true, false, true)
   934                 : ((tree.mods.flags & Flags.ENUM) != 0)
   935                 ? attr.attribBase(enumBase(tree.pos, c), baseEnv,
   936                                   true, false, false)
   937                 : (c.fullname == names.java_lang_Object)
   938                 ? Type.noType
   939                 : syms.objectType;
   940             ct.supertype_field = modelMissingTypes(supertype, tree.extending, false);
   942             // Determine interfaces.
   943             ListBuffer<Type> interfaces = new ListBuffer<Type>();
   944             ListBuffer<Type> all_interfaces = null; // lazy init
   945             Set<Type> interfaceSet = new HashSet<Type>();
   946             List<JCExpression> interfaceTrees = tree.implementing;
   947             for (JCExpression iface : interfaceTrees) {
   948                 Type i = attr.attribBase(iface, baseEnv, false, true, true);
   949                 if (i.hasTag(CLASS)) {
   950                     interfaces.append(i);
   951                     if (all_interfaces != null) all_interfaces.append(i);
   952                     chk.checkNotRepeated(iface.pos(), types.erasure(i), interfaceSet);
   953                 } else {
   954                     if (all_interfaces == null)
   955                         all_interfaces = new ListBuffer<Type>().appendList(interfaces);
   956                     all_interfaces.append(modelMissingTypes(i, iface, true));
   957                 }
   958             }
   959             if ((c.flags_field & ANNOTATION) != 0) {
   960                 ct.interfaces_field = List.of(syms.annotationType);
   961                 ct.all_interfaces_field = ct.interfaces_field;
   962             }  else {
   963                 ct.interfaces_field = interfaces.toList();
   964                 ct.all_interfaces_field = (all_interfaces == null)
   965                         ? ct.interfaces_field : all_interfaces.toList();
   966             }
   968             if (c.fullname == names.java_lang_Object) {
   969                 if (tree.extending != null) {
   970                     chk.checkNonCyclic(tree.extending.pos(),
   971                                        supertype);
   972                     ct.supertype_field = Type.noType;
   973                 }
   974                 else if (tree.implementing.nonEmpty()) {
   975                     chk.checkNonCyclic(tree.implementing.head.pos(),
   976                                        ct.interfaces_field.head);
   977                     ct.interfaces_field = List.nil();
   978                 }
   979             }
   981             // Annotations.
   982             // In general, we cannot fully process annotations yet,  but we
   983             // can attribute the annotation types and then check to see if the
   984             // @Deprecated annotation is present.
   985             attr.attribAnnotationTypes(tree.mods.annotations, baseEnv);
   986             if (hasDeprecatedAnnotation(tree.mods.annotations))
   987                 c.flags_field |= DEPRECATED;
   988             annotateLater(tree.mods.annotations, baseEnv, c);
   989             // class type parameters use baseEnv but everything uses env
   991             chk.checkNonCyclicDecl(tree);
   993             attr.attribTypeVariables(tree.typarams, baseEnv);
   994             // Do this here, where we have the symbol.
   995             for (JCTypeParameter tp : tree.typarams)
   996                 typeAnnotate(tp, baseEnv, sym);
   997             annotate.flush();
   999             // Add default constructor if needed.
  1000             if ((c.flags() & INTERFACE) == 0 &&
  1001                 !TreeInfo.hasConstructors(tree.defs)) {
  1002                 List<Type> argtypes = List.nil();
  1003                 List<Type> typarams = List.nil();
  1004                 List<Type> thrown = List.nil();
  1005                 long ctorFlags = 0;
  1006                 boolean based = false;
  1007                 boolean addConstructor = true;
  1008                 JCNewClass nc = null;
  1009                 if (c.name.isEmpty()) {
  1010                     nc = (JCNewClass)env.next.tree;
  1011                     if (nc.constructor != null) {
  1012                         addConstructor = nc.constructor.kind != ERR;
  1013                         Type superConstrType = types.memberType(c.type,
  1014                                                                 nc.constructor);
  1015                         argtypes = superConstrType.getParameterTypes();
  1016                         typarams = superConstrType.getTypeArguments();
  1017                         ctorFlags = nc.constructor.flags() & VARARGS;
  1018                         if (nc.encl != null) {
  1019                             argtypes = argtypes.prepend(nc.encl.type);
  1020                             based = true;
  1022                         thrown = superConstrType.getThrownTypes();
  1025                 if (addConstructor) {
  1026                     MethodSymbol basedConstructor = nc != null ?
  1027                             (MethodSymbol)nc.constructor : null;
  1028                     JCTree constrDef = DefaultConstructor(make.at(tree.pos), c,
  1029                                                         basedConstructor,
  1030                                                         typarams, argtypes, thrown,
  1031                                                         ctorFlags, based);
  1032                     tree.defs = tree.defs.prepend(constrDef);
  1036             // enter symbols for 'this' into current scope.
  1037             VarSymbol thisSym =
  1038                 new VarSymbol(FINAL | HASINIT, names._this, c.type, c);
  1039             thisSym.pos = Position.FIRSTPOS;
  1040             env.info.scope.enter(thisSym);
  1041             // if this is a class, enter symbol for 'super' into current scope.
  1042             if ((c.flags_field & INTERFACE) == 0 &&
  1043                     ct.supertype_field.hasTag(CLASS)) {
  1044                 VarSymbol superSym =
  1045                     new VarSymbol(FINAL | HASINIT, names._super,
  1046                                   ct.supertype_field, c);
  1047                 superSym.pos = Position.FIRSTPOS;
  1048                 env.info.scope.enter(superSym);
  1051             // check that no package exists with same fully qualified name,
  1052             // but admit classes in the unnamed package which have the same
  1053             // name as a top-level package.
  1054             if (checkClash &&
  1055                 c.owner.kind == PCK && c.owner != syms.unnamedPackage &&
  1056                 reader.packageExists(c.fullname)) {
  1057                 log.error(tree.pos, "clash.with.pkg.of.same.name", Kinds.kindName(sym), c);
  1059             if (c.owner.kind == PCK && (c.flags_field & PUBLIC) == 0 &&
  1060                 !env.toplevel.sourcefile.isNameCompatible(c.name.toString(),JavaFileObject.Kind.SOURCE)) {
  1061                 c.flags_field |= AUXILIARY;
  1063         } catch (CompletionFailure ex) {
  1064             chk.completionError(tree.pos(), ex);
  1065         } finally {
  1066             log.useSource(prev);
  1069         // Enter all member fields and methods of a set of half completed
  1070         // classes in a second phase.
  1071         if (wasFirst) {
  1072             try {
  1073                 while (halfcompleted.nonEmpty()) {
  1074                     finish(halfcompleted.next());
  1076             } finally {
  1077                 isFirst = true;
  1080         if (allowTypeAnnos) {
  1081             TypeAnnotations.organizeTypeAnnotationsSignatures(syms, names, log, tree, annotate);
  1085     /*
  1086      * If the symbol is non-null, attach the type annotation to it.
  1087      */
  1088     private void actualEnterTypeAnnotations(final List<JCAnnotation> annotations,
  1089             final Env<AttrContext> env,
  1090             final Symbol s) {
  1091         Map<TypeSymbol, ListBuffer<Attribute.TypeCompound>> annotated =
  1092                 new LinkedHashMap<TypeSymbol, ListBuffer<Attribute.TypeCompound>>();
  1093         Map<Attribute.TypeCompound, DiagnosticPosition> pos =
  1094                 new HashMap<Attribute.TypeCompound, DiagnosticPosition>();
  1096         for (List<JCAnnotation> al = annotations; !al.isEmpty(); al = al.tail) {
  1097             JCAnnotation a = al.head;
  1098             Attribute.TypeCompound tc = annotate.enterTypeAnnotation(a,
  1099                     syms.annotationType,
  1100                     env);
  1101             if (tc == null) {
  1102                 continue;
  1105             if (annotated.containsKey(a.type.tsym)) {
  1106                 if (source.allowRepeatedAnnotations()) {
  1107                     ListBuffer<Attribute.TypeCompound> l = annotated.get(a.type.tsym);
  1108                     l = l.append(tc);
  1109                     annotated.put(a.type.tsym, l);
  1110                     pos.put(tc, a.pos());
  1111                 } else {
  1112                     log.error(a.pos(), "duplicate.annotation");
  1114             } else {
  1115                 annotated.put(a.type.tsym, ListBuffer.of(tc));
  1116                 pos.put(tc, a.pos());
  1120         if (s != null) {
  1121             s.appendTypeAttributesWithCompletion(
  1122                     annotate.new AnnotateRepeatedContext<Attribute.TypeCompound>(env, annotated, pos, log, true));
  1126     public void typeAnnotate(final JCTree tree, final Env<AttrContext> env, final Symbol sym) {
  1127         if (allowTypeAnnos) {
  1128             tree.accept(new TypeAnnotate(env, sym));
  1132     /**
  1133      * We need to use a TreeScanner, because it is not enough to visit the top-level
  1134      * annotations. We also need to visit type arguments, etc.
  1135      */
  1136     private class TypeAnnotate extends TreeScanner {
  1137         private Env<AttrContext> env;
  1138         private Symbol sym;
  1140         public TypeAnnotate(final Env<AttrContext> env, final Symbol sym) {
  1141             this.env = env;
  1142             this.sym = sym;
  1145         void annotateTypeLater(final List<JCAnnotation> annotations) {
  1146             if (annotations.isEmpty()) {
  1147                 return;
  1150             annotate.normal(new Annotate.Annotator() {
  1151                 @Override
  1152                 public String toString() {
  1153                     return "type annotate " + annotations + " onto " + sym + " in " + sym.owner;
  1155                 @Override
  1156                 public void enterAnnotation() {
  1157                     JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
  1158                     try {
  1159                         actualEnterTypeAnnotations(annotations, env, sym);
  1160                     } finally {
  1161                         log.useSource(prev);
  1164             });
  1167         @Override
  1168         public void visitAnnotatedType(final JCAnnotatedType tree) {
  1169             annotateTypeLater(tree.annotations);
  1170             super.visitAnnotatedType(tree);
  1173         @Override
  1174         public void visitTypeParameter(final JCTypeParameter tree) {
  1175             annotateTypeLater(tree.annotations);
  1176             super.visitTypeParameter(tree);
  1179         @Override
  1180         public void visitNewArray(final JCNewArray tree) {
  1181             annotateTypeLater(tree.annotations);
  1182             for (List<JCAnnotation> dimAnnos : tree.dimAnnotations)
  1183                 annotateTypeLater(dimAnnos);
  1184             super.visitNewArray(tree);
  1187         @Override
  1188         public void visitMethodDef(final JCMethodDecl tree) {
  1189             scan(tree.mods);
  1190             scan(tree.restype);
  1191             scan(tree.typarams);
  1192             scan(tree.recvparam);
  1193             scan(tree.params);
  1194             scan(tree.thrown);
  1195             scan(tree.defaultValue);
  1196             // Do not annotate the body, just the signature.
  1197             // scan(tree.body);
  1200         @Override
  1201         public void visitVarDef(final JCVariableDecl tree) {
  1202             if (sym != null && sym.kind == Kinds.VAR) {
  1203                 // Don't visit a parameter once when the sym is the method
  1204                 // and once when the sym is the parameter.
  1205                 scan(tree.mods);
  1206                 scan(tree.vartype);
  1208             scan(tree.init);
  1211         @Override
  1212         public void visitClassDef(JCClassDecl tree) {
  1213             // We can only hit a classdef if it is declared within
  1214             // a method. Ignore it - the class will be visited
  1215             // separately later.
  1218         @Override
  1219         public void visitNewClass(JCNewClass tree) {
  1220             if (tree.def == null) {
  1221                 // For an anonymous class instantiation the class
  1222                 // will be visited separately.
  1223                 super.visitNewClass(tree);
  1229     private Env<AttrContext> baseEnv(JCClassDecl tree, Env<AttrContext> env) {
  1230         Scope baseScope = new Scope(tree.sym);
  1231         //import already entered local classes into base scope
  1232         for (Scope.Entry e = env.outer.info.scope.elems ; e != null ; e = e.sibling) {
  1233             if (e.sym.isLocal()) {
  1234                 baseScope.enter(e.sym);
  1237         //import current type-parameters into base scope
  1238         if (tree.typarams != null)
  1239             for (List<JCTypeParameter> typarams = tree.typarams;
  1240                  typarams.nonEmpty();
  1241                  typarams = typarams.tail)
  1242                 baseScope.enter(typarams.head.type.tsym);
  1243         Env<AttrContext> outer = env.outer; // the base clause can't see members of this class
  1244         Env<AttrContext> localEnv = outer.dup(tree, outer.info.dup(baseScope));
  1245         localEnv.baseClause = true;
  1246         localEnv.outer = outer;
  1247         localEnv.info.isSelfCall = false;
  1248         return localEnv;
  1251     /** Enter member fields and methods of a class
  1252      *  @param env        the environment current for the class block.
  1253      */
  1254     private void finish(Env<AttrContext> env) {
  1255         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
  1256         try {
  1257             JCClassDecl tree = (JCClassDecl)env.tree;
  1258             finishClass(tree, env);
  1259         } finally {
  1260             log.useSource(prev);
  1264     /** Generate a base clause for an enum type.
  1265      *  @param pos              The position for trees and diagnostics, if any
  1266      *  @param c                The class symbol of the enum
  1267      */
  1268     private JCExpression enumBase(int pos, ClassSymbol c) {
  1269         JCExpression result = make.at(pos).
  1270             TypeApply(make.QualIdent(syms.enumSym),
  1271                       List.<JCExpression>of(make.Type(c.type)));
  1272         return result;
  1275     Type modelMissingTypes(Type t, final JCExpression tree, final boolean interfaceExpected) {
  1276         if (!t.hasTag(ERROR))
  1277             return t;
  1279         return new ErrorType(((ErrorType) t).getOriginalType(), t.tsym) {
  1280             private Type modelType;
  1282             @Override
  1283             public Type getModelType() {
  1284                 if (modelType == null)
  1285                     modelType = new Synthesizer(getOriginalType(), interfaceExpected).visit(tree);
  1286                 return modelType;
  1288         };
  1290     // where
  1291     private class Synthesizer extends JCTree.Visitor {
  1292         Type originalType;
  1293         boolean interfaceExpected;
  1294         List<ClassSymbol> synthesizedSymbols = List.nil();
  1295         Type result;
  1297         Synthesizer(Type originalType, boolean interfaceExpected) {
  1298             this.originalType = originalType;
  1299             this.interfaceExpected = interfaceExpected;
  1302         Type visit(JCTree tree) {
  1303             tree.accept(this);
  1304             return result;
  1307         List<Type> visit(List<? extends JCTree> trees) {
  1308             ListBuffer<Type> lb = new ListBuffer<Type>();
  1309             for (JCTree t: trees)
  1310                 lb.append(visit(t));
  1311             return lb.toList();
  1314         @Override
  1315         public void visitTree(JCTree tree) {
  1316             result = syms.errType;
  1319         @Override
  1320         public void visitIdent(JCIdent tree) {
  1321             if (!tree.type.hasTag(ERROR)) {
  1322                 result = tree.type;
  1323             } else {
  1324                 result = synthesizeClass(tree.name, syms.unnamedPackage).type;
  1328         @Override
  1329         public void visitSelect(JCFieldAccess tree) {
  1330             if (!tree.type.hasTag(ERROR)) {
  1331                 result = tree.type;
  1332             } else {
  1333                 Type selectedType;
  1334                 boolean prev = interfaceExpected;
  1335                 try {
  1336                     interfaceExpected = false;
  1337                     selectedType = visit(tree.selected);
  1338                 } finally {
  1339                     interfaceExpected = prev;
  1341                 ClassSymbol c = synthesizeClass(tree.name, selectedType.tsym);
  1342                 result = c.type;
  1346         @Override
  1347         public void visitTypeApply(JCTypeApply tree) {
  1348             if (!tree.type.hasTag(ERROR)) {
  1349                 result = tree.type;
  1350             } else {
  1351                 ClassType clazzType = (ClassType) visit(tree.clazz);
  1352                 if (synthesizedSymbols.contains(clazzType.tsym))
  1353                     synthesizeTyparams((ClassSymbol) clazzType.tsym, tree.arguments.size());
  1354                 final List<Type> actuals = visit(tree.arguments);
  1355                 result = new ErrorType(tree.type, clazzType.tsym) {
  1356                     @Override
  1357                     public List<Type> getTypeArguments() {
  1358                         return actuals;
  1360                 };
  1364         ClassSymbol synthesizeClass(Name name, Symbol owner) {
  1365             int flags = interfaceExpected ? INTERFACE : 0;
  1366             ClassSymbol c = new ClassSymbol(flags, name, owner);
  1367             c.members_field = new Scope.ErrorScope(c);
  1368             c.type = new ErrorType(originalType, c) {
  1369                 @Override
  1370                 public List<Type> getTypeArguments() {
  1371                     return typarams_field;
  1373             };
  1374             synthesizedSymbols = synthesizedSymbols.prepend(c);
  1375             return c;
  1378         void synthesizeTyparams(ClassSymbol sym, int n) {
  1379             ClassType ct = (ClassType) sym.type;
  1380             Assert.check(ct.typarams_field.isEmpty());
  1381             if (n == 1) {
  1382                 TypeVar v = new TypeVar(names.fromString("T"), sym, syms.botType);
  1383                 ct.typarams_field = ct.typarams_field.prepend(v);
  1384             } else {
  1385                 for (int i = n; i > 0; i--) {
  1386                     TypeVar v = new TypeVar(names.fromString("T" + i), sym, syms.botType);
  1387                     ct.typarams_field = ct.typarams_field.prepend(v);
  1394 /* ***************************************************************************
  1395  * tree building
  1396  ****************************************************************************/
  1398     /** Generate default constructor for given class. For classes different
  1399      *  from java.lang.Object, this is:
  1401      *    c(argtype_0 x_0, ..., argtype_n x_n) throws thrown {
  1402      *      super(x_0, ..., x_n)
  1403      *    }
  1405      *  or, if based == true:
  1407      *    c(argtype_0 x_0, ..., argtype_n x_n) throws thrown {
  1408      *      x_0.super(x_1, ..., x_n)
  1409      *    }
  1411      *  @param make     The tree factory.
  1412      *  @param c        The class owning the default constructor.
  1413      *  @param argtypes The parameter types of the constructor.
  1414      *  @param thrown   The thrown exceptions of the constructor.
  1415      *  @param based    Is first parameter a this$n?
  1416      */
  1417     JCTree DefaultConstructor(TreeMaker make,
  1418                             ClassSymbol c,
  1419                             MethodSymbol baseInit,
  1420                             List<Type> typarams,
  1421                             List<Type> argtypes,
  1422                             List<Type> thrown,
  1423                             long flags,
  1424                             boolean based) {
  1425         JCTree result;
  1426         if ((c.flags() & ENUM) != 0 &&
  1427             (types.supertype(c.type).tsym == syms.enumSym)) {
  1428             // constructors of true enums are private
  1429             flags = (flags & ~AccessFlags) | PRIVATE | GENERATEDCONSTR;
  1430         } else
  1431             flags |= (c.flags() & AccessFlags) | GENERATEDCONSTR;
  1432         if (c.name.isEmpty()) {
  1433             flags |= ANONCONSTR;
  1435         Type mType = new MethodType(argtypes, null, thrown, c);
  1436         Type initType = typarams.nonEmpty() ?
  1437                 new ForAll(typarams, mType) :
  1438                 mType;
  1439         MethodSymbol init = new MethodSymbol(flags, names.init,
  1440                 initType, c);
  1441         init.params = createDefaultConstructorParams(make, baseInit, init,
  1442                 argtypes, based);
  1443         List<JCVariableDecl> params = make.Params(argtypes, init);
  1444         List<JCStatement> stats = List.nil();
  1445         if (c.type != syms.objectType) {
  1446             stats = stats.prepend(SuperCall(make, typarams, params, based));
  1448         result = make.MethodDef(init, make.Block(0, stats));
  1449         return result;
  1452     private List<VarSymbol> createDefaultConstructorParams(
  1453             TreeMaker make,
  1454             MethodSymbol baseInit,
  1455             MethodSymbol init,
  1456             List<Type> argtypes,
  1457             boolean based) {
  1458         List<VarSymbol> initParams = null;
  1459         List<Type> argTypesList = argtypes;
  1460         if (based) {
  1461             /*  In this case argtypes will have an extra type, compared to baseInit,
  1462              *  corresponding to the type of the enclosing instance i.e.:
  1464              *  Inner i = outer.new Inner(1){}
  1466              *  in the above example argtypes will be (Outer, int) and baseInit
  1467              *  will have parameter's types (int). So in this case we have to add
  1468              *  first the extra type in argtypes and then get the names of the
  1469              *  parameters from baseInit.
  1470              */
  1471             initParams = List.nil();
  1472             VarSymbol param = new VarSymbol(0, make.paramName(0), argtypes.head, init);
  1473             initParams = initParams.append(param);
  1474             argTypesList = argTypesList.tail;
  1476         if (baseInit != null && baseInit.params != null &&
  1477             baseInit.params.nonEmpty() && argTypesList.nonEmpty()) {
  1478             initParams = (initParams == null) ? List.<VarSymbol>nil() : initParams;
  1479             List<VarSymbol> baseInitParams = baseInit.params;
  1480             while (baseInitParams.nonEmpty() && argTypesList.nonEmpty()) {
  1481                 VarSymbol param = new VarSymbol(baseInitParams.head.flags(),
  1482                         baseInitParams.head.name, argTypesList.head, init);
  1483                 initParams = initParams.append(param);
  1484                 baseInitParams = baseInitParams.tail;
  1485                 argTypesList = argTypesList.tail;
  1488         return initParams;
  1491     /** Generate call to superclass constructor. This is:
  1493      *    super(id_0, ..., id_n)
  1495      * or, if based == true
  1497      *    id_0.super(id_1,...,id_n)
  1499      *  where id_0, ..., id_n are the names of the given parameters.
  1501      *  @param make    The tree factory
  1502      *  @param params  The parameters that need to be passed to super
  1503      *  @param typarams  The type parameters that need to be passed to super
  1504      *  @param based   Is first parameter a this$n?
  1505      */
  1506     JCExpressionStatement SuperCall(TreeMaker make,
  1507                    List<Type> typarams,
  1508                    List<JCVariableDecl> params,
  1509                    boolean based) {
  1510         JCExpression meth;
  1511         if (based) {
  1512             meth = make.Select(make.Ident(params.head), names._super);
  1513             params = params.tail;
  1514         } else {
  1515             meth = make.Ident(names._super);
  1517         List<JCExpression> typeargs = typarams.nonEmpty() ? make.Types(typarams) : null;
  1518         return make.Exec(make.Apply(typeargs, meth, make.Idents(params)));

mercurial