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

Mon, 04 Feb 2013 18:08:53 -0500

author
dholmes
date
Mon, 04 Feb 2013 18:08:53 -0500
changeset 1570
f91144b7da75
parent 1521
71f35e4b93a5
child 1565
d04960f05593
permissions
-rw-r--r--

Merge

     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.lang.model.type.TypeKind;
    35 import javax.tools.JavaFileObject;
    37 import com.sun.tools.javac.code.*;
    38 import com.sun.tools.javac.jvm.*;
    39 import com.sun.tools.javac.tree.*;
    40 import com.sun.tools.javac.util.*;
    42 import com.sun.tools.javac.code.Type.*;
    43 import com.sun.tools.javac.code.Symbol.*;
    44 import com.sun.tools.javac.tree.JCTree.*;
    46 import static com.sun.tools.javac.code.Flags.*;
    47 import static com.sun.tools.javac.code.Flags.ANNOTATION;
    48 import static com.sun.tools.javac.code.Kinds.*;
    49 import static com.sun.tools.javac.code.TypeTag.CLASS;
    50 import static com.sun.tools.javac.code.TypeTag.ERROR;
    51 import static com.sun.tools.javac.code.TypeTag.TYPEVAR;
    52 import static com.sun.tools.javac.tree.JCTree.Tag.*;
    53 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
    54 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    56 /** This is the second phase of Enter, in which classes are completed
    57  *  by entering their members into the class scope using
    58  *  MemberEnter.complete().  See Enter for an overview.
    59  *
    60  *  <p><b>This is NOT part of any supported API.
    61  *  If you write code that depends on this, you do so at your own risk.
    62  *  This code and its internal interfaces are subject to change or
    63  *  deletion without notice.</b>
    64  */
    65 public class MemberEnter extends JCTree.Visitor implements Completer {
    66     protected static final Context.Key<MemberEnter> memberEnterKey =
    67         new Context.Key<MemberEnter>();
    69     /** A switch to determine whether we check for package/class conflicts
    70      */
    71     final static boolean checkClash = true;
    73     private final Names names;
    74     private final Enter enter;
    75     private final Log log;
    76     private final Check chk;
    77     private final Attr attr;
    78     private final Symtab syms;
    79     private final TreeMaker make;
    80     private final ClassReader reader;
    81     private final Todo todo;
    82     private final Annotate annotate;
    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;
    89     public static MemberEnter instance(Context context) {
    90         MemberEnter instance = context.get(memberEnterKey);
    91         if (instance == null)
    92             instance = new MemberEnter(context);
    93         return instance;
    94     }
    96     protected MemberEnter(Context context) {
    97         context.put(memberEnterKey, this);
    98         names = Names.instance(context);
    99         enter = Enter.instance(context);
   100         log = Log.instance(context);
   101         chk = Check.instance(context);
   102         attr = Attr.instance(context);
   103         syms = Symtab.instance(context);
   104         make = TreeMaker.instance(context);
   105         reader = ClassReader.instance(context);
   106         todo = Todo.instance(context);
   107         annotate = Annotate.instance(context);
   108         types = Types.instance(context);
   109         diags = JCDiagnostic.Factory.instance(context);
   110         source = Source.instance(context);
   111         target = Target.instance(context);
   112         deferredLintHandler = DeferredLintHandler.instance(context);
   113     }
   115     /** A queue for classes whose members still need to be entered into the
   116      *  symbol table.
   117      */
   118     ListBuffer<Env<AttrContext>> halfcompleted = new ListBuffer<Env<AttrContext>>();
   120     /** Set to true only when the first of a set of classes is
   121      *  processed from the halfcompleted queue.
   122      */
   123     boolean isFirst = true;
   125     /** A flag to disable completion from time to time during member
   126      *  enter, as we only need to look up types.  This avoids
   127      *  unnecessarily deep recursion.
   128      */
   129     boolean completionEnabled = true;
   131     /* ---------- Processing import clauses ----------------
   132      */
   134     /** Import all classes of a class or package on demand.
   135      *  @param pos           Position to be used for error reporting.
   136      *  @param tsym          The class or package the members of which are imported.
   137      *  @param env           The env in which the imported classes will be entered.
   138      */
   139     private void importAll(int pos,
   140                            final TypeSymbol tsym,
   141                            Env<AttrContext> env) {
   142         // Check that packages imported from exist (JLS ???).
   143         if (tsym.kind == PCK && tsym.members().elems == null && !tsym.exists()) {
   144             // If we can't find java.lang, exit immediately.
   145             if (((PackageSymbol)tsym).fullname.equals(names.java_lang)) {
   146                 JCDiagnostic msg = diags.fragment("fatal.err.no.java.lang");
   147                 throw new FatalError(msg);
   148             } else {
   149                 log.error(DiagnosticFlag.RESOLVE_ERROR, pos, "doesnt.exist", tsym);
   150             }
   151         }
   152         env.toplevel.starImportScope.importAll(tsym.members());
   153     }
   155     /** Import all static members of a class or package on demand.
   156      *  @param pos           Position to be used for error reporting.
   157      *  @param tsym          The class or package the members of which are imported.
   158      *  @param env           The env in which the imported classes will be entered.
   159      */
   160     private void importStaticAll(int pos,
   161                                  final TypeSymbol tsym,
   162                                  Env<AttrContext> env) {
   163         final JavaFileObject sourcefile = env.toplevel.sourcefile;
   164         final Scope toScope = env.toplevel.starImportScope;
   165         final PackageSymbol packge = env.toplevel.packge;
   166         final TypeSymbol origin = tsym;
   168         // enter imported types immediately
   169         new Object() {
   170             Set<Symbol> processed = new HashSet<Symbol>();
   171             void importFrom(TypeSymbol tsym) {
   172                 if (tsym == null || !processed.add(tsym))
   173                     return;
   175                 // also import inherited names
   176                 importFrom(types.supertype(tsym.type).tsym);
   177                 for (Type t : types.interfaces(tsym.type))
   178                     importFrom(t.tsym);
   180                 final Scope fromScope = tsym.members();
   181                 for (Scope.Entry e = fromScope.elems; e != null; e = e.sibling) {
   182                     Symbol sym = e.sym;
   183                     if (sym.kind == TYP &&
   184                         (sym.flags() & STATIC) != 0 &&
   185                         staticImportAccessible(sym, packge) &&
   186                         sym.isMemberOf(origin, types) &&
   187                         !toScope.includes(sym))
   188                         toScope.enter(sym, fromScope, origin.members());
   189                 }
   190             }
   191         }.importFrom(tsym);
   193         // enter non-types before annotations that might use them
   194         annotate.earlier(new Annotate.Annotator() {
   195             Set<Symbol> processed = new HashSet<Symbol>();
   197             public String toString() {
   198                 return "import static " + tsym + ".*" + " in " + sourcefile;
   199             }
   200             void importFrom(TypeSymbol tsym) {
   201                 if (tsym == null || !processed.add(tsym))
   202                     return;
   204                 // also import inherited names
   205                 importFrom(types.supertype(tsym.type).tsym);
   206                 for (Type t : types.interfaces(tsym.type))
   207                     importFrom(t.tsym);
   209                 final Scope fromScope = tsym.members();
   210                 for (Scope.Entry e = fromScope.elems; e != null; e = e.sibling) {
   211                     Symbol sym = e.sym;
   212                     if (sym.isStatic() && sym.kind != TYP &&
   213                         staticImportAccessible(sym, packge) &&
   214                         !toScope.includes(sym) &&
   215                         sym.isMemberOf(origin, types)) {
   216                         toScope.enter(sym, fromScope, origin.members());
   217                     }
   218                 }
   219             }
   220             public void enterAnnotation() {
   221                 importFrom(tsym);
   222             }
   223         });
   224     }
   226     // is the sym accessible everywhere in packge?
   227     boolean staticImportAccessible(Symbol sym, PackageSymbol packge) {
   228         int flags = (int)(sym.flags() & AccessFlags);
   229         switch (flags) {
   230         default:
   231         case PUBLIC:
   232             return true;
   233         case PRIVATE:
   234             return false;
   235         case 0:
   236         case PROTECTED:
   237             return sym.packge() == packge;
   238         }
   239     }
   241     /** Import statics types of a given name.  Non-types are handled in Attr.
   242      *  @param pos           Position to be used for error reporting.
   243      *  @param tsym          The class from which the name is imported.
   244      *  @param name          The (simple) name being imported.
   245      *  @param env           The environment containing the named import
   246      *                  scope to add to.
   247      */
   248     private void importNamedStatic(final DiagnosticPosition pos,
   249                                    final TypeSymbol tsym,
   250                                    final Name name,
   251                                    final Env<AttrContext> env) {
   252         if (tsym.kind != TYP) {
   253             log.error(DiagnosticFlag.RECOVERABLE, pos, "static.imp.only.classes.and.interfaces");
   254             return;
   255         }
   257         final Scope toScope = env.toplevel.namedImportScope;
   258         final PackageSymbol packge = env.toplevel.packge;
   259         final TypeSymbol origin = tsym;
   261         // enter imported types immediately
   262         new Object() {
   263             Set<Symbol> processed = new HashSet<Symbol>();
   264             void importFrom(TypeSymbol tsym) {
   265                 if (tsym == null || !processed.add(tsym))
   266                     return;
   268                 // also import inherited names
   269                 importFrom(types.supertype(tsym.type).tsym);
   270                 for (Type t : types.interfaces(tsym.type))
   271                     importFrom(t.tsym);
   273                 for (Scope.Entry e = tsym.members().lookup(name);
   274                      e.scope != null;
   275                      e = e.next()) {
   276                     Symbol sym = e.sym;
   277                     if (sym.isStatic() &&
   278                         sym.kind == TYP &&
   279                         staticImportAccessible(sym, packge) &&
   280                         sym.isMemberOf(origin, types) &&
   281                         chk.checkUniqueStaticImport(pos, sym, toScope))
   282                         toScope.enter(sym, sym.owner.members(), origin.members());
   283                 }
   284             }
   285         }.importFrom(tsym);
   287         // enter non-types before annotations that might use them
   288         annotate.earlier(new Annotate.Annotator() {
   289             Set<Symbol> processed = new HashSet<Symbol>();
   290             boolean found = false;
   292             public String toString() {
   293                 return "import static " + tsym + "." + name;
   294             }
   295             void importFrom(TypeSymbol tsym) {
   296                 if (tsym == null || !processed.add(tsym))
   297                     return;
   299                 // also import inherited names
   300                 importFrom(types.supertype(tsym.type).tsym);
   301                 for (Type t : types.interfaces(tsym.type))
   302                     importFrom(t.tsym);
   304                 for (Scope.Entry e = tsym.members().lookup(name);
   305                      e.scope != null;
   306                      e = e.next()) {
   307                     Symbol sym = e.sym;
   308                     if (sym.isStatic() &&
   309                         staticImportAccessible(sym, packge) &&
   310                         sym.isMemberOf(origin, types)) {
   311                         found = true;
   312                         if (sym.kind == MTH ||
   313                             sym.kind != TYP && chk.checkUniqueStaticImport(pos, sym, toScope))
   314                             toScope.enter(sym, sym.owner.members(), origin.members());
   315                     }
   316                 }
   317             }
   318             public void enterAnnotation() {
   319                 JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   320                 try {
   321                     importFrom(tsym);
   322                     if (!found) {
   323                         log.error(pos, "cant.resolve.location",
   324                                   KindName.STATIC,
   325                                   name, List.<Type>nil(), List.<Type>nil(),
   326                                   Kinds.typeKindName(tsym.type),
   327                                   tsym.type);
   328                     }
   329                 } finally {
   330                     log.useSource(prev);
   331                 }
   332             }
   333         });
   334     }
   335     /** Import given class.
   336      *  @param pos           Position to be used for error reporting.
   337      *  @param tsym          The class to be imported.
   338      *  @param env           The environment containing the named import
   339      *                  scope to add to.
   340      */
   341     private void importNamed(DiagnosticPosition pos, Symbol tsym, Env<AttrContext> env) {
   342         if (tsym.kind == TYP &&
   343             chk.checkUniqueImport(pos, tsym, env.toplevel.namedImportScope))
   344             env.toplevel.namedImportScope.enter(tsym, tsym.owner.members());
   345     }
   347     /** Construct method type from method signature.
   348      *  @param typarams    The method's type parameters.
   349      *  @param params      The method's value parameters.
   350      *  @param res             The method's result type,
   351      *                 null if it is a constructor.
   352      *  @param recvparam       The method's receiver parameter,
   353      *                 null if none given; TODO: or already set here?
   354      *  @param thrown      The method's thrown exceptions.
   355      *  @param env             The method's (local) environment.
   356      */
   357     Type signature(List<JCTypeParameter> typarams,
   358                    List<JCVariableDecl> params,
   359                    JCTree res,
   360                    JCVariableDecl recvparam,
   361                    List<JCExpression> thrown,
   362                    Env<AttrContext> env) {
   364         // Enter and attribute type parameters.
   365         List<Type> tvars = enter.classEnter(typarams, env);
   366         attr.attribTypeVariables(typarams, env);
   368         // Enter and attribute value parameters.
   369         ListBuffer<Type> argbuf = new ListBuffer<Type>();
   370         for (List<JCVariableDecl> l = params; l.nonEmpty(); l = l.tail) {
   371             memberEnter(l.head, env);
   372             argbuf.append(l.head.vartype.type);
   373         }
   375         // Attribute result type, if one is given.
   376         Type restype = res == null ? syms.voidType : attr.attribType(res, env);
   378         // Attribute receiver type, if one is given.
   379         Type recvtype;
   380         if (recvparam!=null) {
   381             memberEnter(recvparam, env);
   382             recvtype = recvparam.vartype.type;
   383         } else {
   384             recvtype = null;
   385         }
   387         // Attribute thrown exceptions.
   388         ListBuffer<Type> thrownbuf = new ListBuffer<Type>();
   389         for (List<JCExpression> l = thrown; l.nonEmpty(); l = l.tail) {
   390             Type exc = attr.attribType(l.head, env);
   391             if (!exc.hasTag(TYPEVAR))
   392                 exc = chk.checkClassType(l.head.pos(), exc);
   393             thrownbuf.append(exc);
   394         }
   395         MethodType mtype = new MethodType(argbuf.toList(),
   396                                     restype,
   397                                     thrownbuf.toList(),
   398                                     syms.methodClass);
   399         mtype.recvtype = recvtype;
   401         return tvars.isEmpty() ? mtype : new ForAll(tvars, mtype);
   402     }
   404 /* ********************************************************************
   405  * Visitor methods for member enter
   406  *********************************************************************/
   408     /** Visitor argument: the current environment
   409      */
   410     protected Env<AttrContext> env;
   412     /** Enter field and method definitions and process import
   413      *  clauses, catching any completion failure exceptions.
   414      */
   415     protected void memberEnter(JCTree tree, Env<AttrContext> env) {
   416         Env<AttrContext> prevEnv = this.env;
   417         try {
   418             this.env = env;
   419             tree.accept(this);
   420         }  catch (CompletionFailure ex) {
   421             chk.completionError(tree.pos(), ex);
   422         } finally {
   423             this.env = prevEnv;
   424         }
   425     }
   427     /** Enter members from a list of trees.
   428      */
   429     void memberEnter(List<? extends JCTree> trees, Env<AttrContext> env) {
   430         for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail)
   431             memberEnter(l.head, env);
   432     }
   434     /** Enter members for a class.
   435      */
   436     void finishClass(JCClassDecl tree, Env<AttrContext> env) {
   437         if ((tree.mods.flags & Flags.ENUM) != 0 &&
   438             (types.supertype(tree.sym.type).tsym.flags() & Flags.ENUM) == 0) {
   439             addEnumMembers(tree, env);
   440         }
   441         memberEnter(tree.defs, env);
   442     }
   444     /** Add the implicit members for an enum type
   445      *  to the symbol table.
   446      */
   447     private void addEnumMembers(JCClassDecl tree, Env<AttrContext> env) {
   448         JCExpression valuesType = make.Type(new ArrayType(tree.sym.type, syms.arrayClass));
   450         // public static T[] values() { return ???; }
   451         JCMethodDecl values = make.
   452             MethodDef(make.Modifiers(Flags.PUBLIC|Flags.STATIC),
   453                       names.values,
   454                       valuesType,
   455                       List.<JCTypeParameter>nil(),
   456                       List.<JCVariableDecl>nil(),
   457                       List.<JCExpression>nil(), // thrown
   458                       null, //make.Block(0, Tree.emptyList.prepend(make.Return(make.Ident(names._null)))),
   459                       null);
   460         memberEnter(values, env);
   462         // public static T valueOf(String name) { return ???; }
   463         JCMethodDecl valueOf = make.
   464             MethodDef(make.Modifiers(Flags.PUBLIC|Flags.STATIC),
   465                       names.valueOf,
   466                       make.Type(tree.sym.type),
   467                       List.<JCTypeParameter>nil(),
   468                       List.of(make.VarDef(make.Modifiers(Flags.PARAMETER),
   469                                             names.fromString("name"),
   470                                             make.Type(syms.stringType), null)),
   471                       List.<JCExpression>nil(), // thrown
   472                       null, //make.Block(0, Tree.emptyList.prepend(make.Return(make.Ident(names._null)))),
   473                       null);
   474         memberEnter(valueOf, env);
   476         // the remaining members are for bootstrapping only
   477         if (!target.compilerBootstrap(tree.sym)) return;
   479         // public final int ordinal() { return ???; }
   480         JCMethodDecl ordinal = make.at(tree.pos).
   481             MethodDef(make.Modifiers(Flags.PUBLIC|Flags.FINAL),
   482                       names.ordinal,
   483                       make.Type(syms.intType),
   484                       List.<JCTypeParameter>nil(),
   485                       List.<JCVariableDecl>nil(),
   486                       List.<JCExpression>nil(),
   487                       null,
   488                       null);
   489         memberEnter(ordinal, env);
   491         // public final String name() { return ???; }
   492         JCMethodDecl name = make.
   493             MethodDef(make.Modifiers(Flags.PUBLIC|Flags.FINAL),
   494                       names._name,
   495                       make.Type(syms.stringType),
   496                       List.<JCTypeParameter>nil(),
   497                       List.<JCVariableDecl>nil(),
   498                       List.<JCExpression>nil(),
   499                       null,
   500                       null);
   501         memberEnter(name, env);
   503         // public int compareTo(E other) { return ???; }
   504         MethodSymbol compareTo = new
   505             MethodSymbol(Flags.PUBLIC,
   506                          names.compareTo,
   507                          new MethodType(List.of(tree.sym.type),
   508                                         syms.intType,
   509                                         List.<Type>nil(),
   510                                         syms.methodClass),
   511                          tree.sym);
   512         memberEnter(make.MethodDef(compareTo, null), env);
   513     }
   515     public void visitTopLevel(JCCompilationUnit tree) {
   516         if (tree.starImportScope.elems != null) {
   517             // we must have already processed this toplevel
   518             return;
   519         }
   521         // check that no class exists with same fully qualified name as
   522         // toplevel package
   523         if (checkClash && tree.pid != null) {
   524             Symbol p = tree.packge;
   525             while (p.owner != syms.rootPackage) {
   526                 p.owner.complete(); // enter all class members of p
   527                 if (syms.classes.get(p.getQualifiedName()) != null) {
   528                     log.error(tree.pos,
   529                               "pkg.clashes.with.class.of.same.name",
   530                               p);
   531                 }
   532                 p = p.owner;
   533             }
   534         }
   536         // process package annotations
   537         annotateLater(tree.packageAnnotations, env, tree.packge);
   539         // Import-on-demand java.lang.
   540         importAll(tree.pos, reader.enterPackage(names.java_lang), env);
   542         // Process all import clauses.
   543         memberEnter(tree.defs, env);
   544     }
   546     // process the non-static imports and the static imports of types.
   547     public void visitImport(JCImport tree) {
   548         JCFieldAccess imp = (JCFieldAccess)tree.qualid;
   549         Name name = TreeInfo.name(imp);
   551         // Create a local environment pointing to this tree to disable
   552         // effects of other imports in Resolve.findGlobalType
   553         Env<AttrContext> localEnv = env.dup(tree);
   555         TypeSymbol p = attr.attribImportQualifier(tree, localEnv).tsym;
   556         if (name == names.asterisk) {
   557             // Import on demand.
   558             chk.checkCanonical(imp.selected);
   559             if (tree.staticImport)
   560                 importStaticAll(tree.pos, p, env);
   561             else
   562                 importAll(tree.pos, p, env);
   563         } else {
   564             // Named type import.
   565             if (tree.staticImport) {
   566                 importNamedStatic(tree.pos(), p, name, localEnv);
   567                 chk.checkCanonical(imp.selected);
   568             } else {
   569                 TypeSymbol c = attribImportType(imp, localEnv).tsym;
   570                 chk.checkCanonical(imp);
   571                 importNamed(tree.pos(), c, env);
   572             }
   573         }
   574     }
   576     public void visitMethodDef(JCMethodDecl tree) {
   577         Scope enclScope = enter.enterScope(env);
   578         MethodSymbol m = new MethodSymbol(0, tree.name, null, enclScope.owner);
   579         m.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, m, tree);
   580         tree.sym = m;
   582         //if this is a default method, add the DEFAULT flag to the enclosing interface
   583         if ((tree.mods.flags & DEFAULT) != 0) {
   584             m.enclClass().flags_field |= DEFAULT;
   585         }
   587         Env<AttrContext> localEnv = methodEnv(tree, env);
   589         DeferredLintHandler prevLintHandler =
   590                 chk.setDeferredLintHandler(deferredLintHandler.setPos(tree.pos()));
   591         try {
   592             // Compute the method type
   593             m.type = signature(tree.typarams, tree.params,
   594                                tree.restype, tree.recvparam,
   595                                tree.thrown,
   596                                localEnv);
   597         } finally {
   598             chk.setDeferredLintHandler(prevLintHandler);
   599         }
   601         // Set m.params
   602         ListBuffer<VarSymbol> params = new ListBuffer<VarSymbol>();
   603         JCVariableDecl lastParam = null;
   604         for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) {
   605             JCVariableDecl param = lastParam = l.head;
   606             params.append(Assert.checkNonNull(param.sym));
   607         }
   608         m.params = params.toList();
   610         // mark the method varargs, if necessary
   611         if (lastParam != null && (lastParam.mods.flags & Flags.VARARGS) != 0)
   612             m.flags_field |= Flags.VARARGS;
   614         localEnv.info.scope.leave();
   615         if (chk.checkUnique(tree.pos(), m, enclScope)) {
   616             enclScope.enter(m);
   617         }
   618         annotateLater(tree.mods.annotations, localEnv, m);
   619         // Visit the signature of the method. Note that
   620         // TypeAnnotate doesn't descend into the body.
   621         typeAnnotate(tree, localEnv, m);
   623         if (tree.defaultValue != null)
   624             annotateDefaultValueLater(tree.defaultValue, localEnv, m);
   625     }
   627     /** Create a fresh environment for method bodies.
   628      *  @param tree     The method definition.
   629      *  @param env      The environment current outside of the method definition.
   630      */
   631     Env<AttrContext> methodEnv(JCMethodDecl tree, Env<AttrContext> env) {
   632         Env<AttrContext> localEnv =
   633             env.dup(tree, env.info.dup(env.info.scope.dupUnshared()));
   634         localEnv.enclMethod = tree;
   635         localEnv.info.scope.owner = tree.sym;
   636         if (tree.sym.type != null) {
   637             //when this is called in the enter stage, there's no type to be set
   638             localEnv.info.returnResult = attr.new ResultInfo(VAL, tree.sym.type.getReturnType());
   639         }
   640         if ((tree.mods.flags & STATIC) != 0) localEnv.info.staticLevel++;
   641         return localEnv;
   642     }
   644     public void visitVarDef(JCVariableDecl tree) {
   645         Env<AttrContext> localEnv = env;
   646         if ((tree.mods.flags & STATIC) != 0 ||
   647             (env.info.scope.owner.flags() & INTERFACE) != 0) {
   648             localEnv = env.dup(tree, env.info.dup());
   649             localEnv.info.staticLevel++;
   650         }
   651         DeferredLintHandler prevLintHandler =
   652                 chk.setDeferredLintHandler(deferredLintHandler.setPos(tree.pos()));
   653         try {
   654             if (TreeInfo.isEnumInit(tree)) {
   655                 attr.attribIdentAsEnumType(localEnv, (JCIdent)tree.vartype);
   656             } else {
   657                 attr.attribType(tree.vartype, localEnv);
   658             }
   659         } finally {
   660             chk.setDeferredLintHandler(prevLintHandler);
   661         }
   663         if ((tree.mods.flags & VARARGS) != 0) {
   664             //if we are entering a varargs parameter, we need to replace its type
   665             //(a plain array type) with the more precise VarargsType --- we need
   666             //to do it this way because varargs is represented in the tree as a modifier
   667             //on the parameter declaration, and not as a distinct type of array node.
   668             ArrayType atype = (ArrayType)tree.vartype.type.unannotatedType();
   669             tree.vartype.type = atype.makeVarargs();
   670         }
   671         Scope enclScope = enter.enterScope(env);
   672         VarSymbol v =
   673             new VarSymbol(0, tree.name, tree.vartype.type, enclScope.owner);
   674         v.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, v, tree);
   675         tree.sym = v;
   676         if (tree.init != null) {
   677             v.flags_field |= HASINIT;
   678             if ((v.flags_field & FINAL) != 0 &&
   679                     !tree.init.hasTag(NEWCLASS) &&
   680                     !tree.init.hasTag(LAMBDA)) {
   681                 Env<AttrContext> initEnv = getInitEnv(tree, env);
   682                 initEnv.info.enclVar = v;
   683                 v.setLazyConstValue(initEnv(tree, initEnv), attr, tree.init);
   684             }
   685         }
   686         if (chk.checkUnique(tree.pos(), v, enclScope)) {
   687             chk.checkTransparentVar(tree.pos(), v, enclScope);
   688             enclScope.enter(v);
   689         }
   690         annotateLater(tree.mods.annotations, localEnv, v);
   691         typeAnnotate(tree.vartype, env, tree.sym);
   692         annotate.flush();
   693         v.pos = tree.pos;
   694     }
   696     /** Create a fresh environment for a variable's initializer.
   697      *  If the variable is a field, the owner of the environment's scope
   698      *  is be the variable itself, otherwise the owner is the method
   699      *  enclosing the variable definition.
   700      *
   701      *  @param tree     The variable definition.
   702      *  @param env      The environment current outside of the variable definition.
   703      */
   704     Env<AttrContext> initEnv(JCVariableDecl tree, Env<AttrContext> env) {
   705         Env<AttrContext> localEnv = env.dupto(new AttrContextEnv(tree, env.info.dup()));
   706         if (tree.sym.owner.kind == TYP) {
   707             localEnv.info.scope = env.info.scope.dupUnshared();
   708             localEnv.info.scope.owner = tree.sym;
   709         }
   710         if ((tree.mods.flags & STATIC) != 0 ||
   711                 ((env.enclClass.sym.flags() & INTERFACE) != 0 && env.enclMethod == null))
   712             localEnv.info.staticLevel++;
   713         return localEnv;
   714     }
   716     /** Default member enter visitor method: do nothing
   717      */
   718     public void visitTree(JCTree tree) {
   719     }
   721     public void visitErroneous(JCErroneous tree) {
   722         if (tree.errs != null)
   723             memberEnter(tree.errs, env);
   724     }
   726     public Env<AttrContext> getMethodEnv(JCMethodDecl tree, Env<AttrContext> env) {
   727         Env<AttrContext> mEnv = methodEnv(tree, env);
   728         mEnv.info.lint = mEnv.info.lint.augment(tree.sym.annotations, tree.sym.flags());
   729         for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail)
   730             mEnv.info.scope.enterIfAbsent(l.head.type.tsym);
   731         for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail)
   732             mEnv.info.scope.enterIfAbsent(l.head.sym);
   733         return mEnv;
   734     }
   736     public Env<AttrContext> getInitEnv(JCVariableDecl tree, Env<AttrContext> env) {
   737         Env<AttrContext> iEnv = initEnv(tree, env);
   738         return iEnv;
   739     }
   741 /* ********************************************************************
   742  * Type completion
   743  *********************************************************************/
   745     Type attribImportType(JCTree tree, Env<AttrContext> env) {
   746         Assert.check(completionEnabled);
   747         try {
   748             // To prevent deep recursion, suppress completion of some
   749             // types.
   750             completionEnabled = false;
   751             return attr.attribType(tree, env);
   752         } finally {
   753             completionEnabled = true;
   754         }
   755     }
   757 /* ********************************************************************
   758  * Annotation processing
   759  *********************************************************************/
   761     /** Queue annotations for later processing. */
   762     void annotateLater(final List<JCAnnotation> annotations,
   763                        final Env<AttrContext> localEnv,
   764                        final Symbol s) {
   765         if (annotations.isEmpty()) {
   766             return;
   767         }
   768         if (s.kind != PCK) {
   769             s.annotations.reset(); // mark Annotations as incomplete for now
   770         }
   771         annotate.normal(new Annotate.Annotator() {
   772                 @Override
   773                 public String toString() {
   774                     return "annotate " + annotations + " onto " + s + " in " + s.owner;
   775                 }
   777                 @Override
   778                 public void enterAnnotation() {
   779                     Assert.check(s.kind == PCK || s.annotations.pendingCompletion());
   780                     JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile);
   781                     try {
   782                         if (!s.annotations.isEmpty() &&
   783                             annotations.nonEmpty())
   784                             log.error(annotations.head.pos,
   785                                       "already.annotated",
   786                                       kindName(s), s);
   787                         actualEnterAnnotations(annotations, localEnv, s);
   788                     } finally {
   789                         log.useSource(prev);
   790                     }
   791                 }
   792             });
   793     }
   795     /**
   796      * Check if a list of annotations contains a reference to
   797      * java.lang.Deprecated.
   798      **/
   799     private boolean hasDeprecatedAnnotation(List<JCAnnotation> annotations) {
   800         for (List<JCAnnotation> al = annotations; !al.isEmpty(); al = al.tail) {
   801             JCAnnotation a = al.head;
   802             if (a.annotationType.type == syms.deprecatedType && a.args.isEmpty())
   803                 return true;
   804         }
   805         return false;
   806     }
   808     /** Enter a set of annotations. */
   809     private void actualEnterAnnotations(List<JCAnnotation> annotations,
   810                           Env<AttrContext> env,
   811                           Symbol s) {
   812         Map<TypeSymbol, ListBuffer<Attribute.Compound>> annotated =
   813                 new LinkedHashMap<TypeSymbol, ListBuffer<Attribute.Compound>>();
   814         Map<Attribute.Compound, DiagnosticPosition> pos =
   815                 new HashMap<Attribute.Compound, DiagnosticPosition>();
   817         for (List<JCAnnotation> al = annotations; !al.isEmpty(); al = al.tail) {
   818             JCAnnotation a = al.head;
   819             Attribute.Compound c = annotate.enterAnnotation(a,
   820                                                             syms.annotationType,
   821                                                             env);
   822             if (c == null) {
   823                 continue;
   824             }
   826             if (annotated.containsKey(a.type.tsym)) {
   827                 if (source.allowRepeatedAnnotations()) {
   828                     ListBuffer<Attribute.Compound> l = annotated.get(a.type.tsym);
   829                     l = l.append(c);
   830                     annotated.put(a.type.tsym, l);
   831                     pos.put(c, a.pos());
   832                 } else {
   833                     log.error(a.pos(), "duplicate.annotation");
   834                 }
   835             } else {
   836                 annotated.put(a.type.tsym, ListBuffer.of(c));
   837                 pos.put(c, a.pos());
   838             }
   840             // Note: @Deprecated has no effect on local variables and parameters
   841             if (!c.type.isErroneous()
   842                 && s.owner.kind != MTH
   843                 && types.isSameType(c.type, syms.deprecatedType)) {
   844                 s.flags_field |= Flags.DEPRECATED;
   845             }
   846         }
   848         s.annotations.setDeclarationAttributesWithCompletion(
   849                 annotate.new AnnotateRepeatedContext<Attribute.Compound>(env, annotated, pos, log, false));
   850     }
   852     /** Queue processing of an attribute default value. */
   853     void annotateDefaultValueLater(final JCExpression defaultValue,
   854                                    final Env<AttrContext> localEnv,
   855                                    final MethodSymbol m) {
   856         annotate.normal(new Annotate.Annotator() {
   857                 @Override
   858                 public String toString() {
   859                     return "annotate " + m.owner + "." +
   860                         m + " default " + defaultValue;
   861                 }
   863                 @Override
   864                 public void enterAnnotation() {
   865                     JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile);
   866                     try {
   867                         enterDefaultValue(defaultValue, localEnv, m);
   868                     } finally {
   869                         log.useSource(prev);
   870                     }
   871                 }
   872             });
   873     }
   875     /** Enter a default value for an attribute method. */
   876     private void enterDefaultValue(final JCExpression defaultValue,
   877                                    final Env<AttrContext> localEnv,
   878                                    final MethodSymbol m) {
   879         m.defaultValue = annotate.enterAttributeValue(m.type.getReturnType(),
   880                                                       defaultValue,
   881                                                       localEnv);
   882     }
   884 /* ********************************************************************
   885  * Source completer
   886  *********************************************************************/
   888     /** Complete entering a class.
   889      *  @param sym         The symbol of the class to be completed.
   890      */
   891     public void complete(Symbol sym) throws CompletionFailure {
   892         // Suppress some (recursive) MemberEnter invocations
   893         if (!completionEnabled) {
   894             // Re-install same completer for next time around and return.
   895             Assert.check((sym.flags() & Flags.COMPOUND) == 0);
   896             sym.completer = this;
   897             return;
   898         }
   900         ClassSymbol c = (ClassSymbol)sym;
   901         ClassType ct = (ClassType)c.type;
   902         Env<AttrContext> env = enter.typeEnvs.get(c);
   903         JCClassDecl tree = (JCClassDecl)env.tree;
   904         boolean wasFirst = isFirst;
   905         isFirst = false;
   907         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
   908         try {
   909             // Save class environment for later member enter (2) processing.
   910             halfcompleted.append(env);
   912             // Mark class as not yet attributed.
   913             c.flags_field |= UNATTRIBUTED;
   915             // If this is a toplevel-class, make sure any preceding import
   916             // clauses have been seen.
   917             if (c.owner.kind == PCK) {
   918                 memberEnter(env.toplevel, env.enclosing(TOPLEVEL));
   919                 todo.append(env);
   920             }
   922             if (c.owner.kind == TYP)
   923                 c.owner.complete();
   925             // create an environment for evaluating the base clauses
   926             Env<AttrContext> baseEnv = baseEnv(tree, env);
   928             if (tree.extending != null)
   929                 typeAnnotate(tree.extending, baseEnv, sym);
   930             for (JCExpression impl : tree.implementing)
   931                 typeAnnotate(impl, baseEnv, sym);
   932             annotate.flush();
   934             // Determine supertype.
   935             Type supertype =
   936                 (tree.extending != null)
   937                 ? attr.attribBase(tree.extending, baseEnv, true, false, true)
   938                 : ((tree.mods.flags & Flags.ENUM) != 0 && !target.compilerBootstrap(c))
   939                 ? attr.attribBase(enumBase(tree.pos, c), baseEnv,
   940                                   true, false, false)
   941                 : (c.fullname == names.java_lang_Object)
   942                 ? Type.noType
   943                 : syms.objectType;
   944             ct.supertype_field = modelMissingTypes(supertype, tree.extending, false);
   946             // Determine interfaces.
   947             ListBuffer<Type> interfaces = new ListBuffer<Type>();
   948             ListBuffer<Type> all_interfaces = null; // lazy init
   949             Set<Type> interfaceSet = new HashSet<Type>();
   950             List<JCExpression> interfaceTrees = tree.implementing;
   951             if ((tree.mods.flags & Flags.ENUM) != 0 && target.compilerBootstrap(c)) {
   952                 // add interface Comparable<T>
   953                 interfaceTrees =
   954                     interfaceTrees.prepend(make.Type(new ClassType(syms.comparableType.getEnclosingType(),
   955                                                                    List.of(c.type),
   956                                                                    syms.comparableType.tsym)));
   957                 // add interface Serializable
   958                 interfaceTrees =
   959                     interfaceTrees.prepend(make.Type(syms.serializableType));
   960             }
   961             for (JCExpression iface : interfaceTrees) {
   962                 Type i = attr.attribBase(iface, baseEnv, false, true, true);
   963                 if (i.hasTag(CLASS)) {
   964                     interfaces.append(i);
   965                     if (all_interfaces != null) all_interfaces.append(i);
   966                     chk.checkNotRepeated(iface.pos(), types.erasure(i), interfaceSet);
   967                 } else {
   968                     if (all_interfaces == null)
   969                         all_interfaces = new ListBuffer<Type>().appendList(interfaces);
   970                     all_interfaces.append(modelMissingTypes(i, iface, true));
   971                 }
   972             }
   973             if ((c.flags_field & ANNOTATION) != 0) {
   974                 ct.interfaces_field = List.of(syms.annotationType);
   975                 ct.all_interfaces_field = ct.interfaces_field;
   976             }  else {
   977                 ct.interfaces_field = interfaces.toList();
   978                 ct.all_interfaces_field = (all_interfaces == null)
   979                         ? ct.interfaces_field : all_interfaces.toList();
   980             }
   982             if (c.fullname == names.java_lang_Object) {
   983                 if (tree.extending != null) {
   984                     chk.checkNonCyclic(tree.extending.pos(),
   985                                        supertype);
   986                     ct.supertype_field = Type.noType;
   987                 }
   988                 else if (tree.implementing.nonEmpty()) {
   989                     chk.checkNonCyclic(tree.implementing.head.pos(),
   990                                        ct.interfaces_field.head);
   991                     ct.interfaces_field = List.nil();
   992                 }
   993             }
   995             // Annotations.
   996             // In general, we cannot fully process annotations yet,  but we
   997             // can attribute the annotation types and then check to see if the
   998             // @Deprecated annotation is present.
   999             attr.attribAnnotationTypes(tree.mods.annotations, baseEnv);
  1000             if (hasDeprecatedAnnotation(tree.mods.annotations))
  1001                 c.flags_field |= DEPRECATED;
  1002             annotateLater(tree.mods.annotations, baseEnv, c);
  1003             // class type parameters use baseEnv but everything uses env
  1005             chk.checkNonCyclicDecl(tree);
  1007             attr.attribTypeVariables(tree.typarams, baseEnv);
  1008             // Do this here, where we have the symbol.
  1009             for (JCTypeParameter tp : tree.typarams)
  1010                 typeAnnotate(tp, baseEnv, sym);
  1011             annotate.flush();
  1013             // Add default constructor if needed.
  1014             if ((c.flags() & INTERFACE) == 0 &&
  1015                 !TreeInfo.hasConstructors(tree.defs)) {
  1016                 List<Type> argtypes = List.nil();
  1017                 List<Type> typarams = List.nil();
  1018                 List<Type> thrown = List.nil();
  1019                 long ctorFlags = 0;
  1020                 boolean based = false;
  1021                 boolean addConstructor = true;
  1022                 if (c.name.isEmpty()) {
  1023                     JCNewClass nc = (JCNewClass)env.next.tree;
  1024                     if (nc.constructor != null) {
  1025                         addConstructor = nc.constructor.kind != ERR;
  1026                         Type superConstrType = types.memberType(c.type,
  1027                                                                 nc.constructor);
  1028                         argtypes = superConstrType.getParameterTypes();
  1029                         typarams = superConstrType.getTypeArguments();
  1030                         ctorFlags = nc.constructor.flags() & VARARGS;
  1031                         if (nc.encl != null) {
  1032                             argtypes = argtypes.prepend(nc.encl.type);
  1033                             based = true;
  1035                         thrown = superConstrType.getThrownTypes();
  1038                 if (addConstructor) {
  1039                     JCTree constrDef = DefaultConstructor(make.at(tree.pos), c,
  1040                                                         typarams, argtypes, thrown,
  1041                                                         ctorFlags, based);
  1042                     tree.defs = tree.defs.prepend(constrDef);
  1046             // enter symbols for 'this' into current scope.
  1047             VarSymbol thisSym =
  1048                 new VarSymbol(FINAL | HASINIT, names._this, c.type, c);
  1049             thisSym.pos = Position.FIRSTPOS;
  1050             env.info.scope.enter(thisSym);
  1051             // if this is a class, enter symbol for 'super' into current scope.
  1052             if ((c.flags_field & INTERFACE) == 0 &&
  1053                     ct.supertype_field.hasTag(CLASS)) {
  1054                 VarSymbol superSym =
  1055                     new VarSymbol(FINAL | HASINIT, names._super,
  1056                                   ct.supertype_field, c);
  1057                 superSym.pos = Position.FIRSTPOS;
  1058                 env.info.scope.enter(superSym);
  1061             // check that no package exists with same fully qualified name,
  1062             // but admit classes in the unnamed package which have the same
  1063             // name as a top-level package.
  1064             if (checkClash &&
  1065                 c.owner.kind == PCK && c.owner != syms.unnamedPackage &&
  1066                 reader.packageExists(c.fullname)) {
  1067                 log.error(tree.pos, "clash.with.pkg.of.same.name", Kinds.kindName(sym), c);
  1069             if (c.owner.kind == PCK && (c.flags_field & PUBLIC) == 0 &&
  1070                 !env.toplevel.sourcefile.isNameCompatible(c.name.toString(),JavaFileObject.Kind.SOURCE)) {
  1071                 c.flags_field |= AUXILIARY;
  1073         } catch (CompletionFailure ex) {
  1074             chk.completionError(tree.pos(), ex);
  1075         } finally {
  1076             log.useSource(prev);
  1079         // Enter all member fields and methods of a set of half completed
  1080         // classes in a second phase.
  1081         if (wasFirst) {
  1082             try {
  1083                 while (halfcompleted.nonEmpty()) {
  1084                     finish(halfcompleted.next());
  1086             } finally {
  1087                 isFirst = true;
  1090         annotate.afterRepeated(TypeAnnotations.organizeTypeAnnotationsSignatures(syms, names, log, tree));
  1093     private void actualEnterTypeAnnotations(final List<JCAnnotation> annotations,
  1094             final Env<AttrContext> env,
  1095             final Symbol s) {
  1096         Map<TypeSymbol, ListBuffer<Attribute.TypeCompound>> annotated =
  1097                 new LinkedHashMap<TypeSymbol, ListBuffer<Attribute.TypeCompound>>();
  1098         Map<Attribute.TypeCompound, DiagnosticPosition> pos =
  1099                 new HashMap<Attribute.TypeCompound, DiagnosticPosition>();
  1101         for (List<JCAnnotation> al = annotations; !al.isEmpty(); al = al.tail) {
  1102             JCAnnotation a = al.head;
  1103             Attribute.TypeCompound tc = annotate.enterTypeAnnotation(a,
  1104                     syms.annotationType,
  1105                     env);
  1106             if (tc == null) {
  1107                 continue;
  1110             if (annotated.containsKey(a.type.tsym)) {
  1111                 if (source.allowRepeatedAnnotations()) {
  1112                     ListBuffer<Attribute.TypeCompound> l = annotated.get(a.type.tsym);
  1113                     l = l.append(tc);
  1114                     annotated.put(a.type.tsym, l);
  1115                     pos.put(tc, a.pos());
  1116                 } else {
  1117                     log.error(a.pos(), "duplicate.annotation");
  1119             } else {
  1120                 annotated.put(a.type.tsym, ListBuffer.of(tc));
  1121                 pos.put(tc, a.pos());
  1125         s.annotations.appendTypeAttributesWithCompletion(
  1126                 annotate.new AnnotateRepeatedContext<Attribute.TypeCompound>(env, annotated, pos, log, true));
  1129     public void typeAnnotate(final JCTree tree, final Env<AttrContext> env, final Symbol sym) {
  1130         tree.accept(new TypeAnnotate(env, sym));
  1133     /**
  1134      * We need to use a TreeScanner, because it is not enough to visit the top-level
  1135      * annotations. We also need to visit type arguments, etc.
  1136      */
  1137     private class TypeAnnotate extends TreeScanner {
  1138         private Env<AttrContext> env;
  1139         private Symbol sym;
  1141         public TypeAnnotate(final Env<AttrContext> env, final Symbol sym) {
  1142             this.env = env;
  1143             this.sym = sym;
  1146         void annotateTypeLater(final List<JCAnnotation> annotations) {
  1147             if (annotations.isEmpty()) {
  1148                 return;
  1151             annotate.normal(new Annotate.Annotator() {
  1152                 @Override
  1153                 public String toString() {
  1154                     return "type annotate " + annotations + " onto " + sym + " in " + sym.owner;
  1156                 @Override
  1157                 public void enterAnnotation() {
  1158                     JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
  1159                     try {
  1160                         actualEnterTypeAnnotations(annotations, env, sym);
  1161                     } finally {
  1162                         log.useSource(prev);
  1165             });
  1168         @Override
  1169         public void visitAnnotatedType(final JCAnnotatedType tree) {
  1170             annotateTypeLater(tree.annotations);
  1171             super.visitAnnotatedType(tree);
  1174         @Override
  1175         public void visitTypeParameter(final JCTypeParameter tree) {
  1176             annotateTypeLater(tree.annotations);
  1177             super.visitTypeParameter(tree);
  1180         @Override
  1181         public void visitNewArray(final JCNewArray tree) {
  1182             annotateTypeLater(tree.annotations);
  1183             for (List<JCAnnotation> dimAnnos : tree.dimAnnotations)
  1184                 annotateTypeLater(dimAnnos);
  1185             super.visitNewArray(tree);
  1188         @Override
  1189         public void visitMethodDef(final JCMethodDecl tree) {
  1190             scan(tree.mods);
  1191             scan(tree.restype);
  1192             scan(tree.typarams);
  1193             scan(tree.recvparam);
  1194             scan(tree.params);
  1195             scan(tree.thrown);
  1196             scan(tree.defaultValue);
  1197             // Do not annotate the body, just the signature.
  1198             // scan(tree.body);
  1203     private Env<AttrContext> baseEnv(JCClassDecl tree, Env<AttrContext> env) {
  1204         Scope baseScope = new Scope(tree.sym);
  1205         //import already entered local classes into base scope
  1206         for (Scope.Entry e = env.outer.info.scope.elems ; e != null ; e = e.sibling) {
  1207             if (e.sym.isLocal()) {
  1208                 baseScope.enter(e.sym);
  1211         //import current type-parameters into base scope
  1212         if (tree.typarams != null)
  1213             for (List<JCTypeParameter> typarams = tree.typarams;
  1214                  typarams.nonEmpty();
  1215                  typarams = typarams.tail)
  1216                 baseScope.enter(typarams.head.type.tsym);
  1217         Env<AttrContext> outer = env.outer; // the base clause can't see members of this class
  1218         Env<AttrContext> localEnv = outer.dup(tree, outer.info.dup(baseScope));
  1219         localEnv.baseClause = true;
  1220         localEnv.outer = outer;
  1221         localEnv.info.isSelfCall = false;
  1222         return localEnv;
  1225     /** Enter member fields and methods of a class
  1226      *  @param env        the environment current for the class block.
  1227      */
  1228     private void finish(Env<AttrContext> env) {
  1229         JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
  1230         try {
  1231             JCClassDecl tree = (JCClassDecl)env.tree;
  1232             finishClass(tree, env);
  1233         } finally {
  1234             log.useSource(prev);
  1238     /** Generate a base clause for an enum type.
  1239      *  @param pos              The position for trees and diagnostics, if any
  1240      *  @param c                The class symbol of the enum
  1241      */
  1242     private JCExpression enumBase(int pos, ClassSymbol c) {
  1243         JCExpression result = make.at(pos).
  1244             TypeApply(make.QualIdent(syms.enumSym),
  1245                       List.<JCExpression>of(make.Type(c.type)));
  1246         return result;
  1249     Type modelMissingTypes(Type t, final JCExpression tree, final boolean interfaceExpected) {
  1250         if (!t.hasTag(ERROR))
  1251             return t;
  1253         return new ErrorType(((ErrorType) t).getOriginalType(), t.tsym) {
  1254             private Type modelType;
  1256             @Override
  1257             public Type getModelType() {
  1258                 if (modelType == null)
  1259                     modelType = new Synthesizer(getOriginalType(), interfaceExpected).visit(tree);
  1260                 return modelType;
  1262         };
  1264     // where
  1265     private class Synthesizer extends JCTree.Visitor {
  1266         Type originalType;
  1267         boolean interfaceExpected;
  1268         List<ClassSymbol> synthesizedSymbols = List.nil();
  1269         Type result;
  1271         Synthesizer(Type originalType, boolean interfaceExpected) {
  1272             this.originalType = originalType;
  1273             this.interfaceExpected = interfaceExpected;
  1276         Type visit(JCTree tree) {
  1277             tree.accept(this);
  1278             return result;
  1281         List<Type> visit(List<? extends JCTree> trees) {
  1282             ListBuffer<Type> lb = new ListBuffer<Type>();
  1283             for (JCTree t: trees)
  1284                 lb.append(visit(t));
  1285             return lb.toList();
  1288         @Override
  1289         public void visitTree(JCTree tree) {
  1290             result = syms.errType;
  1293         @Override
  1294         public void visitIdent(JCIdent tree) {
  1295             if (!tree.type.hasTag(ERROR)) {
  1296                 result = tree.type;
  1297             } else {
  1298                 result = synthesizeClass(tree.name, syms.unnamedPackage).type;
  1302         @Override
  1303         public void visitSelect(JCFieldAccess tree) {
  1304             if (!tree.type.hasTag(ERROR)) {
  1305                 result = tree.type;
  1306             } else {
  1307                 Type selectedType;
  1308                 boolean prev = interfaceExpected;
  1309                 try {
  1310                     interfaceExpected = false;
  1311                     selectedType = visit(tree.selected);
  1312                 } finally {
  1313                     interfaceExpected = prev;
  1315                 ClassSymbol c = synthesizeClass(tree.name, selectedType.tsym);
  1316                 result = c.type;
  1320         @Override
  1321         public void visitTypeApply(JCTypeApply tree) {
  1322             if (!tree.type.hasTag(ERROR)) {
  1323                 result = tree.type;
  1324             } else {
  1325                 ClassType clazzType = (ClassType) visit(tree.clazz);
  1326                 if (synthesizedSymbols.contains(clazzType.tsym))
  1327                     synthesizeTyparams((ClassSymbol) clazzType.tsym, tree.arguments.size());
  1328                 final List<Type> actuals = visit(tree.arguments);
  1329                 result = new ErrorType(tree.type, clazzType.tsym) {
  1330                     @Override
  1331                     public List<Type> getTypeArguments() {
  1332                         return actuals;
  1334                 };
  1338         ClassSymbol synthesizeClass(Name name, Symbol owner) {
  1339             int flags = interfaceExpected ? INTERFACE : 0;
  1340             ClassSymbol c = new ClassSymbol(flags, name, owner);
  1341             c.members_field = new Scope.ErrorScope(c);
  1342             c.type = new ErrorType(originalType, c) {
  1343                 @Override
  1344                 public List<Type> getTypeArguments() {
  1345                     return typarams_field;
  1347             };
  1348             synthesizedSymbols = synthesizedSymbols.prepend(c);
  1349             return c;
  1352         void synthesizeTyparams(ClassSymbol sym, int n) {
  1353             ClassType ct = (ClassType) sym.type;
  1354             Assert.check(ct.typarams_field.isEmpty());
  1355             if (n == 1) {
  1356                 TypeVar v = new TypeVar(names.fromString("T"), sym, syms.botType);
  1357                 ct.typarams_field = ct.typarams_field.prepend(v);
  1358             } else {
  1359                 for (int i = n; i > 0; i--) {
  1360                     TypeVar v = new TypeVar(names.fromString("T" + i), sym, syms.botType);
  1361                     ct.typarams_field = ct.typarams_field.prepend(v);
  1368 /* ***************************************************************************
  1369  * tree building
  1370  ****************************************************************************/
  1372     /** Generate default constructor for given class. For classes different
  1373      *  from java.lang.Object, this is:
  1375      *    c(argtype_0 x_0, ..., argtype_n x_n) throws thrown {
  1376      *      super(x_0, ..., x_n)
  1377      *    }
  1379      *  or, if based == true:
  1381      *    c(argtype_0 x_0, ..., argtype_n x_n) throws thrown {
  1382      *      x_0.super(x_1, ..., x_n)
  1383      *    }
  1385      *  @param make     The tree factory.
  1386      *  @param c        The class owning the default constructor.
  1387      *  @param argtypes The parameter types of the constructor.
  1388      *  @param thrown   The thrown exceptions of the constructor.
  1389      *  @param based    Is first parameter a this$n?
  1390      */
  1391     JCTree DefaultConstructor(TreeMaker make,
  1392                             ClassSymbol c,
  1393                             List<Type> typarams,
  1394                             List<Type> argtypes,
  1395                             List<Type> thrown,
  1396                             long flags,
  1397                             boolean based) {
  1398         List<JCVariableDecl> params = make.Params(argtypes, syms.noSymbol);
  1399         List<JCStatement> stats = List.nil();
  1400         if (c.type != syms.objectType)
  1401             stats = stats.prepend(SuperCall(make, typarams, params, based));
  1402         if ((c.flags() & ENUM) != 0 &&
  1403             (types.supertype(c.type).tsym == syms.enumSym ||
  1404              target.compilerBootstrap(c))) {
  1405             // constructors of true enums are private
  1406             flags = (flags & ~AccessFlags) | PRIVATE | GENERATEDCONSTR;
  1407         } else
  1408             flags |= (c.flags() & AccessFlags) | GENERATEDCONSTR;
  1409         if (c.name.isEmpty()) flags |= ANONCONSTR;
  1410         JCTree result = make.MethodDef(
  1411             make.Modifiers(flags),
  1412             names.init,
  1413             null,
  1414             make.TypeParams(typarams),
  1415             params,
  1416             make.Types(thrown),
  1417             make.Block(0, stats),
  1418             null);
  1419         return result;
  1422     /** Generate call to superclass constructor. This is:
  1424      *    super(id_0, ..., id_n)
  1426      * or, if based == true
  1428      *    id_0.super(id_1,...,id_n)
  1430      *  where id_0, ..., id_n are the names of the given parameters.
  1432      *  @param make    The tree factory
  1433      *  @param params  The parameters that need to be passed to super
  1434      *  @param typarams  The type parameters that need to be passed to super
  1435      *  @param based   Is first parameter a this$n?
  1436      */
  1437     JCExpressionStatement SuperCall(TreeMaker make,
  1438                    List<Type> typarams,
  1439                    List<JCVariableDecl> params,
  1440                    boolean based) {
  1441         JCExpression meth;
  1442         if (based) {
  1443             meth = make.Select(make.Ident(params.head), names._super);
  1444             params = params.tail;
  1445         } else {
  1446             meth = make.Ident(names._super);
  1448         List<JCExpression> typeargs = typarams.nonEmpty() ? make.Types(typarams) : null;
  1449         return make.Exec(make.Apply(typeargs, meth, make.Idents(params)));

mercurial