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

Thu, 29 Jul 2010 15:56:25 +0100

author
mcimadamore
date
Thu, 29 Jul 2010 15:56:25 +0100
changeset 615
36c4ec4525b4
parent 581
f2fdd52e4e87
child 657
70ebdef189c9
permissions
-rw-r--r--

6938454: Unable to determine generic type in program that compiles under Java 6
Summary: a redundant dubtyping check causes spurious inference failure
Reviewed-by: jjg

     1 /*
     2  * Copyright (c) 1999, 2008, 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.*;
    29 import javax.tools.JavaFileObject;
    30 import javax.tools.JavaFileManager;
    32 import com.sun.tools.javac.code.*;
    33 import com.sun.tools.javac.jvm.*;
    34 import com.sun.tools.javac.tree.*;
    35 import com.sun.tools.javac.util.*;
    36 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    37 import com.sun.tools.javac.util.List;
    39 import com.sun.tools.javac.code.Type.*;
    40 import com.sun.tools.javac.code.Symbol.*;
    41 import com.sun.tools.javac.tree.JCTree.*;
    43 import static com.sun.tools.javac.code.Flags.*;
    44 import static com.sun.tools.javac.code.Kinds.*;
    46 /** This class enters symbols for all encountered definitions into
    47  *  the symbol table. The pass consists of two phases, organized as
    48  *  follows:
    49  *
    50  *  <p>In the first phase, all class symbols are intered into their
    51  *  enclosing scope, descending recursively down the tree for classes
    52  *  which are members of other classes. The class symbols are given a
    53  *  MemberEnter object as completer.
    54  *
    55  *  <p>In the second phase classes are completed using
    56  *  MemberEnter.complete().  Completion might occur on demand, but
    57  *  any classes that are not completed that way will be eventually
    58  *  completed by processing the `uncompleted' queue.  Completion
    59  *  entails (1) determination of a class's parameters, supertype and
    60  *  interfaces, as well as (2) entering all symbols defined in the
    61  *  class into its scope, with the exception of class symbols which
    62  *  have been entered in phase 1.  (2) depends on (1) having been
    63  *  completed for a class and all its superclasses and enclosing
    64  *  classes. That's why, after doing (1), we put classes in a
    65  *  `halfcompleted' queue. Only when we have performed (1) for a class
    66  *  and all it's superclasses and enclosing classes, we proceed to
    67  *  (2).
    68  *
    69  *  <p>Whereas the first phase is organized as a sweep through all
    70  *  compiled syntax trees, the second phase is demand. Members of a
    71  *  class are entered when the contents of a class are first
    72  *  accessed. This is accomplished by installing completer objects in
    73  *  class symbols for compiled classes which invoke the member-enter
    74  *  phase for the corresponding class tree.
    75  *
    76  *  <p>Classes migrate from one phase to the next via queues:
    77  *
    78  *  <pre>
    79  *  class enter -> (Enter.uncompleted)         --> member enter (1)
    80  *              -> (MemberEnter.halfcompleted) --> member enter (2)
    81  *              -> (Todo)                      --> attribute
    82  *                                              (only for toplevel classes)
    83  *  </pre>
    84  *
    85  *  <p><b>This is NOT part of any supported API.
    86  *  If you write code that depends on this, you do so at your own risk.
    87  *  This code and its internal interfaces are subject to change or
    88  *  deletion without notice.</b>
    89  */
    90 public class Enter extends JCTree.Visitor {
    91     protected static final Context.Key<Enter> enterKey =
    92         new Context.Key<Enter>();
    94     Log log;
    95     Symtab syms;
    96     Check chk;
    97     TreeMaker make;
    98     ClassReader reader;
    99     Annotate annotate;
   100     MemberEnter memberEnter;
   101     Types types;
   102     Lint lint;
   103     Names names;
   104     JavaFileManager fileManager;
   106     private final Todo todo;
   108     public static Enter instance(Context context) {
   109         Enter instance = context.get(enterKey);
   110         if (instance == null)
   111             instance = new Enter(context);
   112         return instance;
   113     }
   115     protected Enter(Context context) {
   116         context.put(enterKey, this);
   118         log = Log.instance(context);
   119         reader = ClassReader.instance(context);
   120         make = TreeMaker.instance(context);
   121         syms = Symtab.instance(context);
   122         chk = Check.instance(context);
   123         memberEnter = MemberEnter.instance(context);
   124         types = Types.instance(context);
   125         annotate = Annotate.instance(context);
   126         lint = Lint.instance(context);
   127         names = Names.instance(context);
   129         predefClassDef = make.ClassDef(
   130             make.Modifiers(PUBLIC),
   131             syms.predefClass.name, null, null, null, null);
   132         predefClassDef.sym = syms.predefClass;
   133         todo = Todo.instance(context);
   134         fileManager = context.get(JavaFileManager.class);
   135     }
   137     /** A hashtable mapping classes and packages to the environments current
   138      *  at the points of their definitions.
   139      */
   140     Map<TypeSymbol,Env<AttrContext>> typeEnvs =
   141             new HashMap<TypeSymbol,Env<AttrContext>>();
   143     /** Accessor for typeEnvs
   144      */
   145     public Env<AttrContext> getEnv(TypeSymbol sym) {
   146         return typeEnvs.get(sym);
   147     }
   149     public Env<AttrContext> getClassEnv(TypeSymbol sym) {
   150         Env<AttrContext> localEnv = getEnv(sym);
   151         Env<AttrContext> lintEnv = localEnv;
   152         while (lintEnv.info.lint == null)
   153             lintEnv = lintEnv.next;
   154         localEnv.info.lint = lintEnv.info.lint.augment(sym.attributes_field, sym.flags());
   155         return localEnv;
   156     }
   158     /** The queue of all classes that might still need to be completed;
   159      *  saved and initialized by main().
   160      */
   161     ListBuffer<ClassSymbol> uncompleted;
   163     /** A dummy class to serve as enclClass for toplevel environments.
   164      */
   165     private JCClassDecl predefClassDef;
   167 /* ************************************************************************
   168  * environment construction
   169  *************************************************************************/
   172     /** Create a fresh environment for class bodies.
   173      *  This will create a fresh scope for local symbols of a class, referred
   174      *  to by the environments info.scope field.
   175      *  This scope will contain
   176      *    - symbols for this and super
   177      *    - symbols for any type parameters
   178      *  In addition, it serves as an anchor for scopes of methods and initializers
   179      *  which are nested in this scope via Scope.dup().
   180      *  This scope should not be confused with the members scope of a class.
   181      *
   182      *  @param tree     The class definition.
   183      *  @param env      The environment current outside of the class definition.
   184      */
   185     public Env<AttrContext> classEnv(JCClassDecl tree, Env<AttrContext> env) {
   186         Env<AttrContext> localEnv =
   187             env.dup(tree, env.info.dup(new Scope(tree.sym)));
   188         localEnv.enclClass = tree;
   189         localEnv.outer = env;
   190         localEnv.info.isSelfCall = false;
   191         localEnv.info.lint = null; // leave this to be filled in by Attr,
   192                                    // when annotations have been processed
   193         return localEnv;
   194     }
   196     /** Create a fresh environment for toplevels.
   197      *  @param tree     The toplevel tree.
   198      */
   199     Env<AttrContext> topLevelEnv(JCCompilationUnit tree) {
   200         Env<AttrContext> localEnv = new Env<AttrContext>(tree, new AttrContext());
   201         localEnv.toplevel = tree;
   202         localEnv.enclClass = predefClassDef;
   203         tree.namedImportScope = new Scope.ImportScope(tree.packge);
   204         tree.starImportScope = new Scope.ImportScope(tree.packge);
   205         localEnv.info.scope = tree.namedImportScope;
   206         localEnv.info.lint = lint;
   207         return localEnv;
   208     }
   210     public Env<AttrContext> getTopLevelEnv(JCCompilationUnit tree) {
   211         Env<AttrContext> localEnv = new Env<AttrContext>(tree, new AttrContext());
   212         localEnv.toplevel = tree;
   213         localEnv.enclClass = predefClassDef;
   214         localEnv.info.scope = tree.namedImportScope;
   215         localEnv.info.lint = lint;
   216         return localEnv;
   217     }
   219     /** The scope in which a member definition in environment env is to be entered
   220      *  This is usually the environment's scope, except for class environments,
   221      *  where the local scope is for type variables, and the this and super symbol
   222      *  only, and members go into the class member scope.
   223      */
   224     Scope enterScope(Env<AttrContext> env) {
   225         return (env.tree.getTag() == JCTree.CLASSDEF)
   226             ? ((JCClassDecl) env.tree).sym.members_field
   227             : env.info.scope;
   228     }
   230 /* ************************************************************************
   231  * Visitor methods for phase 1: class enter
   232  *************************************************************************/
   234     /** Visitor argument: the current environment.
   235      */
   236     protected Env<AttrContext> env;
   238     /** Visitor result: the computed type.
   239      */
   240     Type result;
   242     /** Visitor method: enter all classes in given tree, catching any
   243      *  completion failure exceptions. Return the tree's type.
   244      *
   245      *  @param tree    The tree to be visited.
   246      *  @param env     The environment visitor argument.
   247      */
   248     Type classEnter(JCTree tree, Env<AttrContext> env) {
   249         Env<AttrContext> prevEnv = this.env;
   250         try {
   251             this.env = env;
   252             tree.accept(this);
   253             return result;
   254         }  catch (CompletionFailure ex) {
   255             return chk.completionError(tree.pos(), ex);
   256         } finally {
   257             this.env = prevEnv;
   258         }
   259     }
   261     /** Visitor method: enter classes of a list of trees, returning a list of types.
   262      */
   263     <T extends JCTree> List<Type> classEnter(List<T> trees, Env<AttrContext> env) {
   264         ListBuffer<Type> ts = new ListBuffer<Type>();
   265         for (List<T> l = trees; l.nonEmpty(); l = l.tail) {
   266             Type t = classEnter(l.head, env);
   267             if (t != null)
   268                 ts.append(t);
   269         }
   270         return ts.toList();
   271     }
   273     @Override
   274     public void visitTopLevel(JCCompilationUnit tree) {
   275         JavaFileObject prev = log.useSource(tree.sourcefile);
   276         boolean addEnv = false;
   277         boolean isPkgInfo = tree.sourcefile.isNameCompatible("package-info",
   278                                                              JavaFileObject.Kind.SOURCE);
   279         if (tree.pid != null) {
   280             tree.packge = reader.enterPackage(TreeInfo.fullName(tree.pid));
   281             if (tree.packageAnnotations.nonEmpty()) {
   282                 if (isPkgInfo) {
   283                     addEnv = true;
   284                 } else {
   285                     log.error(tree.packageAnnotations.head.pos(),
   286                               "pkg.annotations.sb.in.package-info.java");
   287                 }
   288             }
   289         } else {
   290             tree.packge = syms.unnamedPackage;
   291         }
   292         tree.packge.complete(); // Find all classes in package.
   293         Env<AttrContext> topEnv = topLevelEnv(tree);
   295         // Save environment of package-info.java file.
   296         if (isPkgInfo) {
   297             Env<AttrContext> env0 = typeEnvs.get(tree.packge);
   298             if (env0 == null) {
   299                 typeEnvs.put(tree.packge, topEnv);
   300             } else {
   301                 JCCompilationUnit tree0 = env0.toplevel;
   302                 if (!fileManager.isSameFile(tree.sourcefile, tree0.sourcefile)) {
   303                     log.warning(tree.pid != null ? tree.pid.pos()
   304                                                  : null,
   305                                 "pkg-info.already.seen",
   306                                 tree.packge);
   307                     if (addEnv || (tree0.packageAnnotations.isEmpty() &&
   308                                    tree.docComments != null &&
   309                                    tree.docComments.get(tree) != null)) {
   310                         typeEnvs.put(tree.packge, topEnv);
   311                     }
   312                 }
   313             }
   315             for (Symbol q = tree.packge; q != null && q.kind == PCK; q = q.owner)
   316                 q.flags_field |= EXISTS;
   318             Name name = names.package_info;
   319             ClassSymbol c = reader.enterClass(name, tree.packge);
   320             c.flatname = names.fromString(tree.packge + "." + name);
   321             c.sourcefile = tree.sourcefile;
   322             c.completer = null;
   323             c.members_field = new Scope(c);
   324             tree.packge.package_info = c;
   325         }
   326         classEnter(tree.defs, topEnv);
   327         if (addEnv) {
   328             todo.append(topEnv);
   329         }
   330         log.useSource(prev);
   331         result = null;
   332     }
   334     @Override
   335     public void visitClassDef(JCClassDecl tree) {
   336         Symbol owner = env.info.scope.owner;
   337         Scope enclScope = enterScope(env);
   338         ClassSymbol c;
   339         if (owner.kind == PCK) {
   340             // We are seeing a toplevel class.
   341             PackageSymbol packge = (PackageSymbol)owner;
   342             for (Symbol q = packge; q != null && q.kind == PCK; q = q.owner)
   343                 q.flags_field |= EXISTS;
   344             c = reader.enterClass(tree.name, packge);
   345             packge.members().enterIfAbsent(c);
   346             if ((tree.mods.flags & PUBLIC) != 0 && !classNameMatchesFileName(c, env)) {
   347                 log.error(tree.pos(),
   348                           "class.public.should.be.in.file", tree.name);
   349             }
   350         } else {
   351             if (!tree.name.isEmpty() &&
   352                 !chk.checkUniqueClassName(tree.pos(), tree.name, enclScope)) {
   353                 result = null;
   354                 return;
   355             }
   356             if (owner.kind == TYP) {
   357                 // We are seeing a member class.
   358                 c = reader.enterClass(tree.name, (TypeSymbol)owner);
   359                 if ((owner.flags_field & INTERFACE) != 0) {
   360                     tree.mods.flags |= PUBLIC | STATIC;
   361                 }
   362             } else {
   363                 // We are seeing a local class.
   364                 c = reader.defineClass(tree.name, owner);
   365                 c.flatname = chk.localClassName(c);
   366                 if (!c.name.isEmpty())
   367                     chk.checkTransparentClass(tree.pos(), c, env.info.scope);
   368             }
   369         }
   370         tree.sym = c;
   372         // Enter class into `compiled' table and enclosing scope.
   373         if (chk.compiled.get(c.flatname) != null) {
   374             duplicateClass(tree.pos(), c);
   375             result = types.createErrorType(tree.name, (TypeSymbol)owner, Type.noType);
   376             tree.sym = (ClassSymbol)result.tsym;
   377             return;
   378         }
   379         chk.compiled.put(c.flatname, c);
   380         enclScope.enter(c);
   382         // Set up an environment for class block and store in `typeEnvs'
   383         // table, to be retrieved later in memberEnter and attribution.
   384         Env<AttrContext> localEnv = classEnv(tree, env);
   385         typeEnvs.put(c, localEnv);
   387         // Fill out class fields.
   388         c.completer = memberEnter;
   389         c.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, c, tree);
   390         c.sourcefile = env.toplevel.sourcefile;
   391         c.members_field = new Scope(c);
   393         ClassType ct = (ClassType)c.type;
   394         if (owner.kind != PCK && (c.flags_field & STATIC) == 0) {
   395             // We are seeing a local or inner class.
   396             // Set outer_field of this class to closest enclosing class
   397             // which contains this class in a non-static context
   398             // (its "enclosing instance class"), provided such a class exists.
   399             Symbol owner1 = owner;
   400             while ((owner1.kind & (VAR | MTH)) != 0 &&
   401                    (owner1.flags_field & STATIC) == 0) {
   402                 owner1 = owner1.owner;
   403             }
   404             if (owner1.kind == TYP) {
   405                 ct.setEnclosingType(owner1.type);
   406             }
   407         }
   409         // Enter type parameters.
   410         ct.typarams_field = classEnter(tree.typarams, localEnv);
   412         // Add non-local class to uncompleted, to make sure it will be
   413         // completed later.
   414         if (!c.isLocal() && uncompleted != null) uncompleted.append(c);
   415 //      System.err.println("entering " + c.fullname + " in " + c.owner);//DEBUG
   417         // Recursively enter all member classes.
   418         classEnter(tree.defs, localEnv);
   420         result = c.type;
   421     }
   422     //where
   423         /** Does class have the same name as the file it appears in?
   424          */
   425         private static boolean classNameMatchesFileName(ClassSymbol c,
   426                                                         Env<AttrContext> env) {
   427             return env.toplevel.sourcefile.isNameCompatible(c.name.toString(),
   428                                                             JavaFileObject.Kind.SOURCE);
   429         }
   431     /** Complain about a duplicate class. */
   432     protected void duplicateClass(DiagnosticPosition pos, ClassSymbol c) {
   433         log.error(pos, "duplicate.class", c.fullname);
   434     }
   436     /** Class enter visitor method for type parameters.
   437      *  Enter a symbol for type parameter in local scope, after checking that it
   438      *  is unique.
   439      */
   440     @Override
   441     public void visitTypeParameter(JCTypeParameter tree) {
   442         TypeVar a = (tree.type != null)
   443             ? (TypeVar)tree.type
   444             : new TypeVar(tree.name, env.info.scope.owner, syms.botType);
   445         tree.type = a;
   446         if (chk.checkUnique(tree.pos(), a.tsym, env.info.scope)) {
   447             env.info.scope.enter(a.tsym);
   448         }
   449         result = a;
   450     }
   452     /** Default class enter visitor method: do nothing.
   453      */
   454     @Override
   455     public void visitTree(JCTree tree) {
   456         result = null;
   457     }
   459     /** Main method: enter all classes in a list of toplevel trees.
   460      *  @param trees      The list of trees to be processed.
   461      */
   462     public void main(List<JCCompilationUnit> trees) {
   463         complete(trees, null);
   464     }
   466     /** Main method: enter one class from a list of toplevel trees and
   467      *  place the rest on uncompleted for later processing.
   468      *  @param trees      The list of trees to be processed.
   469      *  @param c          The class symbol to be processed.
   470      */
   471     public void complete(List<JCCompilationUnit> trees, ClassSymbol c) {
   472         annotate.enterStart();
   473         ListBuffer<ClassSymbol> prevUncompleted = uncompleted;
   474         if (memberEnter.completionEnabled) uncompleted = new ListBuffer<ClassSymbol>();
   476         try {
   477             // enter all classes, and construct uncompleted list
   478             classEnter(trees, null);
   480             // complete all uncompleted classes in memberEnter
   481             if  (memberEnter.completionEnabled) {
   482                 while (uncompleted.nonEmpty()) {
   483                     ClassSymbol clazz = uncompleted.next();
   484                     if (c == null || c == clazz || prevUncompleted == null)
   485                         clazz.complete();
   486                     else
   487                         // defer
   488                         prevUncompleted.append(clazz);
   489                 }
   491                 // if there remain any unimported toplevels (these must have
   492                 // no classes at all), process their import statements as well.
   493                 for (JCCompilationUnit tree : trees) {
   494                     if (tree.starImportScope.elems == null) {
   495                         JavaFileObject prev = log.useSource(tree.sourcefile);
   496                         Env<AttrContext> topEnv = topLevelEnv(tree);
   497                         memberEnter.memberEnter(tree, topEnv);
   498                         log.useSource(prev);
   499                     }
   500                 }
   501             }
   502         } finally {
   503             uncompleted = prevUncompleted;
   504             annotate.enterDone();
   505         }
   506     }
   507 }

mercurial