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

Wed, 23 Oct 2013 23:20:32 -0400

author
emc
date
Wed, 23 Oct 2013 23:20:32 -0400
changeset 2167
d2fa3f7e964e
parent 2133
19e8eebfbe52
child 2424
7e97c65c373c
permissions
-rw-r--r--

8006732: support correct bytecode storage of type annotations in multicatch
Summary: Fix issue with annotations being added before attribution, which causes multicatch not to work right and several tests to fail.
Reviewed-by: jfranck, jjg

     1 /*
     2  * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.  Oracle designates this
     8  * particular file as subject to the "Classpath" exception as provided
     9  * by Oracle in the LICENSE file that accompanied this code.
    10  *
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    14  * version 2 for more details (a copy is included in the LICENSE file that
    15  * accompanied this code).
    16  *
    17  * You should have received a copy of the GNU General Public License version
    18  * 2 along with this work; if not, write to the Free Software Foundation,
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    20  *
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    22  * or visit www.oracle.com if you need additional information or have any
    23  * questions.
    24  */
    26 package com.sun.tools.javac.comp;
    28 import java.util.HashMap;
    29 import java.util.HashSet;
    30 import java.util.LinkedHashMap;
    31 import java.util.Map;
    32 import java.util.Set;
    34 import javax.tools.JavaFileObject;
    36 import com.sun.tools.javac.code.*;
    37 import com.sun.tools.javac.jvm.*;
    38 import com.sun.tools.javac.tree.*;
    39 import com.sun.tools.javac.util.*;
    41 import com.sun.tools.javac.code.Type.*;
    42 import com.sun.tools.javac.code.Symbol.*;
    43 import com.sun.tools.javac.tree.JCTree.*;
    45 import static com.sun.tools.javac.code.Flags.*;
    46 import static com.sun.tools.javac.code.Flags.ANNOTATION;
    47 import static com.sun.tools.javac.code.Kinds.*;
    48 import static com.sun.tools.javac.code.TypeTag.CLASS;
    49 import static com.sun.tools.javac.code.TypeTag.ERROR;
    50 import static com.sun.tools.javac.code.TypeTag.TYPEVAR;
    51 import static com.sun.tools.javac.tree.JCTree.Tag.*;
    52 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
    53 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    55 /** This is the second phase of Enter, in which classes are completed
    56  *  by entering their members into the class scope using
    57  *  MemberEnter.complete().  See Enter for an overview.
    58  *
    59  *  <p><b>This is NOT part of any supported API.
    60  *  If you write code that depends on this, you do so at your own risk.
    61  *  This code and its internal interfaces are subject to change or
    62  *  deletion without notice.</b>
    63  */
    64 public class MemberEnter extends JCTree.Visitor implements Completer {
    65     protected static final Context.Key<MemberEnter> memberEnterKey =
    66         new Context.Key<MemberEnter>();
    68     /** A switch to determine whether we check for package/class conflicts
    69      */
    70     final static boolean checkClash = true;
    72     private final Names names;
    73     private final Enter enter;
    74     private final Log log;
    75     private final Check chk;
    76     private final Attr attr;
    77     private final Symtab syms;
    78     private final TreeMaker make;
    79     private final ClassReader reader;
    80     private final Todo todo;
    81     private final Annotate annotate;
    82     private final 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;
    90     public static MemberEnter instance(Context context) {
    91         MemberEnter instance = context.get(memberEnterKey);
    92         if (instance == null)
    93             instance = new MemberEnter(context);
    94         return instance;
    95     }
    97     protected MemberEnter(Context context) {
    98         context.put(memberEnterKey, this);
    99         names = Names.instance(context);
   100         enter = Enter.instance(context);
   101         log = Log.instance(context);
   102         chk = Check.instance(context);
   103         attr = Attr.instance(context);
   104         syms = Symtab.instance(context);
   105         make = TreeMaker.instance(context);
   106         reader = ClassReader.instance(context);
   107         todo = Todo.instance(context);
   108         annotate = Annotate.instance(context);
   109         typeAnnotations = TypeAnnotations.instance(context);
   110         types = Types.instance(context);
   111         diags = JCDiagnostic.Factory.instance(context);
   112         source = Source.instance(context);
   113         target = Target.instance(context);
   114         deferredLintHandler = DeferredLintHandler.instance(context);
   115         lint = Lint.instance(context);
   116         allowTypeAnnos = source.allowTypeAnnotations();
   117         allowRepeatedAnnos = source.allowRepeatedAnnotations();
   118     }
   120     /** Switch: support type annotations.
   121      */
   122     boolean allowTypeAnnos;
   124     boolean allowRepeatedAnnos;
   126     /** A queue for classes whose members still need to be entered into the
   127      *  symbol table.
   128      */
   129     ListBuffer<Env<AttrContext>> halfcompleted = new ListBuffer<Env<AttrContext>>();
   131     /** Set to true only when the first of a set of classes is
   132      *  processed from the half completed queue.
   133      */
   134     boolean isFirst = true;
   136     /** A flag to disable completion from time to time during member
   137      *  enter, as we only need to look up types.  This avoids
   138      *  unnecessarily deep recursion.
   139      */
   140     boolean completionEnabled = true;
   142     /* ---------- Processing import clauses ----------------
   143      */
   145     /** Import all classes of a class or package on demand.
   146      *  @param pos           Position to be used for error reporting.
   147      *  @param tsym          The class or package the members of which are imported.
   148      *  @param env           The env in which the imported classes will be entered.
   149      */
   150     private void importAll(int pos,
   151                            final TypeSymbol tsym,
   152                            Env<AttrContext> env) {
   153         // Check that packages imported from exist (JLS ???).
   154         if (tsym.kind == PCK && tsym.members().elems == null && !tsym.exists()) {
   155             // If we can't find java.lang, exit immediately.
   156             if (((PackageSymbol)tsym).fullname.equals(names.java_lang)) {
   157                 JCDiagnostic msg = diags.fragment("fatal.err.no.java.lang");
   158                 throw new FatalError(msg);
   159             } else {
   160                 log.error(DiagnosticFlag.RESOLVE_ERROR, pos, "doesnt.exist", tsym);
   161             }
   162         }
   163         env.toplevel.starImportScope.importAll(tsym.members());
   164     }
   166     /** Import all static members of a class or package on demand.
   167      *  @param pos           Position to be used for error reporting.
   168      *  @param tsym          The class or package the members of which are imported.
   169      *  @param env           The env in which the imported classes will be entered.
   170      */
   171     private void importStaticAll(int pos,
   172                                  final TypeSymbol tsym,
   173                                  Env<AttrContext> env) {
   174         final JavaFileObject sourcefile = env.toplevel.sourcefile;
   175         final Scope toScope = env.toplevel.starImportScope;
   176         final PackageSymbol packge = env.toplevel.packge;
   177         final TypeSymbol origin = tsym;
   179         // enter imported types immediately
   180         new Object() {
   181             Set<Symbol> processed = new HashSet<Symbol>();
   182             void importFrom(TypeSymbol tsym) {
   183                 if (tsym == null || !processed.add(tsym))
   184                     return;
   186                 // also import inherited names
   187                 importFrom(types.supertype(tsym.type).tsym);
   188                 for (Type t : types.interfaces(tsym.type))
   189                     importFrom(t.tsym);
   191                 final Scope fromScope = tsym.members();
   192                 for (Scope.Entry e = fromScope.elems; e != null; e = e.sibling) {
   193                     Symbol sym = e.sym;
   194                     if (sym.kind == TYP &&
   195                         (sym.flags() & STATIC) != 0 &&
   196                         staticImportAccessible(sym, packge) &&
   197                         sym.isMemberOf(origin, types) &&
   198                         !toScope.includes(sym))
   199                         toScope.enter(sym, fromScope, origin.members(), true);
   200                 }
   201             }
   202         }.importFrom(tsym);
   204         // enter non-types before annotations that might use them
   205         annotate.earlier(new Annotate.Worker() {
   206             Set<Symbol> processed = new HashSet<Symbol>();
   208             public String toString() {
   209                 return "import static " + tsym + ".*" + " in " + sourcefile;
   210             }
   211             void importFrom(TypeSymbol tsym) {
   212                 if (tsym == null || !processed.add(tsym))
   213                     return;
   215                 // also import inherited names
   216                 importFrom(types.supertype(tsym.type).tsym);
   217                 for (Type t : types.interfaces(tsym.type))
   218                     importFrom(t.tsym);
   220                 final Scope fromScope = tsym.members();
   221                 for (Scope.Entry e = fromScope.elems; e != null; e = e.sibling) {
   222                     Symbol sym = e.sym;
   223                     if (sym.isStatic() && sym.kind != TYP &&
   224                         staticImportAccessible(sym, packge) &&
   225                         !toScope.includes(sym) &&
   226                         sym.isMemberOf(origin, types)) {
   227                         toScope.enter(sym, fromScope, origin.members(), true);
   228                     }
   229                 }
   230             }
   231             public void run() {
   232                 importFrom(tsym);
   233             }
   234         });
   235     }
   237     // is the sym accessible everywhere in packge?
   238     boolean staticImportAccessible(Symbol sym, PackageSymbol packge) {
   239         int flags = (int)(sym.flags() & AccessFlags);
   240         switch (flags) {
   241         default:
   242         case PUBLIC:
   243             return true;
   244         case PRIVATE:
   245             return false;
   246         case 0:
   247         case PROTECTED:
   248             return sym.packge() == packge;
   249         }
   250     }
   252     /** Import statics types of a given name.  Non-types are handled in Attr.
   253      *  @param pos           Position to be used for error reporting.
   254      *  @param tsym          The class from which the name is imported.
   255      *  @param name          The (simple) name being imported.
   256      *  @param env           The environment containing the named import
   257      *                  scope to add to.
   258      */
   259     private void importNamedStatic(final DiagnosticPosition pos,
   260                                    final TypeSymbol tsym,
   261                                    final Name name,
   262                                    final Env<AttrContext> env) {
   263         if (tsym.kind != TYP) {
   264             log.error(DiagnosticFlag.RECOVERABLE, pos, "static.imp.only.classes.and.interfaces");
   265             return;
   266         }
   268         final Scope toScope = env.toplevel.namedImportScope;
   269         final PackageSymbol packge = env.toplevel.packge;
   270         final TypeSymbol origin = tsym;
   272         // enter imported types immediately
   273         new Object() {
   274             Set<Symbol> processed = new HashSet<Symbol>();
   275             void importFrom(TypeSymbol tsym) {
   276                 if (tsym == null || !processed.add(tsym))
   277                     return;
   279                 // also import inherited names
   280                 importFrom(types.supertype(tsym.type).tsym);
   281                 for (Type t : types.interfaces(tsym.type))
   282                     importFrom(t.tsym);
   284                 for (Scope.Entry e = tsym.members().lookup(name);
   285                      e.scope != null;
   286                      e = e.next()) {
   287                     Symbol sym = e.sym;
   288                     if (sym.isStatic() &&
   289                         sym.kind == TYP &&
   290                         staticImportAccessible(sym, packge) &&
   291                         sym.isMemberOf(origin, types) &&
   292                         chk.checkUniqueStaticImport(pos, sym, toScope))
   293                         toScope.enter(sym, sym.owner.members(), origin.members(), true);
   294                 }
   295             }
   296         }.importFrom(tsym);
   298         // enter non-types before annotations that might use them
   299         annotate.earlier(new Annotate.Worker() {
   300             Set<Symbol> processed = new HashSet<Symbol>();
   301             boolean found = false;
   303             public String toString() {
   304                 return "import static " + tsym + "." + name;
   305             }
   306             void importFrom(TypeSymbol tsym) {
   307                 if (tsym == null || !processed.add(tsym))
   308                     return;
   310                 // also import inherited names
   311                 importFrom(types.supertype(tsym.type).tsym);
   312                 for (Type t : types.interfaces(tsym.type))
   313                     importFrom(t.tsym);
   315                 for (Scope.Entry e = tsym.members().lookup(name);
   316                      e.scope != null;
   317                      e = e.next()) {
   318                     Symbol sym = e.sym;
   319                     if (sym.isStatic() &&
   320                         staticImportAccessible(sym, packge) &&
   321                         sym.isMemberOf(origin, types)) {
   322                         found = true;
   323                         if (sym.kind != TYP) {
   324                             toScope.enter(sym, sym.owner.members(), origin.members(), true);
   325                         }
   326                     }
   327                 }
   328             }
   329             public void run() {
   330                 JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   331                 try {
   332                     importFrom(tsym);
   333                     if (!found) {
   334                         log.error(pos, "cant.resolve.location",
   335                                   KindName.STATIC,
   336                                   name, List.<Type>nil(), List.<Type>nil(),
   337                                   Kinds.typeKindName(tsym.type),
   338                                   tsym.type);
   339                     }
   340                 } finally {
   341                     log.useSource(prev);
   342                 }
   343             }
   344         });
   345     }
   346     /** Import given class.
   347      *  @param pos           Position to be used for error reporting.
   348      *  @param tsym          The class to be imported.
   349      *  @param env           The environment containing the named import
   350      *                  scope to add to.
   351      */
   352     private void importNamed(DiagnosticPosition pos, Symbol tsym, Env<AttrContext> env) {
   353         if (tsym.kind == TYP &&
   354             chk.checkUniqueImport(pos, tsym, env.toplevel.namedImportScope))
   355             env.toplevel.namedImportScope.enter(tsym, tsym.owner.members());
   356     }
   358     /** Construct method type from method signature.
   359      *  @param typarams    The method's type parameters.
   360      *  @param params      The method's value parameters.
   361      *  @param res             The method's result type,
   362      *                 null if it is a constructor.
   363      *  @param recvparam       The method's receiver parameter,
   364      *                 null if none given; TODO: or already set here?
   365      *  @param thrown      The method's thrown exceptions.
   366      *  @param env             The method's (local) environment.
   367      */
   368     Type signature(MethodSymbol msym,
   369                    List<JCTypeParameter> typarams,
   370                    List<JCVariableDecl> params,
   371                    JCTree res,
   372                    JCVariableDecl recvparam,
   373                    List<JCExpression> thrown,
   374                    Env<AttrContext> env) {
   376         // Enter and attribute type parameters.
   377         List<Type> tvars = enter.classEnter(typarams, env);
   378         attr.attribTypeVariables(typarams, env);
   380         // Enter and attribute value parameters.
   381         ListBuffer<Type> argbuf = new ListBuffer<Type>();
   382         for (List<JCVariableDecl> l = params; l.nonEmpty(); l = l.tail) {
   383             memberEnter(l.head, env);
   384             argbuf.append(l.head.vartype.type);
   385         }
   387         // Attribute result type, if one is given.
   388         Type restype = res == null ? syms.voidType : attr.attribType(res, env);
   390         // Attribute receiver type, if one is given.
   391         Type recvtype;
   392         if (recvparam!=null) {
   393             memberEnter(recvparam, env);
   394             recvtype = recvparam.vartype.type;
   395         } else {
   396             recvtype = null;
   397         }
   399         // Attribute thrown exceptions.
   400         ListBuffer<Type> thrownbuf = new ListBuffer<Type>();
   401         for (List<JCExpression> l = thrown; l.nonEmpty(); l = l.tail) {
   402             Type exc = attr.attribType(l.head, env);
   403             if (!exc.hasTag(TYPEVAR)) {
   404                 exc = chk.checkClassType(l.head.pos(), exc);
   405             } else if (exc.tsym.owner == msym) {
   406                 //mark inference variables in 'throws' clause
   407                 exc.tsym.flags_field |= THROWS;
   408             }
   409             thrownbuf.append(exc);
   410         }
   411         MethodType mtype = new MethodType(argbuf.toList(),
   412                                     restype,
   413                                     thrownbuf.toList(),
   414                                     syms.methodClass);
   415         mtype.recvtype = recvtype;
   417         return tvars.isEmpty() ? mtype : new ForAll(tvars, mtype);
   418     }
   420 /* ********************************************************************
   421  * Visitor methods for member enter
   422  *********************************************************************/
   424     /** Visitor argument: the current environment
   425      */
   426     protected Env<AttrContext> env;
   428     /** Enter field and method definitions and process import
   429      *  clauses, catching any completion failure exceptions.
   430      */
   431     protected void memberEnter(JCTree tree, Env<AttrContext> env) {
   432         Env<AttrContext> prevEnv = this.env;
   433         try {
   434             this.env = env;
   435             tree.accept(this);
   436         }  catch (CompletionFailure ex) {
   437             chk.completionError(tree.pos(), ex);
   438         } finally {
   439             this.env = prevEnv;
   440         }
   441     }
   443     /** Enter members from a list of trees.
   444      */
   445     void memberEnter(List<? extends JCTree> trees, Env<AttrContext> env) {
   446         for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
   447             memberEnter(l.head, env);
   448     }
   450     /** Enter members for a class.
   451      */
   452     void finishClass(JCClassDecl tree, Env<AttrContext> env) {
   453         if ((tree.mods.flags & Flags.ENUM) != 0 &&
   454             (types.supertype(tree.sym.type).tsym.flags() & Flags.ENUM) == 0) {
   455             addEnumMembers(tree, env);
   456         }
   457         memberEnter(tree.defs, env);
   458     }
   460     /** Add the implicit members for an enum type
   461      *  to the symbol table.
   462      */
   463     private void addEnumMembers(JCClassDecl tree, Env<AttrContext> env) {
   464         JCExpression valuesType = make.Type(new ArrayType(tree.sym.type, syms.arrayClass));
   466         // public static T[] values() { return ???; }
   467         JCMethodDecl values = make.
   468             MethodDef(make.Modifiers(Flags.PUBLIC|Flags.STATIC),
   469                       names.values,
   470                       valuesType,
   471                       List.<JCTypeParameter>nil(),
   472                       List.<JCVariableDecl>nil(),
   473                       List.<JCExpression>nil(), // thrown
   474                       null, //make.Block(0, Tree.emptyList.prepend(make.Return(make.Ident(names._null)))),
   475                       null);
   476         memberEnter(values, env);
   478         // public static T valueOf(String name) { return ???; }
   479         JCMethodDecl valueOf = make.
   480             MethodDef(make.Modifiers(Flags.PUBLIC|Flags.STATIC),
   481                       names.valueOf,
   482                       make.Type(tree.sym.type),
   483                       List.<JCTypeParameter>nil(),
   484                       List.of(make.VarDef(make.Modifiers(Flags.PARAMETER |
   485                                                          Flags.MANDATED),
   486                                             names.fromString("name"),
   487                                             make.Type(syms.stringType), null)),
   488                       List.<JCExpression>nil(), // thrown
   489                       null, //make.Block(0, Tree.emptyList.prepend(make.Return(make.Ident(names._null)))),
   490                       null);
   491         memberEnter(valueOf, env);
   492     }
   494     public void visitTopLevel(JCCompilationUnit tree) {
   495         if (tree.starImportScope.elems != null) {
   496             // we must have already processed this toplevel
   497             return;
   498         }
   500         // check that no class exists with same fully qualified name as
   501         // toplevel package
   502         if (checkClash && tree.pid != null) {
   503             Symbol p = tree.packge;
   504             while (p.owner != syms.rootPackage) {
   505                 p.owner.complete(); // enter all class members of p
   506                 if (syms.classes.get(p.getQualifiedName()) != null) {
   507                     log.error(tree.pos,
   508                               "pkg.clashes.with.class.of.same.name",
   509                               p);
   510                 }
   511                 p = p.owner;
   512             }
   513         }
   515         // process package annotations
   516         annotateLater(tree.packageAnnotations, env, tree.packge, null);
   518         DiagnosticPosition prevLintPos = deferredLintHandler.immediate();
   519         Lint prevLint = chk.setLint(lint);
   521         try {
   522             // Import-on-demand java.lang.
   523             importAll(tree.pos, reader.enterPackage(names.java_lang), env);
   525             // Process all import clauses.
   526             memberEnter(tree.defs, env);
   527         } finally {
   528             chk.setLint(prevLint);
   529             deferredLintHandler.setPos(prevLintPos);
   530         }
   531     }
   533     // process the non-static imports and the static imports of types.
   534     public void visitImport(JCImport tree) {
   535         JCFieldAccess imp = (JCFieldAccess)tree.qualid;
   536         Name name = TreeInfo.name(imp);
   538         // Create a local environment pointing to this tree to disable
   539         // effects of other imports in Resolve.findGlobalType
   540         Env<AttrContext> localEnv = env.dup(tree);
   542         TypeSymbol p = attr.attribImportQualifier(tree, localEnv).tsym;
   543         if (name == names.asterisk) {
   544             // Import on demand.
   545             chk.checkCanonical(imp.selected);
   546             if (tree.staticImport)
   547                 importStaticAll(tree.pos, p, env);
   548             else
   549                 importAll(tree.pos, p, env);
   550         } else {
   551             // Named type import.
   552             if (tree.staticImport) {
   553                 importNamedStatic(tree.pos(), p, name, localEnv);
   554                 chk.checkCanonical(imp.selected);
   555             } else {
   556                 TypeSymbol c = attribImportType(imp, localEnv).tsym;
   557                 chk.checkCanonical(imp);
   558                 importNamed(tree.pos(), c, env);
   559             }
   560         }
   561     }
   563     public void visitMethodDef(JCMethodDecl tree) {
   564         Scope enclScope = enter.enterScope(env);
   565         MethodSymbol m = new MethodSymbol(0, tree.name, null, enclScope.owner);
   566         m.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, m, tree);
   567         tree.sym = m;
   569         //if this is a default method, add the DEFAULT flag to the enclosing interface
   570         if ((tree.mods.flags & DEFAULT) != 0) {
   571             m.enclClass().flags_field |= DEFAULT;
   572         }
   574         Env<AttrContext> localEnv = methodEnv(tree, env);
   576         annotate.enterStart();
   577         try {
   578             DiagnosticPosition prevLintPos = deferredLintHandler.setPos(tree.pos());
   579             try {
   580                 // Compute the method type
   581                 m.type = signature(m, tree.typarams, tree.params,
   582                                    tree.restype, tree.recvparam,
   583                                    tree.thrown,
   584                                    localEnv);
   585             } finally {
   586                 deferredLintHandler.setPos(prevLintPos);
   587             }
   589             if (types.isSignaturePolymorphic(m)) {
   590                 m.flags_field |= SIGNATURE_POLYMORPHIC;
   591             }
   593             // Set m.params
   594             ListBuffer<VarSymbol> params = new ListBuffer<VarSymbol>();
   595             JCVariableDecl lastParam = null;
   596             for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
   597                 JCVariableDecl param = lastParam = l.head;
   598                 params.append(Assert.checkNonNull(param.sym));
   599             }
   600             m.params = params.toList();
   602             // mark the method varargs, if necessary
   603             if (lastParam != null && (lastParam.mods.flags & Flags.VARARGS) != 0)
   604                 m.flags_field |= Flags.VARARGS;
   606             localEnv.info.scope.leave();
   607             if (chk.checkUnique(tree.pos(), m, enclScope)) {
   608             enclScope.enter(m);
   609             }
   611             annotateLater(tree.mods.annotations, localEnv, m, tree.pos());
   612             // Visit the signature of the method. Note that
   613             // TypeAnnotate doesn't descend into the body.
   614             typeAnnotate(tree, localEnv, m, tree.pos());
   616             if (tree.defaultValue != null)
   617                 annotateDefaultValueLater(tree.defaultValue, localEnv, m);
   618         } finally {
   619             annotate.enterDone();
   620         }
   621     }
   623     /** Create a fresh environment for method bodies.
   624      *  @param tree     The method definition.
   625      *  @param env      The environment current outside of the method definition.
   626      */
   627     Env<AttrContext> methodEnv(JCMethodDecl tree, Env<AttrContext> env) {
   628         Env<AttrContext> localEnv =
   629             env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
   630         localEnv.enclMethod = tree;
   631         localEnv.info.scope.owner = tree.sym;
   632         if (tree.sym.type != null) {
   633             //when this is called in the enter stage, there's no type to be set
   634             localEnv.info.returnResult = attr.new ResultInfo(VAL, tree.sym.type.getReturnType());
   635         }
   636         if ((tree.mods.flags & STATIC) != 0) localEnv.info.staticLevel++;
   637         return localEnv;
   638     }
   640     public void visitVarDef(JCVariableDecl tree) {
   641         Env<AttrContext> localEnv = env;
   642         if ((tree.mods.flags & STATIC) != 0 ||
   643             (env.info.scope.owner.flags() & INTERFACE) != 0) {
   644             localEnv = env.dup(tree, env.info.dup());
   645             localEnv.info.staticLevel++;
   646         }
   647         DiagnosticPosition prevLintPos = deferredLintHandler.setPos(tree.pos());
   648         annotate.enterStart();
   649         try {
   650             try {
   651                 if (TreeInfo.isEnumInit(tree)) {
   652                     attr.attribIdentAsEnumType(localEnv, (JCIdent)tree.vartype);
   653                 } else {
   654                     attr.attribType(tree.vartype, localEnv);
   655                     if (tree.nameexpr != null) {
   656                         attr.attribExpr(tree.nameexpr, localEnv);
   657                         MethodSymbol m = localEnv.enclMethod.sym;
   658                         if (m.isConstructor()) {
   659                             Type outertype = m.owner.owner.type;
   660                             if (outertype.hasTag(TypeTag.CLASS)) {
   661                                 checkType(tree.vartype, outertype, "incorrect.constructor.receiver.type");
   662                                 checkType(tree.nameexpr, outertype, "incorrect.constructor.receiver.name");
   663                             } else {
   664                                 log.error(tree, "receiver.parameter.not.applicable.constructor.toplevel.class");
   665                             }
   666                         } else {
   667                             checkType(tree.vartype, m.owner.type, "incorrect.receiver.type");
   668                             checkType(tree.nameexpr, m.owner.type, "incorrect.receiver.name");
   669                         }
   670                     }
   671                 }
   672             } finally {
   673                 deferredLintHandler.setPos(prevLintPos);
   674             }
   676             if ((tree.mods.flags & VARARGS) != 0) {
   677                 //if we are entering a varargs parameter, we need to
   678                 //replace its type (a plain array type) with the more
   679                 //precise VarargsType --- we need to do it this way
   680                 //because varargs is represented in the tree as a
   681                 //modifier on the parameter declaration, and not as a
   682                 //distinct type of array node.
   683                 ArrayType atype = (ArrayType)tree.vartype.type.unannotatedType();
   684                 tree.vartype.type = atype.makeVarargs();
   685             }
   686             Scope enclScope = enter.enterScope(env);
   687             VarSymbol v =
   688                 new VarSymbol(0, tree.name, tree.vartype.type, enclScope.owner);
   689             v.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, v, tree);
   690             tree.sym = v;
   691             if (tree.init != null) {
   692                 v.flags_field |= HASINIT;
   693                 if ((v.flags_field & FINAL) != 0 &&
   694                     needsLazyConstValue(tree.init)) {
   695                     Env<AttrContext> initEnv = getInitEnv(tree, env);
   696                     initEnv.info.enclVar = v;
   697                     v.setLazyConstValue(initEnv(tree, initEnv), attr, tree);
   698                 }
   699             }
   700             if (chk.checkUnique(tree.pos(), v, enclScope)) {
   701                 chk.checkTransparentVar(tree.pos(), v, enclScope);
   702                 enclScope.enter(v);
   703             }
   704             annotateLater(tree.mods.annotations, localEnv, v, tree.pos());
   705             typeAnnotate(tree.vartype, env, v, tree.pos());
   706             v.pos = tree.pos;
   707         } finally {
   708             annotate.enterDone();
   709         }
   710     }
   711     // where
   712     void checkType(JCTree tree, Type type, String diag) {
   713         if (!tree.type.isErroneous() && !types.isSameType(tree.type, type)) {
   714             log.error(tree, diag, type, tree.type);
   715         }
   716     }
   718     public boolean needsLazyConstValue(JCTree tree) {
   719         InitTreeVisitor initTreeVisitor = new InitTreeVisitor();
   720         tree.accept(initTreeVisitor);
   721         return initTreeVisitor.result;
   722     }
   724     /** Visitor class for expressions which might be constant expressions.
   725      */
   726     static class InitTreeVisitor extends JCTree.Visitor {
   728         private boolean result = true;
   730         @Override
   731         public void visitTree(JCTree tree) {}
   733         @Override
   734         public void visitNewClass(JCNewClass that) {
   735             result = false;
   736         }
   738         @Override
   739         public void visitNewArray(JCNewArray that) {
   740             result = false;
   741         }
   743         @Override
   744         public void visitLambda(JCLambda that) {
   745             result = false;
   746         }
   748         @Override
   749         public void visitReference(JCMemberReference that) {
   750             result = false;
   751         }
   753         @Override
   754         public void visitApply(JCMethodInvocation that) {
   755             result = false;
   756         }
   758         @Override
   759         public void visitSelect(JCFieldAccess tree) {
   760             tree.selected.accept(this);
   761         }
   763         @Override
   764         public void visitConditional(JCConditional tree) {
   765             tree.cond.accept(this);
   766             tree.truepart.accept(this);
   767             tree.falsepart.accept(this);
   768         }
   770         @Override
   771         public void visitParens(JCParens tree) {
   772             tree.expr.accept(this);
   773         }
   775         @Override
   776         public void visitTypeCast(JCTypeCast tree) {
   777             tree.expr.accept(this);
   778         }
   779     }
   781     /** Create a fresh environment for a variable's initializer.
   782      *  If the variable is a field, the owner of the environment's scope
   783      *  is be the variable itself, otherwise the owner is the method
   784      *  enclosing the variable definition.
   785      *
   786      *  @param tree     The variable definition.
   787      *  @param env      The environment current outside of the variable definition.
   788      */
   789     Env<AttrContext> initEnv(JCVariableDecl tree, Env<AttrContext> env) {
   790         Env<AttrContext> localEnv = env.dupto(new AttrContextEnv(tree, env.info.dup()));
   791         if (tree.sym.owner.kind == TYP) {
   792             localEnv.info.scope = env.info.scope.dupUnshared();
   793             localEnv.info.scope.owner = tree.sym;
   794         }
   795         if ((tree.mods.flags & STATIC) != 0 ||
   796                 ((env.enclClass.sym.flags() & INTERFACE) != 0 && env.enclMethod == null))
   797             localEnv.info.staticLevel++;
   798         return localEnv;
   799     }
   801     /** Default member enter visitor method: do nothing
   802      */
   803     public void visitTree(JCTree tree) {
   804     }
   806     public void visitErroneous(JCErroneous tree) {
   807         if (tree.errs != null)
   808             memberEnter(tree.errs, env);
   809     }
   811     public Env<AttrContext> getMethodEnv(JCMethodDecl tree, Env<AttrContext> env) {
   812         Env<AttrContext> mEnv = methodEnv(tree, env);
   813         mEnv.info.lint = mEnv.info.lint.augment(tree.sym);
   814         for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
   815             mEnv.info.scope.enterIfAbsent(l.head.type.tsym);
   816         for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail)
   817             mEnv.info.scope.enterIfAbsent(l.head.sym);
   818         return mEnv;
   819     }
   821     public Env<AttrContext> getInitEnv(JCVariableDecl tree, Env<AttrContext> env) {
   822         Env<AttrContext> iEnv = initEnv(tree, env);
   823         return iEnv;
   824     }
   826 /* ********************************************************************
   827  * Type completion
   828  *********************************************************************/
   830     Type attribImportType(JCTree tree, Env<AttrContext> env) {
   831         Assert.check(completionEnabled);
   832         try {
   833             // To prevent deep recursion, suppress completion of some
   834             // types.
   835             completionEnabled = false;
   836             return attr.attribType(tree, env);
   837         } finally {
   838             completionEnabled = true;
   839         }
   840     }
   842 /* ********************************************************************
   843  * Annotation processing
   844  *********************************************************************/
   846     /** Queue annotations for later processing. */
   847     void annotateLater(final List<JCAnnotation> annotations,
   848                        final Env<AttrContext> localEnv,
   849                        final Symbol s,
   850                        final DiagnosticPosition deferPos) {
   851         if (annotations.isEmpty()) {
   852             return;
   853         }
   854         if (s.kind != PCK) {
   855             s.resetAnnotations(); // mark Annotations as incomplete for now
   856         }
   857         annotate.normal(new Annotate.Worker() {
   858                 @Override
   859                 public String toString() {
   860                     return "annotate " + annotations + " onto " + s + " in " + s.owner;
   861                 }
   863                 @Override
   864                 public void run() {
   865                     Assert.check(s.kind == PCK || s.annotationsPendingCompletion());
   866                     JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile);
   867                     DiagnosticPosition prevLintPos =
   868                         deferPos != null
   869                         ? deferredLintHandler.setPos(deferPos)
   870                         : deferredLintHandler.immediate();
   871                     Lint prevLint = deferPos != null ? null : chk.setLint(lint);
   872                     try {
   873                         if (s.hasAnnotations() &&
   874                             annotations.nonEmpty())
   875                             log.error(annotations.head.pos,
   876                                       "already.annotated",
   877                                       kindName(s), s);
   878                         actualEnterAnnotations(annotations, localEnv, s);
   879                     } finally {
   880                         if (prevLint != null)
   881                             chk.setLint(prevLint);
   882                         deferredLintHandler.setPos(prevLintPos);
   883                         log.useSource(prev);
   884                     }
   885                 }
   886             });
   888         annotate.validate(new Annotate.Worker() { //validate annotations
   889             @Override
   890             public void run() {
   891                 JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile);
   892                 try {
   893                     chk.validateAnnotations(annotations, s);
   894                 } finally {
   895                     log.useSource(prev);
   896                 }
   897             }
   898         });
   899     }
   901     /**
   902      * Check if a list of annotations contains a reference to
   903      * java.lang.Deprecated.
   904      **/
   905     private boolean hasDeprecatedAnnotation(List<JCAnnotation> annotations) {
   906         for (List<JCAnnotation> al = annotations; !al.isEmpty(); al = al.tail) {
   907             JCAnnotation a = al.head;
   908             if (a.annotationType.type == syms.deprecatedType && a.args.isEmpty())
   909                 return true;
   910         }
   911         return false;
   912     }
   914     /** Enter a set of annotations. */
   915     private void actualEnterAnnotations(List<JCAnnotation> annotations,
   916                           Env<AttrContext> env,
   917                           Symbol s) {
   918         Map<TypeSymbol, ListBuffer<Attribute.Compound>> annotated =
   919                 new LinkedHashMap<TypeSymbol, ListBuffer<Attribute.Compound>>();
   920         Map<Attribute.Compound, DiagnosticPosition> pos =
   921                 new HashMap<Attribute.Compound, DiagnosticPosition>();
   923         for (List<JCAnnotation> al = annotations; !al.isEmpty(); al = al.tail) {
   924             JCAnnotation a = al.head;
   925             Attribute.Compound c = annotate.enterAnnotation(a,
   926                                                             syms.annotationType,
   927                                                             env);
   928             if (c == null) {
   929                 continue;
   930             }
   932             if (annotated.containsKey(a.type.tsym)) {
   933                 if (!allowRepeatedAnnos) {
   934                     log.error(a.pos(), "repeatable.annotations.not.supported.in.source");
   935                     allowRepeatedAnnos = true;
   936                 }
   937                 ListBuffer<Attribute.Compound> l = annotated.get(a.type.tsym);
   938                 l = l.append(c);
   939                 annotated.put(a.type.tsym, l);
   940                 pos.put(c, a.pos());
   941             } else {
   942                 annotated.put(a.type.tsym, ListBuffer.of(c));
   943                 pos.put(c, a.pos());
   944             }
   946             // Note: @Deprecated has no effect on local variables and parameters
   947             if (!c.type.isErroneous()
   948                 && s.owner.kind != MTH
   949                 && types.isSameType(c.type, syms.deprecatedType)) {
   950                 s.flags_field |= Flags.DEPRECATED;
   951             }
   952         }
   954         s.setDeclarationAttributesWithCompletion(
   955                 annotate.new AnnotateRepeatedContext<Attribute.Compound>(env, annotated, pos, log, false));
   956     }
   958     /** Queue processing of an attribute default value. */
   959     void annotateDefaultValueLater(final JCExpression defaultValue,
   960                                    final Env<AttrContext> localEnv,
   961                                    final MethodSymbol m) {
   962         annotate.normal(new Annotate.Worker() {
   963                 @Override
   964                 public String toString() {
   965                     return "annotate " + m.owner + "." +
   966                         m + " default " + defaultValue;
   967                 }
   969                 @Override
   970                 public void run() {
   971                     JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile);
   972                     try {
   973                         enterDefaultValue(defaultValue, localEnv, m);
   974                     } finally {
   975                         log.useSource(prev);
   976                     }
   977                 }
   978             });
   979         annotate.validate(new Annotate.Worker() { //validate annotations
   980             @Override
   981             public void run() {
   982                 JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile);
   983                 try {
   984                     // if default value is an annotation, check it is a well-formed
   985                     // annotation value (e.g. no duplicate values, no missing values, etc.)
   986                     chk.validateAnnotationTree(defaultValue);
   987                 } finally {
   988                     log.useSource(prev);
   989                 }
   990             }
   991         });
   992     }
   994     /** Enter a default value for an attribute method. */
   995     private void enterDefaultValue(final JCExpression defaultValue,
   996                                    final Env<AttrContext> localEnv,
   997                                    final MethodSymbol m) {
   998         m.defaultValue = annotate.enterAttributeValue(m.type.getReturnType(),
   999                                                       defaultValue,
  1000                                                       localEnv);
  1003 /* ********************************************************************
  1004  * Source completer
  1005  *********************************************************************/
  1007     /** Complete entering a class.
  1008      *  @param sym         The symbol of the class to be completed.
  1009      */
  1010     public void complete(Symbol sym) throws CompletionFailure {
  1011         // Suppress some (recursive) MemberEnter invocations
  1012         if (!completionEnabled) {
  1013             // Re-install same completer for next time around and return.
  1014             Assert.check((sym.flags() & Flags.COMPOUND) == 0);
  1015             sym.completer = this;
  1016             return;
  1019         ClassSymbol c = (ClassSymbol)sym;
  1020         ClassType ct = (ClassType)c.type;
  1021         Env<AttrContext> env = enter.typeEnvs.get(c);
  1022         JCClassDecl tree = (JCClassDecl)env.tree;
  1023         boolean wasFirst = isFirst;
  1024         isFirst = false;
  1026         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
  1027         DiagnosticPosition prevLintPos = deferredLintHandler.setPos(tree.pos());
  1028         try {
  1029             // Save class environment for later member enter (2) processing.
  1030             halfcompleted.append(env);
  1032             // Mark class as not yet attributed.
  1033             c.flags_field |= UNATTRIBUTED;
  1035             // If this is a toplevel-class, make sure any preceding import
  1036             // clauses have been seen.
  1037             if (c.owner.kind == PCK) {
  1038                 memberEnter(env.toplevel, env.enclosing(TOPLEVEL));
  1039                 todo.append(env);
  1042             if (c.owner.kind == TYP)
  1043                 c.owner.complete();
  1045             // create an environment for evaluating the base clauses
  1046             Env<AttrContext> baseEnv = baseEnv(tree, env);
  1048             if (tree.extending != null)
  1049                 typeAnnotate(tree.extending, baseEnv, sym, tree.pos());
  1050             for (JCExpression impl : tree.implementing)
  1051                 typeAnnotate(impl, baseEnv, sym, tree.pos());
  1052             annotate.flush();
  1054             // Determine supertype.
  1055             Type supertype =
  1056                 (tree.extending != null)
  1057                 ? attr.attribBase(tree.extending, baseEnv, true, false, true)
  1058                 : ((tree.mods.flags & Flags.ENUM) != 0)
  1059                 ? attr.attribBase(enumBase(tree.pos, c), baseEnv,
  1060                                   true, false, false)
  1061                 : (c.fullname == names.java_lang_Object)
  1062                 ? Type.noType
  1063                 : syms.objectType;
  1064             ct.supertype_field = modelMissingTypes(supertype, tree.extending, false);
  1066             // Determine interfaces.
  1067             ListBuffer<Type> interfaces = new ListBuffer<Type>();
  1068             ListBuffer<Type> all_interfaces = null; // lazy init
  1069             Set<Type> interfaceSet = new HashSet<Type>();
  1070             List<JCExpression> interfaceTrees = tree.implementing;
  1071             for (JCExpression iface : interfaceTrees) {
  1072                 Type i = attr.attribBase(iface, baseEnv, false, true, true);
  1073                 if (i.hasTag(CLASS)) {
  1074                     interfaces.append(i);
  1075                     if (all_interfaces != null) all_interfaces.append(i);
  1076                     chk.checkNotRepeated(iface.pos(), types.erasure(i), interfaceSet);
  1077                 } else {
  1078                     if (all_interfaces == null)
  1079                         all_interfaces = new ListBuffer<Type>().appendList(interfaces);
  1080                     all_interfaces.append(modelMissingTypes(i, iface, true));
  1083             if ((c.flags_field & ANNOTATION) != 0) {
  1084                 ct.interfaces_field = List.of(syms.annotationType);
  1085                 ct.all_interfaces_field = ct.interfaces_field;
  1086             }  else {
  1087                 ct.interfaces_field = interfaces.toList();
  1088                 ct.all_interfaces_field = (all_interfaces == null)
  1089                         ? ct.interfaces_field : all_interfaces.toList();
  1092             if (c.fullname == names.java_lang_Object) {
  1093                 if (tree.extending != null) {
  1094                     chk.checkNonCyclic(tree.extending.pos(),
  1095                                        supertype);
  1096                     ct.supertype_field = Type.noType;
  1098                 else if (tree.implementing.nonEmpty()) {
  1099                     chk.checkNonCyclic(tree.implementing.head.pos(),
  1100                                        ct.interfaces_field.head);
  1101                     ct.interfaces_field = List.nil();
  1105             // Annotations.
  1106             // In general, we cannot fully process annotations yet,  but we
  1107             // can attribute the annotation types and then check to see if the
  1108             // @Deprecated annotation is present.
  1109             attr.attribAnnotationTypes(tree.mods.annotations, baseEnv);
  1110             if (hasDeprecatedAnnotation(tree.mods.annotations))
  1111                 c.flags_field |= DEPRECATED;
  1112             annotateLater(tree.mods.annotations, baseEnv, c, tree.pos());
  1113             // class type parameters use baseEnv but everything uses env
  1115             chk.checkNonCyclicDecl(tree);
  1117             attr.attribTypeVariables(tree.typarams, baseEnv);
  1118             // Do this here, where we have the symbol.
  1119             for (JCTypeParameter tp : tree.typarams)
  1120                 typeAnnotate(tp, baseEnv, sym, tree.pos());
  1122             // Add default constructor if needed.
  1123             if ((c.flags() & INTERFACE) == 0 &&
  1124                 !TreeInfo.hasConstructors(tree.defs)) {
  1125                 List<Type> argtypes = List.nil();
  1126                 List<Type> typarams = List.nil();
  1127                 List<Type> thrown = List.nil();
  1128                 long ctorFlags = 0;
  1129                 boolean based = false;
  1130                 boolean addConstructor = true;
  1131                 JCNewClass nc = null;
  1132                 if (c.name.isEmpty()) {
  1133                     nc = (JCNewClass)env.next.tree;
  1134                     if (nc.constructor != null) {
  1135                         addConstructor = nc.constructor.kind != ERR;
  1136                         Type superConstrType = types.memberType(c.type,
  1137                                                                 nc.constructor);
  1138                         argtypes = superConstrType.getParameterTypes();
  1139                         typarams = superConstrType.getTypeArguments();
  1140                         ctorFlags = nc.constructor.flags() & VARARGS;
  1141                         if (nc.encl != null) {
  1142                             argtypes = argtypes.prepend(nc.encl.type);
  1143                             based = true;
  1145                         thrown = superConstrType.getThrownTypes();
  1148                 if (addConstructor) {
  1149                     MethodSymbol basedConstructor = nc != null ?
  1150                             (MethodSymbol)nc.constructor : null;
  1151                     JCTree constrDef = DefaultConstructor(make.at(tree.pos), c,
  1152                                                         basedConstructor,
  1153                                                         typarams, argtypes, thrown,
  1154                                                         ctorFlags, based);
  1155                     tree.defs = tree.defs.prepend(constrDef);
  1159             // enter symbols for 'this' into current scope.
  1160             VarSymbol thisSym =
  1161                 new VarSymbol(FINAL | HASINIT, names._this, c.type, c);
  1162             thisSym.pos = Position.FIRSTPOS;
  1163             env.info.scope.enter(thisSym);
  1164             // if this is a class, enter symbol for 'super' into current scope.
  1165             if ((c.flags_field & INTERFACE) == 0 &&
  1166                     ct.supertype_field.hasTag(CLASS)) {
  1167                 VarSymbol superSym =
  1168                     new VarSymbol(FINAL | HASINIT, names._super,
  1169                                   ct.supertype_field, c);
  1170                 superSym.pos = Position.FIRSTPOS;
  1171                 env.info.scope.enter(superSym);
  1174             // check that no package exists with same fully qualified name,
  1175             // but admit classes in the unnamed package which have the same
  1176             // name as a top-level package.
  1177             if (checkClash &&
  1178                 c.owner.kind == PCK && c.owner != syms.unnamedPackage &&
  1179                 reader.packageExists(c.fullname)) {
  1180                 log.error(tree.pos, "clash.with.pkg.of.same.name", Kinds.kindName(sym), c);
  1182             if (c.owner.kind == PCK && (c.flags_field & PUBLIC) == 0 &&
  1183                 !env.toplevel.sourcefile.isNameCompatible(c.name.toString(),JavaFileObject.Kind.SOURCE)) {
  1184                 c.flags_field |= AUXILIARY;
  1186         } catch (CompletionFailure ex) {
  1187             chk.completionError(tree.pos(), ex);
  1188         } finally {
  1189             deferredLintHandler.setPos(prevLintPos);
  1190             log.useSource(prev);
  1193         // Enter all member fields and methods of a set of half completed
  1194         // classes in a second phase.
  1195         if (wasFirst) {
  1196             try {
  1197                 while (halfcompleted.nonEmpty()) {
  1198                     Env<AttrContext> toFinish = halfcompleted.next();
  1199                     finish(toFinish);
  1200                     if (allowTypeAnnos) {
  1201                         typeAnnotations.organizeTypeAnnotationsSignatures(toFinish, (JCClassDecl)toFinish.tree);
  1202                         typeAnnotations.validateTypeAnnotationsSignatures(toFinish, (JCClassDecl)toFinish.tree);
  1205             } finally {
  1206                 isFirst = true;
  1211     /*
  1212      * If the symbol is non-null, attach the type annotation to it.
  1213      */
  1214     private void actualEnterTypeAnnotations(final List<JCAnnotation> annotations,
  1215             final Env<AttrContext> env,
  1216             final Symbol s) {
  1217         Map<TypeSymbol, ListBuffer<Attribute.TypeCompound>> annotated =
  1218                 new LinkedHashMap<TypeSymbol, ListBuffer<Attribute.TypeCompound>>();
  1219         Map<Attribute.TypeCompound, DiagnosticPosition> pos =
  1220                 new HashMap<Attribute.TypeCompound, DiagnosticPosition>();
  1222         for (List<JCAnnotation> al = annotations; !al.isEmpty(); al = al.tail) {
  1223             JCAnnotation a = al.head;
  1224             Attribute.TypeCompound tc = annotate.enterTypeAnnotation(a,
  1225                     syms.annotationType,
  1226                     env);
  1227             if (tc == null) {
  1228                 continue;
  1231             if (annotated.containsKey(a.type.tsym)) {
  1232                 if (source.allowRepeatedAnnotations()) {
  1233                     ListBuffer<Attribute.TypeCompound> l = annotated.get(a.type.tsym);
  1234                     l = l.append(tc);
  1235                     annotated.put(a.type.tsym, l);
  1236                     pos.put(tc, a.pos());
  1237                 } else {
  1238                     log.error(a.pos(), "repeatable.annotations.not.supported.in.source");
  1240             } else {
  1241                 annotated.put(a.type.tsym, ListBuffer.of(tc));
  1242                 pos.put(tc, a.pos());
  1246         if (s != null) {
  1247             s.appendTypeAttributesWithCompletion(
  1248                     annotate.new AnnotateRepeatedContext<Attribute.TypeCompound>(env, annotated, pos, log, true));
  1252     public void typeAnnotate(final JCTree tree, final Env<AttrContext> env, final Symbol sym, DiagnosticPosition deferPos) {
  1253         if (allowTypeAnnos) {
  1254             tree.accept(new TypeAnnotate(env, sym, deferPos));
  1258     /**
  1259      * We need to use a TreeScanner, because it is not enough to visit the top-level
  1260      * annotations. We also need to visit type arguments, etc.
  1261      */
  1262     private class TypeAnnotate extends TreeScanner {
  1263         private Env<AttrContext> env;
  1264         private Symbol sym;
  1265         private DiagnosticPosition deferPos;
  1267         public TypeAnnotate(final Env<AttrContext> env, final Symbol sym, DiagnosticPosition deferPos) {
  1268             this.env = env;
  1269             this.sym = sym;
  1270             this.deferPos = deferPos;
  1273         void annotateTypeLater(final List<JCAnnotation> annotations) {
  1274             if (annotations.isEmpty()) {
  1275                 return;
  1278             final DiagnosticPosition deferPos = this.deferPos;
  1280             annotate.normal(new Annotate.Worker() {
  1281                 @Override
  1282                 public String toString() {
  1283                     return "type annotate " + annotations + " onto " + sym + " in " + sym.owner;
  1285                 @Override
  1286                 public void run() {
  1287                     JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
  1288                     DiagnosticPosition prevLintPos = null;
  1290                     if (deferPos != null) {
  1291                         prevLintPos = deferredLintHandler.setPos(deferPos);
  1293                     try {
  1294                         actualEnterTypeAnnotations(annotations, env, sym);
  1295                     } finally {
  1296                         if (prevLintPos != null)
  1297                             deferredLintHandler.setPos(prevLintPos);
  1298                         log.useSource(prev);
  1301             });
  1304         @Override
  1305         public void visitAnnotatedType(final JCAnnotatedType tree) {
  1306             annotateTypeLater(tree.annotations);
  1307             super.visitAnnotatedType(tree);
  1310         @Override
  1311         public void visitTypeParameter(final JCTypeParameter tree) {
  1312             annotateTypeLater(tree.annotations);
  1313             super.visitTypeParameter(tree);
  1316         @Override
  1317         public void visitNewArray(final JCNewArray tree) {
  1318             annotateTypeLater(tree.annotations);
  1319             for (List<JCAnnotation> dimAnnos : tree.dimAnnotations)
  1320                 annotateTypeLater(dimAnnos);
  1321             super.visitNewArray(tree);
  1324         @Override
  1325         public void visitMethodDef(final JCMethodDecl tree) {
  1326             scan(tree.mods);
  1327             scan(tree.restype);
  1328             scan(tree.typarams);
  1329             scan(tree.recvparam);
  1330             scan(tree.params);
  1331             scan(tree.thrown);
  1332             scan(tree.defaultValue);
  1333             // Do not annotate the body, just the signature.
  1334             // scan(tree.body);
  1337         @Override
  1338         public void visitVarDef(final JCVariableDecl tree) {
  1339             DiagnosticPosition prevPos = deferPos;
  1340             deferPos = tree.pos();
  1341             try {
  1342                 if (sym != null && sym.kind == Kinds.VAR) {
  1343                     // Don't visit a parameter once when the sym is the method
  1344                     // and once when the sym is the parameter.
  1345                     scan(tree.mods);
  1346                     scan(tree.vartype);
  1348                 scan(tree.init);
  1349             } finally {
  1350                 deferPos = prevPos;
  1354         @Override
  1355         public void visitClassDef(JCClassDecl tree) {
  1356             // We can only hit a classdef if it is declared within
  1357             // a method. Ignore it - the class will be visited
  1358             // separately later.
  1361         @Override
  1362         public void visitNewClass(JCNewClass tree) {
  1363             if (tree.def == null) {
  1364                 // For an anonymous class instantiation the class
  1365                 // will be visited separately.
  1366                 super.visitNewClass(tree);
  1372     private Env<AttrContext> baseEnv(JCClassDecl tree, Env<AttrContext> env) {
  1373         Scope baseScope = new Scope(tree.sym);
  1374         //import already entered local classes into base scope
  1375         for (Scope.Entry e = env.outer.info.scope.elems ; e != null ; e = e.sibling) {
  1376             if (e.sym.isLocal()) {
  1377                 baseScope.enter(e.sym);
  1380         //import current type-parameters into base scope
  1381         if (tree.typarams != null)
  1382             for (List<JCTypeParameter> typarams = tree.typarams;
  1383                  typarams.nonEmpty();
  1384                  typarams = typarams.tail)
  1385                 baseScope.enter(typarams.head.type.tsym);
  1386         Env<AttrContext> outer = env.outer; // the base clause can't see members of this class
  1387         Env<AttrContext> localEnv = outer.dup(tree, outer.info.dup(baseScope));
  1388         localEnv.baseClause = true;
  1389         localEnv.outer = outer;
  1390         localEnv.info.isSelfCall = false;
  1391         return localEnv;
  1394     /** Enter member fields and methods of a class
  1395      *  @param env        the environment current for the class block.
  1396      */
  1397     private void finish(Env<AttrContext> env) {
  1398         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
  1399         try {
  1400             JCClassDecl tree = (JCClassDecl)env.tree;
  1401             finishClass(tree, env);
  1402         } finally {
  1403             log.useSource(prev);
  1407     /** Generate a base clause for an enum type.
  1408      *  @param pos              The position for trees and diagnostics, if any
  1409      *  @param c                The class symbol of the enum
  1410      */
  1411     private JCExpression enumBase(int pos, ClassSymbol c) {
  1412         JCExpression result = make.at(pos).
  1413             TypeApply(make.QualIdent(syms.enumSym),
  1414                       List.<JCExpression>of(make.Type(c.type)));
  1415         return result;
  1418     Type modelMissingTypes(Type t, final JCExpression tree, final boolean interfaceExpected) {
  1419         if (!t.hasTag(ERROR))
  1420             return t;
  1422         return new ErrorType(t.getOriginalType(), t.tsym) {
  1423             private Type modelType;
  1425             @Override
  1426             public Type getModelType() {
  1427                 if (modelType == null)
  1428                     modelType = new Synthesizer(getOriginalType(), interfaceExpected).visit(tree);
  1429                 return modelType;
  1431         };
  1433     // where
  1434     private class Synthesizer extends JCTree.Visitor {
  1435         Type originalType;
  1436         boolean interfaceExpected;
  1437         List<ClassSymbol> synthesizedSymbols = List.nil();
  1438         Type result;
  1440         Synthesizer(Type originalType, boolean interfaceExpected) {
  1441             this.originalType = originalType;
  1442             this.interfaceExpected = interfaceExpected;
  1445         Type visit(JCTree tree) {
  1446             tree.accept(this);
  1447             return result;
  1450         List<Type> visit(List<? extends JCTree> trees) {
  1451             ListBuffer<Type> lb = new ListBuffer<Type>();
  1452             for (JCTree t: trees)
  1453                 lb.append(visit(t));
  1454             return lb.toList();
  1457         @Override
  1458         public void visitTree(JCTree tree) {
  1459             result = syms.errType;
  1462         @Override
  1463         public void visitIdent(JCIdent tree) {
  1464             if (!tree.type.hasTag(ERROR)) {
  1465                 result = tree.type;
  1466             } else {
  1467                 result = synthesizeClass(tree.name, syms.unnamedPackage).type;
  1471         @Override
  1472         public void visitSelect(JCFieldAccess tree) {
  1473             if (!tree.type.hasTag(ERROR)) {
  1474                 result = tree.type;
  1475             } else {
  1476                 Type selectedType;
  1477                 boolean prev = interfaceExpected;
  1478                 try {
  1479                     interfaceExpected = false;
  1480                     selectedType = visit(tree.selected);
  1481                 } finally {
  1482                     interfaceExpected = prev;
  1484                 ClassSymbol c = synthesizeClass(tree.name, selectedType.tsym);
  1485                 result = c.type;
  1489         @Override
  1490         public void visitTypeApply(JCTypeApply tree) {
  1491             if (!tree.type.hasTag(ERROR)) {
  1492                 result = tree.type;
  1493             } else {
  1494                 ClassType clazzType = (ClassType) visit(tree.clazz);
  1495                 if (synthesizedSymbols.contains(clazzType.tsym))
  1496                     synthesizeTyparams((ClassSymbol) clazzType.tsym, tree.arguments.size());
  1497                 final List<Type> actuals = visit(tree.arguments);
  1498                 result = new ErrorType(tree.type, clazzType.tsym) {
  1499                     @Override
  1500                     public List<Type> getTypeArguments() {
  1501                         return actuals;
  1503                 };
  1507         ClassSymbol synthesizeClass(Name name, Symbol owner) {
  1508             int flags = interfaceExpected ? INTERFACE : 0;
  1509             ClassSymbol c = new ClassSymbol(flags, name, owner);
  1510             c.members_field = new Scope.ErrorScope(c);
  1511             c.type = new ErrorType(originalType, c) {
  1512                 @Override
  1513                 public List<Type> getTypeArguments() {
  1514                     return typarams_field;
  1516             };
  1517             synthesizedSymbols = synthesizedSymbols.prepend(c);
  1518             return c;
  1521         void synthesizeTyparams(ClassSymbol sym, int n) {
  1522             ClassType ct = (ClassType) sym.type;
  1523             Assert.check(ct.typarams_field.isEmpty());
  1524             if (n == 1) {
  1525                 TypeVar v = new TypeVar(names.fromString("T"), sym, syms.botType);
  1526                 ct.typarams_field = ct.typarams_field.prepend(v);
  1527             } else {
  1528                 for (int i = n; i > 0; i--) {
  1529                     TypeVar v = new TypeVar(names.fromString("T" + i), sym, syms.botType);
  1530                     ct.typarams_field = ct.typarams_field.prepend(v);
  1537 /* ***************************************************************************
  1538  * tree building
  1539  ****************************************************************************/
  1541     /** Generate default constructor for given class. For classes different
  1542      *  from java.lang.Object, this is:
  1544      *    c(argtype_0 x_0, ..., argtype_n x_n) throws thrown {
  1545      *      super(x_0, ..., x_n)
  1546      *    }
  1548      *  or, if based == true:
  1550      *    c(argtype_0 x_0, ..., argtype_n x_n) throws thrown {
  1551      *      x_0.super(x_1, ..., x_n)
  1552      *    }
  1554      *  @param make     The tree factory.
  1555      *  @param c        The class owning the default constructor.
  1556      *  @param argtypes The parameter types of the constructor.
  1557      *  @param thrown   The thrown exceptions of the constructor.
  1558      *  @param based    Is first parameter a this$n?
  1559      */
  1560     JCTree DefaultConstructor(TreeMaker make,
  1561                             ClassSymbol c,
  1562                             MethodSymbol baseInit,
  1563                             List<Type> typarams,
  1564                             List<Type> argtypes,
  1565                             List<Type> thrown,
  1566                             long flags,
  1567                             boolean based) {
  1568         JCTree result;
  1569         if ((c.flags() & ENUM) != 0 &&
  1570             (types.supertype(c.type).tsym == syms.enumSym)) {
  1571             // constructors of true enums are private
  1572             flags = (flags & ~AccessFlags) | PRIVATE | GENERATEDCONSTR;
  1573         } else
  1574             flags |= (c.flags() & AccessFlags) | GENERATEDCONSTR;
  1575         if (c.name.isEmpty()) {
  1576             flags |= ANONCONSTR;
  1578         Type mType = new MethodType(argtypes, null, thrown, c);
  1579         Type initType = typarams.nonEmpty() ?
  1580                 new ForAll(typarams, mType) :
  1581                 mType;
  1582         MethodSymbol init = new MethodSymbol(flags, names.init,
  1583                 initType, c);
  1584         init.params = createDefaultConstructorParams(make, baseInit, init,
  1585                 argtypes, based);
  1586         List<JCVariableDecl> params = make.Params(argtypes, init);
  1587         List<JCStatement> stats = List.nil();
  1588         if (c.type != syms.objectType) {
  1589             stats = stats.prepend(SuperCall(make, typarams, params, based));
  1591         result = make.MethodDef(init, make.Block(0, stats));
  1592         return result;
  1595     private List<VarSymbol> createDefaultConstructorParams(
  1596             TreeMaker make,
  1597             MethodSymbol baseInit,
  1598             MethodSymbol init,
  1599             List<Type> argtypes,
  1600             boolean based) {
  1601         List<VarSymbol> initParams = null;
  1602         List<Type> argTypesList = argtypes;
  1603         if (based) {
  1604             /*  In this case argtypes will have an extra type, compared to baseInit,
  1605              *  corresponding to the type of the enclosing instance i.e.:
  1607              *  Inner i = outer.new Inner(1){}
  1609              *  in the above example argtypes will be (Outer, int) and baseInit
  1610              *  will have parameter's types (int). So in this case we have to add
  1611              *  first the extra type in argtypes and then get the names of the
  1612              *  parameters from baseInit.
  1613              */
  1614             initParams = List.nil();
  1615             VarSymbol param = new VarSymbol(PARAMETER, make.paramName(0), argtypes.head, init);
  1616             initParams = initParams.append(param);
  1617             argTypesList = argTypesList.tail;
  1619         if (baseInit != null && baseInit.params != null &&
  1620             baseInit.params.nonEmpty() && argTypesList.nonEmpty()) {
  1621             initParams = (initParams == null) ? List.<VarSymbol>nil() : initParams;
  1622             List<VarSymbol> baseInitParams = baseInit.params;
  1623             while (baseInitParams.nonEmpty() && argTypesList.nonEmpty()) {
  1624                 VarSymbol param = new VarSymbol(baseInitParams.head.flags() | PARAMETER,
  1625                         baseInitParams.head.name, argTypesList.head, init);
  1626                 initParams = initParams.append(param);
  1627                 baseInitParams = baseInitParams.tail;
  1628                 argTypesList = argTypesList.tail;
  1631         return initParams;
  1634     /** Generate call to superclass constructor. This is:
  1636      *    super(id_0, ..., id_n)
  1638      * or, if based == true
  1640      *    id_0.super(id_1,...,id_n)
  1642      *  where id_0, ..., id_n are the names of the given parameters.
  1644      *  @param make    The tree factory
  1645      *  @param params  The parameters that need to be passed to super
  1646      *  @param typarams  The type parameters that need to be passed to super
  1647      *  @param based   Is first parameter a this$n?
  1648      */
  1649     JCExpressionStatement SuperCall(TreeMaker make,
  1650                    List<Type> typarams,
  1651                    List<JCVariableDecl> params,
  1652                    boolean based) {
  1653         JCExpression meth;
  1654         if (based) {
  1655             meth = make.Select(make.Ident(params.head), names._super);
  1656             params = params.tail;
  1657         } else {
  1658             meth = make.Ident(names._super);
  1660         List<JCExpression> typeargs = typarams.nonEmpty() ? make.Types(typarams) : null;
  1661         return make.Exec(make.Apply(typeargs, meth, make.Idents(params)));

mercurial