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

Wed, 27 Apr 2016 01:34:52 +0800

author
aoqi
date
Wed, 27 Apr 2016 01:34:52 +0800
changeset 0
959103a6100f
child 2525
2eb010b6cb22
permissions
-rw-r--r--

Initial load
http://hg.openjdk.java.net/jdk8u/jdk8u/langtools/
changeset: 2573:53ca196be1ae
tag: jdk8u25-b17

     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 TypeAnnotations typeAnnotations;
    83     private final Types types;
    84     private final JCDiagnostic.Factory diags;
    85     private final Source source;
    86     private final Target target;
    87     private final DeferredLintHandler deferredLintHandler;
    88     private final Lint lint;
    89     private final TypeEnvs typeEnvs;
    91     public static MemberEnter instance(Context context) {
    92         MemberEnter instance = context.get(memberEnterKey);
    93         if (instance == null)
    94             instance = new MemberEnter(context);
    95         return instance;
    96     }
    98     protected MemberEnter(Context context) {
    99         context.put(memberEnterKey, this);
   100         names = Names.instance(context);
   101         enter = Enter.instance(context);
   102         log = Log.instance(context);
   103         chk = Check.instance(context);
   104         attr = Attr.instance(context);
   105         syms = Symtab.instance(context);
   106         make = TreeMaker.instance(context);
   107         reader = ClassReader.instance(context);
   108         todo = Todo.instance(context);
   109         annotate = Annotate.instance(context);
   110         typeAnnotations = TypeAnnotations.instance(context);
   111         types = Types.instance(context);
   112         diags = JCDiagnostic.Factory.instance(context);
   113         source = Source.instance(context);
   114         target = Target.instance(context);
   115         deferredLintHandler = DeferredLintHandler.instance(context);
   116         lint = Lint.instance(context);
   117         typeEnvs = TypeEnvs.instance(context);
   118         allowTypeAnnos = source.allowTypeAnnotations();
   119         allowRepeatedAnnos = source.allowRepeatedAnnotations();
   120     }
   122     /** Switch: support type annotations.
   123      */
   124     boolean allowTypeAnnos;
   126     boolean allowRepeatedAnnos;
   128     /** A queue for classes whose members still need to be entered into the
   129      *  symbol table.
   130      */
   131     ListBuffer<Env<AttrContext>> halfcompleted = new ListBuffer<Env<AttrContext>>();
   133     /** Set to true only when the first of a set of classes is
   134      *  processed from the half completed queue.
   135      */
   136     boolean isFirst = true;
   138     /** A flag to disable completion from time to time during member
   139      *  enter, as we only need to look up types.  This avoids
   140      *  unnecessarily deep recursion.
   141      */
   142     boolean completionEnabled = true;
   144     /* ---------- Processing import clauses ----------------
   145      */
   147     /** Import all classes of a class or package on demand.
   148      *  @param pos           Position to be used for error reporting.
   149      *  @param tsym          The class or package the members of which are imported.
   150      *  @param env           The env in which the imported classes will be entered.
   151      */
   152     private void importAll(int pos,
   153                            final TypeSymbol tsym,
   154                            Env<AttrContext> env) {
   155         // Check that packages imported from exist (JLS ???).
   156         if (tsym.kind == PCK && tsym.members().elems == null && !tsym.exists()) {
   157             // If we can't find java.lang, exit immediately.
   158             if (((PackageSymbol)tsym).fullname.equals(names.java_lang)) {
   159                 JCDiagnostic msg = diags.fragment("fatal.err.no.java.lang");
   160                 throw new FatalError(msg);
   161             } else {
   162                 log.error(DiagnosticFlag.RESOLVE_ERROR, pos, "doesnt.exist", tsym);
   163             }
   164         }
   165         env.toplevel.starImportScope.importAll(tsym.members());
   166     }
   168     /** Import all static members of a class or package on demand.
   169      *  @param pos           Position to be used for error reporting.
   170      *  @param tsym          The class or package the members of which are imported.
   171      *  @param env           The env in which the imported classes will be entered.
   172      */
   173     private void importStaticAll(int pos,
   174                                  final TypeSymbol tsym,
   175                                  Env<AttrContext> env) {
   176         final JavaFileObject sourcefile = env.toplevel.sourcefile;
   177         final Scope toScope = env.toplevel.starImportScope;
   178         final PackageSymbol packge = env.toplevel.packge;
   179         final TypeSymbol origin = tsym;
   181         // enter imported types immediately
   182         new Object() {
   183             Set<Symbol> processed = new HashSet<Symbol>();
   184             void importFrom(TypeSymbol tsym) {
   185                 if (tsym == null || !processed.add(tsym))
   186                     return;
   188                 // also import inherited names
   189                 importFrom(types.supertype(tsym.type).tsym);
   190                 for (Type t : types.interfaces(tsym.type))
   191                     importFrom(t.tsym);
   193                 final Scope fromScope = tsym.members();
   194                 for (Scope.Entry e = fromScope.elems; e != null; e = e.sibling) {
   195                     Symbol sym = e.sym;
   196                     if (sym.kind == TYP &&
   197                         (sym.flags() & STATIC) != 0 &&
   198                         staticImportAccessible(sym, packge) &&
   199                         sym.isMemberOf(origin, types) &&
   200                         !toScope.includes(sym))
   201                         toScope.enter(sym, fromScope, origin.members(), true);
   202                 }
   203             }
   204         }.importFrom(tsym);
   206         // enter non-types before annotations that might use them
   207         annotate.earlier(new Annotate.Worker() {
   208             Set<Symbol> processed = new HashSet<Symbol>();
   210             public String toString() {
   211                 return "import static " + tsym + ".*" + " in " + sourcefile;
   212             }
   213             void importFrom(TypeSymbol tsym) {
   214                 if (tsym == null || !processed.add(tsym))
   215                     return;
   217                 // also import inherited names
   218                 importFrom(types.supertype(tsym.type).tsym);
   219                 for (Type t : types.interfaces(tsym.type))
   220                     importFrom(t.tsym);
   222                 final Scope fromScope = tsym.members();
   223                 for (Scope.Entry e = fromScope.elems; e != null; e = e.sibling) {
   224                     Symbol sym = e.sym;
   225                     if (sym.isStatic() && sym.kind != TYP &&
   226                         staticImportAccessible(sym, packge) &&
   227                         !toScope.includes(sym) &&
   228                         sym.isMemberOf(origin, types)) {
   229                         toScope.enter(sym, fromScope, origin.members(), true);
   230                     }
   231                 }
   232             }
   233             public void run() {
   234                 importFrom(tsym);
   235             }
   236         });
   237     }
   239     // is the sym accessible everywhere in packge?
   240     boolean staticImportAccessible(Symbol sym, PackageSymbol packge) {
   241         int flags = (int)(sym.flags() & AccessFlags);
   242         switch (flags) {
   243         default:
   244         case PUBLIC:
   245             return true;
   246         case PRIVATE:
   247             return false;
   248         case 0:
   249         case PROTECTED:
   250             return sym.packge() == packge;
   251         }
   252     }
   254     /** Import statics types of a given name.  Non-types are handled in Attr.
   255      *  @param pos           Position to be used for error reporting.
   256      *  @param tsym          The class from which the name is imported.
   257      *  @param name          The (simple) name being imported.
   258      *  @param env           The environment containing the named import
   259      *                  scope to add to.
   260      */
   261     private void importNamedStatic(final DiagnosticPosition pos,
   262                                    final TypeSymbol tsym,
   263                                    final Name name,
   264                                    final Env<AttrContext> env) {
   265         if (tsym.kind != TYP) {
   266             log.error(DiagnosticFlag.RECOVERABLE, pos, "static.imp.only.classes.and.interfaces");
   267             return;
   268         }
   270         final Scope toScope = env.toplevel.namedImportScope;
   271         final PackageSymbol packge = env.toplevel.packge;
   272         final TypeSymbol origin = tsym;
   274         // enter imported types immediately
   275         new Object() {
   276             Set<Symbol> processed = new HashSet<Symbol>();
   277             void importFrom(TypeSymbol tsym) {
   278                 if (tsym == null || !processed.add(tsym))
   279                     return;
   281                 // also import inherited names
   282                 importFrom(types.supertype(tsym.type).tsym);
   283                 for (Type t : types.interfaces(tsym.type))
   284                     importFrom(t.tsym);
   286                 for (Scope.Entry e = tsym.members().lookup(name);
   287                      e.scope != null;
   288                      e = e.next()) {
   289                     Symbol sym = e.sym;
   290                     if (sym.isStatic() &&
   291                         sym.kind == TYP &&
   292                         staticImportAccessible(sym, packge) &&
   293                         sym.isMemberOf(origin, types) &&
   294                         chk.checkUniqueStaticImport(pos, sym, toScope))
   295                         toScope.enter(sym, sym.owner.members(), origin.members(), true);
   296                 }
   297             }
   298         }.importFrom(tsym);
   300         // enter non-types before annotations that might use them
   301         annotate.earlier(new Annotate.Worker() {
   302             Set<Symbol> processed = new HashSet<Symbol>();
   303             boolean found = false;
   305             public String toString() {
   306                 return "import static " + tsym + "." + name;
   307             }
   308             void importFrom(TypeSymbol tsym) {
   309                 if (tsym == null || !processed.add(tsym))
   310                     return;
   312                 // also import inherited names
   313                 importFrom(types.supertype(tsym.type).tsym);
   314                 for (Type t : types.interfaces(tsym.type))
   315                     importFrom(t.tsym);
   317                 for (Scope.Entry e = tsym.members().lookup(name);
   318                      e.scope != null;
   319                      e = e.next()) {
   320                     Symbol sym = e.sym;
   321                     if (sym.isStatic() &&
   322                         staticImportAccessible(sym, packge) &&
   323                         sym.isMemberOf(origin, types)) {
   324                         found = true;
   325                         if (sym.kind != TYP) {
   326                             toScope.enter(sym, sym.owner.members(), origin.members(), true);
   327                         }
   328                     }
   329                 }
   330             }
   331             public void run() {
   332                 JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   333                 try {
   334                     importFrom(tsym);
   335                     if (!found) {
   336                         log.error(pos, "cant.resolve.location",
   337                                   KindName.STATIC,
   338                                   name, List.<Type>nil(), List.<Type>nil(),
   339                                   Kinds.typeKindName(tsym.type),
   340                                   tsym.type);
   341                     }
   342                 } finally {
   343                     log.useSource(prev);
   344                 }
   345             }
   346         });
   347     }
   348     /** Import given class.
   349      *  @param pos           Position to be used for error reporting.
   350      *  @param tsym          The class to be imported.
   351      *  @param env           The environment containing the named import
   352      *                  scope to add to.
   353      */
   354     private void importNamed(DiagnosticPosition pos, Symbol tsym, Env<AttrContext> env) {
   355         if (tsym.kind == TYP &&
   356             chk.checkUniqueImport(pos, tsym, env.toplevel.namedImportScope))
   357             env.toplevel.namedImportScope.enter(tsym, tsym.owner.members());
   358     }
   360     /** Construct method type from method signature.
   361      *  @param typarams    The method's type parameters.
   362      *  @param params      The method's value parameters.
   363      *  @param res             The method's result type,
   364      *                 null if it is a constructor.
   365      *  @param recvparam       The method's receiver parameter,
   366      *                 null if none given; TODO: or already set here?
   367      *  @param thrown      The method's thrown exceptions.
   368      *  @param env             The method's (local) environment.
   369      */
   370     Type signature(MethodSymbol msym,
   371                    List<JCTypeParameter> typarams,
   372                    List<JCVariableDecl> params,
   373                    JCTree res,
   374                    JCVariableDecl recvparam,
   375                    List<JCExpression> thrown,
   376                    Env<AttrContext> env) {
   378         // Enter and attribute type parameters.
   379         List<Type> tvars = enter.classEnter(typarams, env);
   380         attr.attribTypeVariables(typarams, env);
   382         // Enter and attribute value parameters.
   383         ListBuffer<Type> argbuf = new ListBuffer<Type>();
   384         for (List<JCVariableDecl> l = params; l.nonEmpty(); l = l.tail) {
   385             memberEnter(l.head, env);
   386             argbuf.append(l.head.vartype.type);
   387         }
   389         // Attribute result type, if one is given.
   390         Type restype = res == null ? syms.voidType : attr.attribType(res, env);
   392         // Attribute receiver type, if one is given.
   393         Type recvtype;
   394         if (recvparam!=null) {
   395             memberEnter(recvparam, env);
   396             recvtype = recvparam.vartype.type;
   397         } else {
   398             recvtype = null;
   399         }
   401         // Attribute thrown exceptions.
   402         ListBuffer<Type> thrownbuf = new ListBuffer<Type>();
   403         for (List<JCExpression> l = thrown; l.nonEmpty(); l = l.tail) {
   404             Type exc = attr.attribType(l.head, env);
   405             if (!exc.hasTag(TYPEVAR)) {
   406                 exc = chk.checkClassType(l.head.pos(), exc);
   407             } else if (exc.tsym.owner == msym) {
   408                 //mark inference variables in 'throws' clause
   409                 exc.tsym.flags_field |= THROWS;
   410             }
   411             thrownbuf.append(exc);
   412         }
   413         MethodType mtype = new MethodType(argbuf.toList(),
   414                                     restype,
   415                                     thrownbuf.toList(),
   416                                     syms.methodClass);
   417         mtype.recvtype = recvtype;
   419         return tvars.isEmpty() ? mtype : new ForAll(tvars, mtype);
   420     }
   422 /* ********************************************************************
   423  * Visitor methods for member enter
   424  *********************************************************************/
   426     /** Visitor argument: the current environment
   427      */
   428     protected Env<AttrContext> env;
   430     /** Enter field and method definitions and process import
   431      *  clauses, catching any completion failure exceptions.
   432      */
   433     protected void memberEnter(JCTree tree, Env<AttrContext> env) {
   434         Env<AttrContext> prevEnv = this.env;
   435         try {
   436             this.env = env;
   437             tree.accept(this);
   438         }  catch (CompletionFailure ex) {
   439             chk.completionError(tree.pos(), ex);
   440         } finally {
   441             this.env = prevEnv;
   442         }
   443     }
   445     /** Enter members from a list of trees.
   446      */
   447     void memberEnter(List<? extends JCTree> trees, Env<AttrContext> env) {
   448         for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
   449             memberEnter(l.head, env);
   450     }
   452     /** Enter members for a class.
   453      */
   454     void finishClass(JCClassDecl tree, Env<AttrContext> env) {
   455         if ((tree.mods.flags & Flags.ENUM) != 0 &&
   456             (types.supertype(tree.sym.type).tsym.flags() & Flags.ENUM) == 0) {
   457             addEnumMembers(tree, env);
   458         }
   459         memberEnter(tree.defs, env);
   460     }
   462     /** Add the implicit members for an enum type
   463      *  to the symbol table.
   464      */
   465     private void addEnumMembers(JCClassDecl tree, Env<AttrContext> env) {
   466         JCExpression valuesType = make.Type(new ArrayType(tree.sym.type, syms.arrayClass));
   468         // public static T[] values() { return ???; }
   469         JCMethodDecl values = make.
   470             MethodDef(make.Modifiers(Flags.PUBLIC|Flags.STATIC),
   471                       names.values,
   472                       valuesType,
   473                       List.<JCTypeParameter>nil(),
   474                       List.<JCVariableDecl>nil(),
   475                       List.<JCExpression>nil(), // thrown
   476                       null, //make.Block(0, Tree.emptyList.prepend(make.Return(make.Ident(names._null)))),
   477                       null);
   478         memberEnter(values, env);
   480         // public static T valueOf(String name) { return ???; }
   481         JCMethodDecl valueOf = make.
   482             MethodDef(make.Modifiers(Flags.PUBLIC|Flags.STATIC),
   483                       names.valueOf,
   484                       make.Type(tree.sym.type),
   485                       List.<JCTypeParameter>nil(),
   486                       List.of(make.VarDef(make.Modifiers(Flags.PARAMETER |
   487                                                          Flags.MANDATED),
   488                                             names.fromString("name"),
   489                                             make.Type(syms.stringType), null)),
   490                       List.<JCExpression>nil(), // thrown
   491                       null, //make.Block(0, Tree.emptyList.prepend(make.Return(make.Ident(names._null)))),
   492                       null);
   493         memberEnter(valueOf, env);
   494     }
   496     public void visitTopLevel(JCCompilationUnit tree) {
   497         if (tree.starImportScope.elems != null) {
   498             // we must have already processed this toplevel
   499             return;
   500         }
   502         // check that no class exists with same fully qualified name as
   503         // toplevel package
   504         if (checkClash && tree.pid != null) {
   505             Symbol p = tree.packge;
   506             while (p.owner != syms.rootPackage) {
   507                 p.owner.complete(); // enter all class members of p
   508                 if (syms.classes.get(p.getQualifiedName()) != null) {
   509                     log.error(tree.pos,
   510                               "pkg.clashes.with.class.of.same.name",
   511                               p);
   512                 }
   513                 p = p.owner;
   514             }
   515         }
   517         // process package annotations
   518         annotateLater(tree.packageAnnotations, env, tree.packge, null);
   520         DiagnosticPosition prevLintPos = deferredLintHandler.immediate();
   521         Lint prevLint = chk.setLint(lint);
   523         try {
   524             // Import-on-demand java.lang.
   525             importAll(tree.pos, reader.enterPackage(names.java_lang), env);
   527             // Process all import clauses.
   528             memberEnter(tree.defs, env);
   529         } finally {
   530             chk.setLint(prevLint);
   531             deferredLintHandler.setPos(prevLintPos);
   532         }
   533     }
   535     // process the non-static imports and the static imports of types.
   536     public void visitImport(JCImport tree) {
   537         JCFieldAccess imp = (JCFieldAccess)tree.qualid;
   538         Name name = TreeInfo.name(imp);
   540         // Create a local environment pointing to this tree to disable
   541         // effects of other imports in Resolve.findGlobalType
   542         Env<AttrContext> localEnv = env.dup(tree);
   544         TypeSymbol p = attr.attribImportQualifier(tree, localEnv).tsym;
   545         if (name == names.asterisk) {
   546             // Import on demand.
   547             chk.checkCanonical(imp.selected);
   548             if (tree.staticImport)
   549                 importStaticAll(tree.pos, p, env);
   550             else
   551                 importAll(tree.pos, p, env);
   552         } else {
   553             // Named type import.
   554             if (tree.staticImport) {
   555                 importNamedStatic(tree.pos(), p, name, localEnv);
   556                 chk.checkCanonical(imp.selected);
   557             } else {
   558                 TypeSymbol c = attribImportType(imp, localEnv).tsym;
   559                 chk.checkCanonical(imp);
   560                 importNamed(tree.pos(), c, env);
   561             }
   562         }
   563     }
   565     public void visitMethodDef(JCMethodDecl tree) {
   566         Scope enclScope = enter.enterScope(env);
   567         MethodSymbol m = new MethodSymbol(0, tree.name, null, enclScope.owner);
   568         m.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, m, tree);
   569         tree.sym = m;
   571         //if this is a default method, add the DEFAULT flag to the enclosing interface
   572         if ((tree.mods.flags & DEFAULT) != 0) {
   573             m.enclClass().flags_field |= DEFAULT;
   574         }
   576         Env<AttrContext> localEnv = methodEnv(tree, env);
   578         annotate.enterStart();
   579         try {
   580             DiagnosticPosition prevLintPos = deferredLintHandler.setPos(tree.pos());
   581             try {
   582                 // Compute the method type
   583                 m.type = signature(m, tree.typarams, tree.params,
   584                                    tree.restype, tree.recvparam,
   585                                    tree.thrown,
   586                                    localEnv);
   587             } finally {
   588                 deferredLintHandler.setPos(prevLintPos);
   589             }
   591             if (types.isSignaturePolymorphic(m)) {
   592                 m.flags_field |= SIGNATURE_POLYMORPHIC;
   593             }
   595             // Set m.params
   596             ListBuffer<VarSymbol> params = new ListBuffer<VarSymbol>();
   597             JCVariableDecl lastParam = null;
   598             for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
   599                 JCVariableDecl param = lastParam = l.head;
   600                 params.append(Assert.checkNonNull(param.sym));
   601             }
   602             m.params = params.toList();
   604             // mark the method varargs, if necessary
   605             if (lastParam != null && (lastParam.mods.flags & Flags.VARARGS) != 0)
   606                 m.flags_field |= Flags.VARARGS;
   608             localEnv.info.scope.leave();
   609             if (chk.checkUnique(tree.pos(), m, enclScope)) {
   610             enclScope.enter(m);
   611             }
   613             annotateLater(tree.mods.annotations, localEnv, m, tree.pos());
   614             // Visit the signature of the method. Note that
   615             // TypeAnnotate doesn't descend into the body.
   616             typeAnnotate(tree, localEnv, m, tree.pos());
   618             if (tree.defaultValue != null)
   619                 annotateDefaultValueLater(tree.defaultValue, localEnv, m);
   620         } finally {
   621             annotate.enterDone();
   622         }
   623     }
   625     /** Create a fresh environment for method bodies.
   626      *  @param tree     The method definition.
   627      *  @param env      The environment current outside of the method definition.
   628      */
   629     Env<AttrContext> methodEnv(JCMethodDecl tree, Env<AttrContext> env) {
   630         Env<AttrContext> localEnv =
   631             env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
   632         localEnv.enclMethod = tree;
   633         localEnv.info.scope.owner = tree.sym;
   634         if (tree.sym.type != null) {
   635             //when this is called in the enter stage, there's no type to be set
   636             localEnv.info.returnResult = attr.new ResultInfo(VAL, tree.sym.type.getReturnType());
   637         }
   638         if ((tree.mods.flags & STATIC) != 0) localEnv.info.staticLevel++;
   639         return localEnv;
   640     }
   642     public void visitVarDef(JCVariableDecl tree) {
   643         Env<AttrContext> localEnv = env;
   644         if ((tree.mods.flags & STATIC) != 0 ||
   645             (env.info.scope.owner.flags() & INTERFACE) != 0) {
   646             localEnv = env.dup(tree, env.info.dup());
   647             localEnv.info.staticLevel++;
   648         }
   649         DiagnosticPosition prevLintPos = deferredLintHandler.setPos(tree.pos());
   650         annotate.enterStart();
   651         try {
   652             try {
   653                 if (TreeInfo.isEnumInit(tree)) {
   654                     attr.attribIdentAsEnumType(localEnv, (JCIdent)tree.vartype);
   655                 } else {
   656                     attr.attribType(tree.vartype, localEnv);
   657                     if (TreeInfo.isReceiverParam(tree))
   658                         checkReceiver(tree, localEnv);
   659                 }
   660             } finally {
   661                 deferredLintHandler.setPos(prevLintPos);
   662             }
   664             if ((tree.mods.flags & VARARGS) != 0) {
   665                 //if we are entering a varargs parameter, we need to
   666                 //replace its type (a plain array type) with the more
   667                 //precise VarargsType --- we need to do it this way
   668                 //because varargs is represented in the tree as a
   669                 //modifier on the parameter declaration, and not as a
   670                 //distinct type of array node.
   671                 ArrayType atype = (ArrayType)tree.vartype.type.unannotatedType();
   672                 tree.vartype.type = atype.makeVarargs();
   673             }
   674             Scope enclScope = enter.enterScope(env);
   675             VarSymbol v =
   676                 new VarSymbol(0, tree.name, tree.vartype.type, enclScope.owner);
   677             v.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, v, tree);
   678             tree.sym = v;
   679             if (tree.init != null) {
   680                 v.flags_field |= HASINIT;
   681                 if ((v.flags_field & FINAL) != 0 &&
   682                     needsLazyConstValue(tree.init)) {
   683                     Env<AttrContext> initEnv = getInitEnv(tree, env);
   684                     initEnv.info.enclVar = v;
   685                     v.setLazyConstValue(initEnv(tree, initEnv), attr, tree);
   686                 }
   687             }
   688             if (chk.checkUnique(tree.pos(), v, enclScope)) {
   689                 chk.checkTransparentVar(tree.pos(), v, enclScope);
   690                 enclScope.enter(v);
   691             }
   692             annotateLater(tree.mods.annotations, localEnv, v, tree.pos());
   693             typeAnnotate(tree.vartype, env, v, tree.pos());
   694             v.pos = tree.pos;
   695         } finally {
   696             annotate.enterDone();
   697         }
   698     }
   699     // where
   700     void checkType(JCTree tree, Type type, String diag) {
   701         if (!tree.type.isErroneous() && !types.isSameType(tree.type, type)) {
   702             log.error(tree, diag, type, tree.type);
   703         }
   704     }
   705     void checkReceiver(JCVariableDecl tree, Env<AttrContext> localEnv) {
   706         attr.attribExpr(tree.nameexpr, localEnv);
   707         MethodSymbol m = localEnv.enclMethod.sym;
   708         if (m.isConstructor()) {
   709             Type outertype = m.owner.owner.type;
   710             if (outertype.hasTag(TypeTag.METHOD)) {
   711                 // we have a local inner class
   712                 outertype = m.owner.owner.owner.type;
   713             }
   714             if (outertype.hasTag(TypeTag.CLASS)) {
   715                 checkType(tree.vartype, outertype, "incorrect.constructor.receiver.type");
   716                 checkType(tree.nameexpr, outertype, "incorrect.constructor.receiver.name");
   717             } else {
   718                 log.error(tree, "receiver.parameter.not.applicable.constructor.toplevel.class");
   719             }
   720         } else {
   721             checkType(tree.vartype, m.owner.type, "incorrect.receiver.type");
   722             checkType(tree.nameexpr, m.owner.type, "incorrect.receiver.name");
   723         }
   724     }
   726     public boolean needsLazyConstValue(JCTree tree) {
   727         InitTreeVisitor initTreeVisitor = new InitTreeVisitor();
   728         tree.accept(initTreeVisitor);
   729         return initTreeVisitor.result;
   730     }
   732     /** Visitor class for expressions which might be constant expressions.
   733      */
   734     static class InitTreeVisitor extends JCTree.Visitor {
   736         private boolean result = true;
   738         @Override
   739         public void visitTree(JCTree tree) {}
   741         @Override
   742         public void visitNewClass(JCNewClass that) {
   743             result = false;
   744         }
   746         @Override
   747         public void visitNewArray(JCNewArray that) {
   748             result = false;
   749         }
   751         @Override
   752         public void visitLambda(JCLambda that) {
   753             result = false;
   754         }
   756         @Override
   757         public void visitReference(JCMemberReference that) {
   758             result = false;
   759         }
   761         @Override
   762         public void visitApply(JCMethodInvocation that) {
   763             result = false;
   764         }
   766         @Override
   767         public void visitSelect(JCFieldAccess tree) {
   768             tree.selected.accept(this);
   769         }
   771         @Override
   772         public void visitConditional(JCConditional tree) {
   773             tree.cond.accept(this);
   774             tree.truepart.accept(this);
   775             tree.falsepart.accept(this);
   776         }
   778         @Override
   779         public void visitParens(JCParens tree) {
   780             tree.expr.accept(this);
   781         }
   783         @Override
   784         public void visitTypeCast(JCTypeCast tree) {
   785             tree.expr.accept(this);
   786         }
   787     }
   789     /** Create a fresh environment for a variable's initializer.
   790      *  If the variable is a field, the owner of the environment's scope
   791      *  is be the variable itself, otherwise the owner is the method
   792      *  enclosing the variable definition.
   793      *
   794      *  @param tree     The variable definition.
   795      *  @param env      The environment current outside of the variable definition.
   796      */
   797     Env<AttrContext> initEnv(JCVariableDecl tree, Env<AttrContext> env) {
   798         Env<AttrContext> localEnv = env.dupto(new AttrContextEnv(tree, env.info.dup()));
   799         if (tree.sym.owner.kind == TYP) {
   800             localEnv.info.scope = env.info.scope.dupUnshared();
   801             localEnv.info.scope.owner = tree.sym;
   802         }
   803         if ((tree.mods.flags & STATIC) != 0 ||
   804                 ((env.enclClass.sym.flags() & INTERFACE) != 0 && env.enclMethod == null))
   805             localEnv.info.staticLevel++;
   806         return localEnv;
   807     }
   809     /** Default member enter visitor method: do nothing
   810      */
   811     public void visitTree(JCTree tree) {
   812     }
   814     public void visitErroneous(JCErroneous tree) {
   815         if (tree.errs != null)
   816             memberEnter(tree.errs, env);
   817     }
   819     public Env<AttrContext> getMethodEnv(JCMethodDecl tree, Env<AttrContext> env) {
   820         Env<AttrContext> mEnv = methodEnv(tree, env);
   821         mEnv.info.lint = mEnv.info.lint.augment(tree.sym);
   822         for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
   823             mEnv.info.scope.enterIfAbsent(l.head.type.tsym);
   824         for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail)
   825             mEnv.info.scope.enterIfAbsent(l.head.sym);
   826         return mEnv;
   827     }
   829     public Env<AttrContext> getInitEnv(JCVariableDecl tree, Env<AttrContext> env) {
   830         Env<AttrContext> iEnv = initEnv(tree, env);
   831         return iEnv;
   832     }
   834 /* ********************************************************************
   835  * Type completion
   836  *********************************************************************/
   838     Type attribImportType(JCTree tree, Env<AttrContext> env) {
   839         Assert.check(completionEnabled);
   840         try {
   841             // To prevent deep recursion, suppress completion of some
   842             // types.
   843             completionEnabled = false;
   844             return attr.attribType(tree, env);
   845         } finally {
   846             completionEnabled = true;
   847         }
   848     }
   850 /* ********************************************************************
   851  * Annotation processing
   852  *********************************************************************/
   854     /** Queue annotations for later processing. */
   855     void annotateLater(final List<JCAnnotation> annotations,
   856                        final Env<AttrContext> localEnv,
   857                        final Symbol s,
   858                        final DiagnosticPosition deferPos) {
   859         if (annotations.isEmpty()) {
   860             return;
   861         }
   862         if (s.kind != PCK) {
   863             s.resetAnnotations(); // mark Annotations as incomplete for now
   864         }
   865         annotate.normal(new Annotate.Worker() {
   866                 @Override
   867                 public String toString() {
   868                     return "annotate " + annotations + " onto " + s + " in " + s.owner;
   869                 }
   871                 @Override
   872                 public void run() {
   873                     Assert.check(s.kind == PCK || s.annotationsPendingCompletion());
   874                     JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile);
   875                     DiagnosticPosition prevLintPos =
   876                         deferPos != null
   877                         ? deferredLintHandler.setPos(deferPos)
   878                         : deferredLintHandler.immediate();
   879                     Lint prevLint = deferPos != null ? null : chk.setLint(lint);
   880                     try {
   881                         if (s.hasAnnotations() &&
   882                             annotations.nonEmpty())
   883                             log.error(annotations.head.pos,
   884                                       "already.annotated",
   885                                       kindName(s), s);
   886                         actualEnterAnnotations(annotations, localEnv, s);
   887                     } finally {
   888                         if (prevLint != null)
   889                             chk.setLint(prevLint);
   890                         deferredLintHandler.setPos(prevLintPos);
   891                         log.useSource(prev);
   892                     }
   893                 }
   894             });
   896         annotate.validate(new Annotate.Worker() { //validate annotations
   897             @Override
   898             public void run() {
   899                 JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile);
   900                 try {
   901                     chk.validateAnnotations(annotations, s);
   902                 } finally {
   903                     log.useSource(prev);
   904                 }
   905             }
   906         });
   907     }
   909     /**
   910      * Check if a list of annotations contains a reference to
   911      * java.lang.Deprecated.
   912      **/
   913     private boolean hasDeprecatedAnnotation(List<JCAnnotation> annotations) {
   914         for (List<JCAnnotation> al = annotations; !al.isEmpty(); al = al.tail) {
   915             JCAnnotation a = al.head;
   916             if (a.annotationType.type == syms.deprecatedType && a.args.isEmpty())
   917                 return true;
   918         }
   919         return false;
   920     }
   922     /** Enter a set of annotations. */
   923     private void actualEnterAnnotations(List<JCAnnotation> annotations,
   924                           Env<AttrContext> env,
   925                           Symbol s) {
   926         Map<TypeSymbol, ListBuffer<Attribute.Compound>> annotated =
   927                 new LinkedHashMap<TypeSymbol, ListBuffer<Attribute.Compound>>();
   928         Map<Attribute.Compound, DiagnosticPosition> pos =
   929                 new HashMap<Attribute.Compound, DiagnosticPosition>();
   931         for (List<JCAnnotation> al = annotations; !al.isEmpty(); al = al.tail) {
   932             JCAnnotation a = al.head;
   933             Attribute.Compound c = annotate.enterAnnotation(a,
   934                                                             syms.annotationType,
   935                                                             env);
   936             if (c == null) {
   937                 continue;
   938             }
   940             if (annotated.containsKey(a.type.tsym)) {
   941                 if (!allowRepeatedAnnos) {
   942                     log.error(a.pos(), "repeatable.annotations.not.supported.in.source");
   943                     allowRepeatedAnnos = true;
   944                 }
   945                 ListBuffer<Attribute.Compound> l = annotated.get(a.type.tsym);
   946                 l = l.append(c);
   947                 annotated.put(a.type.tsym, l);
   948                 pos.put(c, a.pos());
   949             } else {
   950                 annotated.put(a.type.tsym, ListBuffer.of(c));
   951                 pos.put(c, a.pos());
   952             }
   954             // Note: @Deprecated has no effect on local variables and parameters
   955             if (!c.type.isErroneous()
   956                 && s.owner.kind != MTH
   957                 && types.isSameType(c.type, syms.deprecatedType)) {
   958                 s.flags_field |= Flags.DEPRECATED;
   959             }
   960         }
   962         s.setDeclarationAttributesWithCompletion(
   963                 annotate.new AnnotateRepeatedContext<Attribute.Compound>(env, annotated, pos, log, false));
   964     }
   966     /** Queue processing of an attribute default value. */
   967     void annotateDefaultValueLater(final JCExpression defaultValue,
   968                                    final Env<AttrContext> localEnv,
   969                                    final MethodSymbol m) {
   970         annotate.normal(new Annotate.Worker() {
   971                 @Override
   972                 public String toString() {
   973                     return "annotate " + m.owner + "." +
   974                         m + " default " + defaultValue;
   975                 }
   977                 @Override
   978                 public void run() {
   979                     JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile);
   980                     try {
   981                         enterDefaultValue(defaultValue, localEnv, m);
   982                     } finally {
   983                         log.useSource(prev);
   984                     }
   985                 }
   986             });
   987         annotate.validate(new Annotate.Worker() { //validate annotations
   988             @Override
   989             public void run() {
   990                 JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile);
   991                 try {
   992                     // if default value is an annotation, check it is a well-formed
   993                     // annotation value (e.g. no duplicate values, no missing values, etc.)
   994                     chk.validateAnnotationTree(defaultValue);
   995                 } finally {
   996                     log.useSource(prev);
   997                 }
   998             }
   999         });
  1002     /** Enter a default value for an attribute method. */
  1003     private void enterDefaultValue(final JCExpression defaultValue,
  1004                                    final Env<AttrContext> localEnv,
  1005                                    final MethodSymbol m) {
  1006         m.defaultValue = annotate.enterAttributeValue(m.type.getReturnType(),
  1007                                                       defaultValue,
  1008                                                       localEnv);
  1011 /* ********************************************************************
  1012  * Source completer
  1013  *********************************************************************/
  1015     /** Complete entering a class.
  1016      *  @param sym         The symbol of the class to be completed.
  1017      */
  1018     public void complete(Symbol sym) throws CompletionFailure {
  1019         // Suppress some (recursive) MemberEnter invocations
  1020         if (!completionEnabled) {
  1021             // Re-install same completer for next time around and return.
  1022             Assert.check((sym.flags() & Flags.COMPOUND) == 0);
  1023             sym.completer = this;
  1024             return;
  1027         ClassSymbol c = (ClassSymbol)sym;
  1028         ClassType ct = (ClassType)c.type;
  1029         Env<AttrContext> env = typeEnvs.get(c);
  1030         JCClassDecl tree = (JCClassDecl)env.tree;
  1031         boolean wasFirst = isFirst;
  1032         isFirst = false;
  1034         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
  1035         DiagnosticPosition prevLintPos = deferredLintHandler.setPos(tree.pos());
  1036         try {
  1037             // Save class environment for later member enter (2) processing.
  1038             halfcompleted.append(env);
  1040             // Mark class as not yet attributed.
  1041             c.flags_field |= UNATTRIBUTED;
  1043             // If this is a toplevel-class, make sure any preceding import
  1044             // clauses have been seen.
  1045             if (c.owner.kind == PCK) {
  1046                 memberEnter(env.toplevel, env.enclosing(TOPLEVEL));
  1047                 todo.append(env);
  1050             if (c.owner.kind == TYP)
  1051                 c.owner.complete();
  1053             // create an environment for evaluating the base clauses
  1054             Env<AttrContext> baseEnv = baseEnv(tree, env);
  1056             if (tree.extending != null)
  1057                 typeAnnotate(tree.extending, baseEnv, sym, tree.pos());
  1058             for (JCExpression impl : tree.implementing)
  1059                 typeAnnotate(impl, baseEnv, sym, tree.pos());
  1060             annotate.flush();
  1062             // Determine supertype.
  1063             Type supertype =
  1064                 (tree.extending != null)
  1065                 ? attr.attribBase(tree.extending, baseEnv, true, false, true)
  1066                 : ((tree.mods.flags & Flags.ENUM) != 0)
  1067                 ? attr.attribBase(enumBase(tree.pos, c), baseEnv,
  1068                                   true, false, false)
  1069                 : (c.fullname == names.java_lang_Object)
  1070                 ? Type.noType
  1071                 : syms.objectType;
  1072             ct.supertype_field = modelMissingTypes(supertype, tree.extending, false);
  1074             // Determine interfaces.
  1075             ListBuffer<Type> interfaces = new ListBuffer<Type>();
  1076             ListBuffer<Type> all_interfaces = null; // lazy init
  1077             Set<Type> interfaceSet = new HashSet<Type>();
  1078             List<JCExpression> interfaceTrees = tree.implementing;
  1079             for (JCExpression iface : interfaceTrees) {
  1080                 Type i = attr.attribBase(iface, baseEnv, false, true, true);
  1081                 if (i.hasTag(CLASS)) {
  1082                     interfaces.append(i);
  1083                     if (all_interfaces != null) all_interfaces.append(i);
  1084                     chk.checkNotRepeated(iface.pos(), types.erasure(i), interfaceSet);
  1085                 } else {
  1086                     if (all_interfaces == null)
  1087                         all_interfaces = new ListBuffer<Type>().appendList(interfaces);
  1088                     all_interfaces.append(modelMissingTypes(i, iface, true));
  1091             if ((c.flags_field & ANNOTATION) != 0) {
  1092                 ct.interfaces_field = List.of(syms.annotationType);
  1093                 ct.all_interfaces_field = ct.interfaces_field;
  1094             }  else {
  1095                 ct.interfaces_field = interfaces.toList();
  1096                 ct.all_interfaces_field = (all_interfaces == null)
  1097                         ? ct.interfaces_field : all_interfaces.toList();
  1100             if (c.fullname == names.java_lang_Object) {
  1101                 if (tree.extending != null) {
  1102                     chk.checkNonCyclic(tree.extending.pos(),
  1103                                        supertype);
  1104                     ct.supertype_field = Type.noType;
  1106                 else if (tree.implementing.nonEmpty()) {
  1107                     chk.checkNonCyclic(tree.implementing.head.pos(),
  1108                                        ct.interfaces_field.head);
  1109                     ct.interfaces_field = List.nil();
  1113             // Annotations.
  1114             // In general, we cannot fully process annotations yet,  but we
  1115             // can attribute the annotation types and then check to see if the
  1116             // @Deprecated annotation is present.
  1117             attr.attribAnnotationTypes(tree.mods.annotations, baseEnv);
  1118             if (hasDeprecatedAnnotation(tree.mods.annotations))
  1119                 c.flags_field |= DEPRECATED;
  1120             annotateLater(tree.mods.annotations, baseEnv, c, tree.pos());
  1121             // class type parameters use baseEnv but everything uses env
  1123             chk.checkNonCyclicDecl(tree);
  1125             attr.attribTypeVariables(tree.typarams, baseEnv);
  1126             // Do this here, where we have the symbol.
  1127             for (JCTypeParameter tp : tree.typarams)
  1128                 typeAnnotate(tp, baseEnv, sym, tree.pos());
  1130             // Add default constructor if needed.
  1131             if ((c.flags() & INTERFACE) == 0 &&
  1132                 !TreeInfo.hasConstructors(tree.defs)) {
  1133                 List<Type> argtypes = List.nil();
  1134                 List<Type> typarams = List.nil();
  1135                 List<Type> thrown = List.nil();
  1136                 long ctorFlags = 0;
  1137                 boolean based = false;
  1138                 boolean addConstructor = true;
  1139                 JCNewClass nc = null;
  1140                 if (c.name.isEmpty()) {
  1141                     nc = (JCNewClass)env.next.tree;
  1142                     if (nc.constructor != null) {
  1143                         addConstructor = nc.constructor.kind != ERR;
  1144                         Type superConstrType = types.memberType(c.type,
  1145                                                                 nc.constructor);
  1146                         argtypes = superConstrType.getParameterTypes();
  1147                         typarams = superConstrType.getTypeArguments();
  1148                         ctorFlags = nc.constructor.flags() & VARARGS;
  1149                         if (nc.encl != null) {
  1150                             argtypes = argtypes.prepend(nc.encl.type);
  1151                             based = true;
  1153                         thrown = superConstrType.getThrownTypes();
  1156                 if (addConstructor) {
  1157                     MethodSymbol basedConstructor = nc != null ?
  1158                             (MethodSymbol)nc.constructor : null;
  1159                     JCTree constrDef = DefaultConstructor(make.at(tree.pos), c,
  1160                                                         basedConstructor,
  1161                                                         typarams, argtypes, thrown,
  1162                                                         ctorFlags, based);
  1163                     tree.defs = tree.defs.prepend(constrDef);
  1167             // enter symbols for 'this' into current scope.
  1168             VarSymbol thisSym =
  1169                 new VarSymbol(FINAL | HASINIT, names._this, c.type, c);
  1170             thisSym.pos = Position.FIRSTPOS;
  1171             env.info.scope.enter(thisSym);
  1172             // if this is a class, enter symbol for 'super' into current scope.
  1173             if ((c.flags_field & INTERFACE) == 0 &&
  1174                     ct.supertype_field.hasTag(CLASS)) {
  1175                 VarSymbol superSym =
  1176                     new VarSymbol(FINAL | HASINIT, names._super,
  1177                                   ct.supertype_field, c);
  1178                 superSym.pos = Position.FIRSTPOS;
  1179                 env.info.scope.enter(superSym);
  1182             // check that no package exists with same fully qualified name,
  1183             // but admit classes in the unnamed package which have the same
  1184             // name as a top-level package.
  1185             if (checkClash &&
  1186                 c.owner.kind == PCK && c.owner != syms.unnamedPackage &&
  1187                 reader.packageExists(c.fullname)) {
  1188                 log.error(tree.pos, "clash.with.pkg.of.same.name", Kinds.kindName(sym), c);
  1190             if (c.owner.kind == PCK && (c.flags_field & PUBLIC) == 0 &&
  1191                 !env.toplevel.sourcefile.isNameCompatible(c.name.toString(),JavaFileObject.Kind.SOURCE)) {
  1192                 c.flags_field |= AUXILIARY;
  1194         } catch (CompletionFailure ex) {
  1195             chk.completionError(tree.pos(), ex);
  1196         } finally {
  1197             deferredLintHandler.setPos(prevLintPos);
  1198             log.useSource(prev);
  1201         // Enter all member fields and methods of a set of half completed
  1202         // classes in a second phase.
  1203         if (wasFirst) {
  1204             try {
  1205                 while (halfcompleted.nonEmpty()) {
  1206                     Env<AttrContext> toFinish = halfcompleted.next();
  1207                     finish(toFinish);
  1208                     if (allowTypeAnnos) {
  1209                         typeAnnotations.organizeTypeAnnotationsSignatures(toFinish, (JCClassDecl)toFinish.tree);
  1210                         typeAnnotations.validateTypeAnnotationsSignatures(toFinish, (JCClassDecl)toFinish.tree);
  1213             } finally {
  1214                 isFirst = true;
  1219     /*
  1220      * If the symbol is non-null, attach the type annotation to it.
  1221      */
  1222     private void actualEnterTypeAnnotations(final List<JCAnnotation> annotations,
  1223             final Env<AttrContext> env,
  1224             final Symbol s) {
  1225         Map<TypeSymbol, ListBuffer<Attribute.TypeCompound>> annotated =
  1226                 new LinkedHashMap<TypeSymbol, ListBuffer<Attribute.TypeCompound>>();
  1227         Map<Attribute.TypeCompound, DiagnosticPosition> pos =
  1228                 new HashMap<Attribute.TypeCompound, DiagnosticPosition>();
  1230         for (List<JCAnnotation> al = annotations; !al.isEmpty(); al = al.tail) {
  1231             JCAnnotation a = al.head;
  1232             Attribute.TypeCompound tc = annotate.enterTypeAnnotation(a,
  1233                     syms.annotationType,
  1234                     env);
  1235             if (tc == null) {
  1236                 continue;
  1239             if (annotated.containsKey(a.type.tsym)) {
  1240                 if (source.allowRepeatedAnnotations()) {
  1241                     ListBuffer<Attribute.TypeCompound> l = annotated.get(a.type.tsym);
  1242                     l = l.append(tc);
  1243                     annotated.put(a.type.tsym, l);
  1244                     pos.put(tc, a.pos());
  1245                 } else {
  1246                     log.error(a.pos(), "repeatable.annotations.not.supported.in.source");
  1248             } else {
  1249                 annotated.put(a.type.tsym, ListBuffer.of(tc));
  1250                 pos.put(tc, a.pos());
  1254         if (s != null) {
  1255             s.appendTypeAttributesWithCompletion(
  1256                     annotate.new AnnotateRepeatedContext<Attribute.TypeCompound>(env, annotated, pos, log, true));
  1260     public void typeAnnotate(final JCTree tree, final Env<AttrContext> env, final Symbol sym, DiagnosticPosition deferPos) {
  1261         if (allowTypeAnnos) {
  1262             tree.accept(new TypeAnnotate(env, sym, deferPos));
  1266     /**
  1267      * We need to use a TreeScanner, because it is not enough to visit the top-level
  1268      * annotations. We also need to visit type arguments, etc.
  1269      */
  1270     private class TypeAnnotate extends TreeScanner {
  1271         private Env<AttrContext> env;
  1272         private Symbol sym;
  1273         private DiagnosticPosition deferPos;
  1275         public TypeAnnotate(final Env<AttrContext> env, final Symbol sym, DiagnosticPosition deferPos) {
  1276             this.env = env;
  1277             this.sym = sym;
  1278             this.deferPos = deferPos;
  1281         void annotateTypeLater(final List<JCAnnotation> annotations) {
  1282             if (annotations.isEmpty()) {
  1283                 return;
  1286             final DiagnosticPosition deferPos = this.deferPos;
  1288             annotate.normal(new Annotate.Worker() {
  1289                 @Override
  1290                 public String toString() {
  1291                     return "type annotate " + annotations + " onto " + sym + " in " + sym.owner;
  1293                 @Override
  1294                 public void run() {
  1295                     JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
  1296                     DiagnosticPosition prevLintPos = null;
  1298                     if (deferPos != null) {
  1299                         prevLintPos = deferredLintHandler.setPos(deferPos);
  1301                     try {
  1302                         actualEnterTypeAnnotations(annotations, env, sym);
  1303                     } finally {
  1304                         if (prevLintPos != null)
  1305                             deferredLintHandler.setPos(prevLintPos);
  1306                         log.useSource(prev);
  1309             });
  1312         @Override
  1313         public void visitAnnotatedType(final JCAnnotatedType tree) {
  1314             annotateTypeLater(tree.annotations);
  1315             super.visitAnnotatedType(tree);
  1318         @Override
  1319         public void visitTypeParameter(final JCTypeParameter tree) {
  1320             annotateTypeLater(tree.annotations);
  1321             super.visitTypeParameter(tree);
  1324         @Override
  1325         public void visitNewArray(final JCNewArray tree) {
  1326             annotateTypeLater(tree.annotations);
  1327             for (List<JCAnnotation> dimAnnos : tree.dimAnnotations)
  1328                 annotateTypeLater(dimAnnos);
  1329             super.visitNewArray(tree);
  1332         @Override
  1333         public void visitMethodDef(final JCMethodDecl tree) {
  1334             scan(tree.mods);
  1335             scan(tree.restype);
  1336             scan(tree.typarams);
  1337             scan(tree.recvparam);
  1338             scan(tree.params);
  1339             scan(tree.thrown);
  1340             scan(tree.defaultValue);
  1341             // Do not annotate the body, just the signature.
  1342             // scan(tree.body);
  1345         @Override
  1346         public void visitVarDef(final JCVariableDecl tree) {
  1347             DiagnosticPosition prevPos = deferPos;
  1348             deferPos = tree.pos();
  1349             try {
  1350                 if (sym != null && sym.kind == Kinds.VAR) {
  1351                     // Don't visit a parameter once when the sym is the method
  1352                     // and once when the sym is the parameter.
  1353                     scan(tree.mods);
  1354                     scan(tree.vartype);
  1356                 scan(tree.init);
  1357             } finally {
  1358                 deferPos = prevPos;
  1362         @Override
  1363         public void visitClassDef(JCClassDecl tree) {
  1364             // We can only hit a classdef if it is declared within
  1365             // a method. Ignore it - the class will be visited
  1366             // separately later.
  1369         @Override
  1370         public void visitNewClass(JCNewClass tree) {
  1371             if (tree.def == null) {
  1372                 // For an anonymous class instantiation the class
  1373                 // will be visited separately.
  1374                 super.visitNewClass(tree);
  1380     private Env<AttrContext> baseEnv(JCClassDecl tree, Env<AttrContext> env) {
  1381         Scope baseScope = new Scope(tree.sym);
  1382         //import already entered local classes into base scope
  1383         for (Scope.Entry e = env.outer.info.scope.elems ; e != null ; e = e.sibling) {
  1384             if (e.sym.isLocal()) {
  1385                 baseScope.enter(e.sym);
  1388         //import current type-parameters into base scope
  1389         if (tree.typarams != null)
  1390             for (List<JCTypeParameter> typarams = tree.typarams;
  1391                  typarams.nonEmpty();
  1392                  typarams = typarams.tail)
  1393                 baseScope.enter(typarams.head.type.tsym);
  1394         Env<AttrContext> outer = env.outer; // the base clause can't see members of this class
  1395         Env<AttrContext> localEnv = outer.dup(tree, outer.info.dup(baseScope));
  1396         localEnv.baseClause = true;
  1397         localEnv.outer = outer;
  1398         localEnv.info.isSelfCall = false;
  1399         return localEnv;
  1402     /** Enter member fields and methods of a class
  1403      *  @param env        the environment current for the class block.
  1404      */
  1405     private void finish(Env<AttrContext> env) {
  1406         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
  1407         try {
  1408             JCClassDecl tree = (JCClassDecl)env.tree;
  1409             finishClass(tree, env);
  1410         } finally {
  1411             log.useSource(prev);
  1415     /** Generate a base clause for an enum type.
  1416      *  @param pos              The position for trees and diagnostics, if any
  1417      *  @param c                The class symbol of the enum
  1418      */
  1419     private JCExpression enumBase(int pos, ClassSymbol c) {
  1420         JCExpression result = make.at(pos).
  1421             TypeApply(make.QualIdent(syms.enumSym),
  1422                       List.<JCExpression>of(make.Type(c.type)));
  1423         return result;
  1426     Type modelMissingTypes(Type t, final JCExpression tree, final boolean interfaceExpected) {
  1427         if (!t.hasTag(ERROR))
  1428             return t;
  1430         return new ErrorType(t.getOriginalType(), t.tsym) {
  1431             private Type modelType;
  1433             @Override
  1434             public Type getModelType() {
  1435                 if (modelType == null)
  1436                     modelType = new Synthesizer(getOriginalType(), interfaceExpected).visit(tree);
  1437                 return modelType;
  1439         };
  1441     // where
  1442     private class Synthesizer extends JCTree.Visitor {
  1443         Type originalType;
  1444         boolean interfaceExpected;
  1445         List<ClassSymbol> synthesizedSymbols = List.nil();
  1446         Type result;
  1448         Synthesizer(Type originalType, boolean interfaceExpected) {
  1449             this.originalType = originalType;
  1450             this.interfaceExpected = interfaceExpected;
  1453         Type visit(JCTree tree) {
  1454             tree.accept(this);
  1455             return result;
  1458         List<Type> visit(List<? extends JCTree> trees) {
  1459             ListBuffer<Type> lb = new ListBuffer<Type>();
  1460             for (JCTree t: trees)
  1461                 lb.append(visit(t));
  1462             return lb.toList();
  1465         @Override
  1466         public void visitTree(JCTree tree) {
  1467             result = syms.errType;
  1470         @Override
  1471         public void visitIdent(JCIdent tree) {
  1472             if (!tree.type.hasTag(ERROR)) {
  1473                 result = tree.type;
  1474             } else {
  1475                 result = synthesizeClass(tree.name, syms.unnamedPackage).type;
  1479         @Override
  1480         public void visitSelect(JCFieldAccess tree) {
  1481             if (!tree.type.hasTag(ERROR)) {
  1482                 result = tree.type;
  1483             } else {
  1484                 Type selectedType;
  1485                 boolean prev = interfaceExpected;
  1486                 try {
  1487                     interfaceExpected = false;
  1488                     selectedType = visit(tree.selected);
  1489                 } finally {
  1490                     interfaceExpected = prev;
  1492                 ClassSymbol c = synthesizeClass(tree.name, selectedType.tsym);
  1493                 result = c.type;
  1497         @Override
  1498         public void visitTypeApply(JCTypeApply tree) {
  1499             if (!tree.type.hasTag(ERROR)) {
  1500                 result = tree.type;
  1501             } else {
  1502                 ClassType clazzType = (ClassType) visit(tree.clazz);
  1503                 if (synthesizedSymbols.contains(clazzType.tsym))
  1504                     synthesizeTyparams((ClassSymbol) clazzType.tsym, tree.arguments.size());
  1505                 final List<Type> actuals = visit(tree.arguments);
  1506                 result = new ErrorType(tree.type, clazzType.tsym) {
  1507                     @Override
  1508                     public List<Type> getTypeArguments() {
  1509                         return actuals;
  1511                 };
  1515         ClassSymbol synthesizeClass(Name name, Symbol owner) {
  1516             int flags = interfaceExpected ? INTERFACE : 0;
  1517             ClassSymbol c = new ClassSymbol(flags, name, owner);
  1518             c.members_field = new Scope.ErrorScope(c);
  1519             c.type = new ErrorType(originalType, c) {
  1520                 @Override
  1521                 public List<Type> getTypeArguments() {
  1522                     return typarams_field;
  1524             };
  1525             synthesizedSymbols = synthesizedSymbols.prepend(c);
  1526             return c;
  1529         void synthesizeTyparams(ClassSymbol sym, int n) {
  1530             ClassType ct = (ClassType) sym.type;
  1531             Assert.check(ct.typarams_field.isEmpty());
  1532             if (n == 1) {
  1533                 TypeVar v = new TypeVar(names.fromString("T"), sym, syms.botType);
  1534                 ct.typarams_field = ct.typarams_field.prepend(v);
  1535             } else {
  1536                 for (int i = n; i > 0; i--) {
  1537                     TypeVar v = new TypeVar(names.fromString("T" + i), sym, syms.botType);
  1538                     ct.typarams_field = ct.typarams_field.prepend(v);
  1545 /* ***************************************************************************
  1546  * tree building
  1547  ****************************************************************************/
  1549     /** Generate default constructor for given class. For classes different
  1550      *  from java.lang.Object, this is:
  1552      *    c(argtype_0 x_0, ..., argtype_n x_n) throws thrown {
  1553      *      super(x_0, ..., x_n)
  1554      *    }
  1556      *  or, if based == true:
  1558      *    c(argtype_0 x_0, ..., argtype_n x_n) throws thrown {
  1559      *      x_0.super(x_1, ..., x_n)
  1560      *    }
  1562      *  @param make     The tree factory.
  1563      *  @param c        The class owning the default constructor.
  1564      *  @param argtypes The parameter types of the constructor.
  1565      *  @param thrown   The thrown exceptions of the constructor.
  1566      *  @param based    Is first parameter a this$n?
  1567      */
  1568     JCTree DefaultConstructor(TreeMaker make,
  1569                             ClassSymbol c,
  1570                             MethodSymbol baseInit,
  1571                             List<Type> typarams,
  1572                             List<Type> argtypes,
  1573                             List<Type> thrown,
  1574                             long flags,
  1575                             boolean based) {
  1576         JCTree result;
  1577         if ((c.flags() & ENUM) != 0 &&
  1578             (types.supertype(c.type).tsym == syms.enumSym)) {
  1579             // constructors of true enums are private
  1580             flags = (flags & ~AccessFlags) | PRIVATE | GENERATEDCONSTR;
  1581         } else
  1582             flags |= (c.flags() & AccessFlags) | GENERATEDCONSTR;
  1583         if (c.name.isEmpty()) {
  1584             flags |= ANONCONSTR;
  1586         Type mType = new MethodType(argtypes, null, thrown, c);
  1587         Type initType = typarams.nonEmpty() ?
  1588                 new ForAll(typarams, mType) :
  1589                 mType;
  1590         MethodSymbol init = new MethodSymbol(flags, names.init,
  1591                 initType, c);
  1592         init.params = createDefaultConstructorParams(make, baseInit, init,
  1593                 argtypes, based);
  1594         List<JCVariableDecl> params = make.Params(argtypes, init);
  1595         List<JCStatement> stats = List.nil();
  1596         if (c.type != syms.objectType) {
  1597             stats = stats.prepend(SuperCall(make, typarams, params, based));
  1599         result = make.MethodDef(init, make.Block(0, stats));
  1600         return result;
  1603     private List<VarSymbol> createDefaultConstructorParams(
  1604             TreeMaker make,
  1605             MethodSymbol baseInit,
  1606             MethodSymbol init,
  1607             List<Type> argtypes,
  1608             boolean based) {
  1609         List<VarSymbol> initParams = null;
  1610         List<Type> argTypesList = argtypes;
  1611         if (based) {
  1612             /*  In this case argtypes will have an extra type, compared to baseInit,
  1613              *  corresponding to the type of the enclosing instance i.e.:
  1615              *  Inner i = outer.new Inner(1){}
  1617              *  in the above example argtypes will be (Outer, int) and baseInit
  1618              *  will have parameter's types (int). So in this case we have to add
  1619              *  first the extra type in argtypes and then get the names of the
  1620              *  parameters from baseInit.
  1621              */
  1622             initParams = List.nil();
  1623             VarSymbol param = new VarSymbol(PARAMETER, make.paramName(0), argtypes.head, init);
  1624             initParams = initParams.append(param);
  1625             argTypesList = argTypesList.tail;
  1627         if (baseInit != null && baseInit.params != null &&
  1628             baseInit.params.nonEmpty() && argTypesList.nonEmpty()) {
  1629             initParams = (initParams == null) ? List.<VarSymbol>nil() : initParams;
  1630             List<VarSymbol> baseInitParams = baseInit.params;
  1631             while (baseInitParams.nonEmpty() && argTypesList.nonEmpty()) {
  1632                 VarSymbol param = new VarSymbol(baseInitParams.head.flags() | PARAMETER,
  1633                         baseInitParams.head.name, argTypesList.head, init);
  1634                 initParams = initParams.append(param);
  1635                 baseInitParams = baseInitParams.tail;
  1636                 argTypesList = argTypesList.tail;
  1639         return initParams;
  1642     /** Generate call to superclass constructor. This is:
  1644      *    super(id_0, ..., id_n)
  1646      * or, if based == true
  1648      *    id_0.super(id_1,...,id_n)
  1650      *  where id_0, ..., id_n are the names of the given parameters.
  1652      *  @param make    The tree factory
  1653      *  @param params  The parameters that need to be passed to super
  1654      *  @param typarams  The type parameters that need to be passed to super
  1655      *  @param based   Is first parameter a this$n?
  1656      */
  1657     JCExpressionStatement SuperCall(TreeMaker make,
  1658                    List<Type> typarams,
  1659                    List<JCVariableDecl> params,
  1660                    boolean based) {
  1661         JCExpression meth;
  1662         if (based) {
  1663             meth = make.Select(make.Ident(params.head), names._super);
  1664             params = params.tail;
  1665         } else {
  1666             meth = make.Ident(names._super);
  1668         List<JCExpression> typeargs = typarams.nonEmpty() ? make.Types(typarams) : null;
  1669         return make.Exec(make.Apply(typeargs, meth, make.Idents(params)));

mercurial