src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Enter.java
author Dusan Balek <dbalek@netbeans.org>
Fri, 04 Aug 2017 13:32:32 +0200
changeset 5956 15c0d1682895
parent 5758 132a238fb298
permissions -rw-r--r--
Issue #271211 - NullPointerException at com.sun.tools.javac.comp.Enter.lambda$visitTopLevel$1 - fixed.
     1 /*
     2  * Copyright (c) 1999, 2017, 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  */
    25 
    26 package com.sun.tools.javac.comp;
    27 
    28 import java.net.URI;
    29 import java.util.HashMap;
    30 import java.util.Map;
    31 import java.util.Optional;
    32 
    33 import javax.lang.model.element.ExecutableElement;
    34 import javax.lang.model.element.TypeElement;
    35 import javax.lang.model.element.VariableElement;
    36 import javax.lang.model.util.ElementScanner6;
    37 import javax.tools.JavaFileObject;
    38 import javax.tools.JavaFileManager;
    39 
    40 import com.sun.tools.javac.api.DuplicateClassChecker;
    41 import com.sun.tools.javac.code.*;
    42 import com.sun.tools.javac.code.Kinds.KindName;
    43 import com.sun.tools.javac.code.Kinds.KindSelector;
    44 import com.sun.tools.javac.code.Scope.*;
    45 import com.sun.tools.javac.code.Symbol.*;
    46 import com.sun.tools.javac.code.Type.*;
    47 import com.sun.tools.javac.main.Option.PkgInfo;
    48 import com.sun.tools.javac.model.LazyTreeLoader;
    49 import com.sun.tools.javac.resources.CompilerProperties.Errors;
    50 import com.sun.tools.javac.tree.*;
    51 import com.sun.tools.javac.tree.JCTree.*;
    52 import com.sun.tools.javac.util.*;
    53 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
    54 import com.sun.tools.javac.util.List;
    55 
    56 import static com.sun.tools.javac.code.Flags.*;
    57 import static com.sun.tools.javac.code.Kinds.Kind.*;
    58 
    59 /** This class enters symbols for all encountered definitions into
    60  *  the symbol table. The pass consists of high-level two phases,
    61  *  organized as follows:
    62  *
    63  *  <p>In the first phase, all class symbols are entered into their
    64  *  enclosing scope, descending recursively down the tree for classes
    65  *  which are members of other classes. The class symbols are given a
    66  *  TypeEnter object as completer.
    67  *
    68  *  <p>In the second phase classes are completed using
    69  *  TypeEnter.complete(). Completion might occur on demand, but
    70  *  any classes that are not completed that way will be eventually
    71  *  completed by processing the `uncompleted' queue. Completion
    72  *  entails determination of a class's parameters, supertype and
    73  *  interfaces, as well as entering all symbols defined in the
    74  *  class into its scope, with the exception of class symbols which
    75  *  have been entered in phase 1.
    76  *
    77  *  <p>Whereas the first phase is organized as a sweep through all
    78  *  compiled syntax trees, the second phase is on-demand. Members of a
    79  *  class are entered when the contents of a class are first
    80  *  accessed. This is accomplished by installing completer objects in
    81  *  class symbols for compiled classes which invoke the type-enter
    82  *  phase for the corresponding class tree.
    83  *
    84  *  <p>Classes migrate from one phase to the next via queues:
    85  *
    86  *  <pre>{@literal
    87  *  class enter -> (Enter.uncompleted)         --> type enter
    88  *              -> (Todo)                      --> attribute
    89  *                                              (only for toplevel classes)
    90  *  }</pre>
    91  *
    92  *  <p><b>This is NOT part of any supported API.
    93  *  If you write code that depends on this, you do so at your own risk.
    94  *  This code and its internal interfaces are subject to change or
    95  *  deletion without notice.</b>
    96  */
    97 public class Enter extends JCTree.Visitor {
    98     protected static final Context.Key<Enter> enterKey = new Context.Key<>();
    99 
   100     Annotate annotate;
   101     Log log;
   102     Symtab syms;
   103     Check chk;
   104     TreeMaker make;
   105     TypeEnter typeEnter;
   106     Types types;
   107     Lint lint;
   108     Names names;
   109     JavaFileManager fileManager;
   110     PkgInfo pkginfoOpt;
   111     TypeEnvs typeEnvs;
   112     Modules modules;
   113     JCDiagnostic.Factory diags;
   114     
   115     private final LazyTreeLoader treeLoader;
   116     private final DuplicateClassChecker duplicateClassChecker;
   117     private final Source source;
   118 
   119     private final Todo todo;
   120 
   121     public static Enter instance(Context context) {
   122         Enter instance = context.get(enterKey);
   123         if (instance == null)
   124             instance = new Enter(context);
   125         return instance;
   126     }
   127 
   128     protected Enter(Context context) {
   129         context.put(enterKey, this);
   130 
   131         log = Log.instance(context);
   132         make = TreeMaker.instance(context);
   133         syms = Symtab.instance(context);
   134         chk = Check.instance(context);
   135         typeEnter = TypeEnter.instance(context);
   136         types = Types.instance(context);
   137         annotate = Annotate.instance(context);
   138         lint = Lint.instance(context);
   139         names = Names.instance(context);
   140         modules = Modules.instance(context);
   141         diags = JCDiagnostic.Factory.instance(context);
   142         treeLoader = LazyTreeLoader.instance(context);
   143         duplicateClassChecker = context.get(DuplicateClassChecker.class);
   144 
   145         predefClassDef = make.ClassDef(
   146             make.Modifiers(PUBLIC),
   147             syms.predefClass.name,
   148             List.nil(),
   149             null,
   150             List.nil(),
   151             List.nil());
   152         predefClassDef.sym = syms.predefClass;
   153         todo = Todo.instance(context);
   154         fileManager = context.get(JavaFileManager.class);
   155 
   156         Options options = Options.instance(context);
   157         pkginfoOpt = PkgInfo.get(options);
   158         typeEnvs = TypeEnvs.instance(context);
   159         source = Source.instance(context);
   160     }
   161 
   162     Map<TypeSymbol,Env<AttrContext>> typeEnvsShadow = null;
   163 
   164     private final Map<URI, JCCompilationUnit> compilationUnits =
   165             new HashMap<URI, JCCompilationUnit> ();
   166 
   167     public JCCompilationUnit getCompilationUnit (JavaFileObject fobj) {
   168         return this.compilationUnits.get(fobj.toUri());
   169     }
   170 
   171     /** Accessor for typeEnvs
   172      */
   173     public Env<AttrContext> getEnv(TypeSymbol sym) {
   174         return typeEnvs.get(sym);
   175     }
   176 
   177     public Iterable<Env<AttrContext>> getEnvs() {
   178         return typeEnvs.values();
   179     }
   180 
   181     public Env<AttrContext> getClassEnv(TypeSymbol sym) {
   182         Env<AttrContext> localEnv = getEnv(sym);
   183         if (localEnv == null) return null;
   184         Env<AttrContext> lintEnv = localEnv;
   185         while (lintEnv.info.lint == null)
   186             lintEnv = lintEnv.next;
   187         localEnv.info.lint = lintEnv.info.lint.augment(sym);
   188         return localEnv;
   189     }
   190 
   191     /** The queue of all classes that might still need to be completed;
   192      *  saved and initialized by main().
   193      */
   194     ListBuffer<ClassSymbol> uncompleted;
   195 
   196     /** The queue of modules whose imports still need to be checked. */
   197     ListBuffer<JCCompilationUnit> unfinishedModules = new ListBuffer<>();
   198 
   199     /** A dummy class to serve as enclClass for toplevel environments.
   200      */
   201     private JCClassDecl predefClassDef;
   202 
   203 /* ************************************************************************
   204  * environment construction
   205  *************************************************************************/
   206 
   207 
   208     /** Create a fresh environment for class bodies.
   209      *  This will create a fresh scope for local symbols of a class, referred
   210      *  to by the environments info.scope field.
   211      *  This scope will contain
   212      *    - symbols for this and super
   213      *    - symbols for any type parameters
   214      *  In addition, it serves as an anchor for scopes of methods and initializers
   215      *  which are nested in this scope via Scope.dup().
   216      *  This scope should not be confused with the members scope of a class.
   217      *
   218      *  @param tree     The class definition.
   219      *  @param env      The environment current outside of the class definition.
   220      */
   221     public Env<AttrContext> classEnv(JCClassDecl tree, Env<AttrContext> env) {
   222         Env<AttrContext> localEnv =
   223             env.dup(tree, env.info.dup(WriteableScope.create(tree.sym)));
   224         localEnv.enclClass = tree;
   225         localEnv.outer = env;
   226         localEnv.info.isSelfCall = false;
   227         localEnv.info.lint = null; // leave this to be filled in by Attr,
   228                                    // when annotations have been processed
   229         localEnv.info.isAnonymousDiamond = TreeInfo.isDiamond(env.tree);
   230         return localEnv;
   231     }
   232 
   233     /** Create a fresh environment for toplevels.
   234      *  @param tree     The toplevel tree.
   235      */
   236     Env<AttrContext> topLevelEnv(JCCompilationUnit tree) {
   237         Env<AttrContext> localEnv = new Env<>(tree, new AttrContext());
   238         localEnv.toplevel = tree;
   239         localEnv.enclClass = predefClassDef;
   240         tree.toplevelScope = WriteableScope.create(tree.packge);
   241         tree.namedImportScope = new NamedImportScope(tree.packge, tree.toplevelScope);
   242         tree.starImportScope = new StarImportScope(tree.packge);
   243         localEnv.info.scope = tree.toplevelScope;
   244         localEnv.info.lint = lint;
   245         return localEnv;
   246     }
   247 
   248     public Env<AttrContext> getTopLevelEnv(JCCompilationUnit tree) {
   249         Env<AttrContext> localEnv = new Env<>(tree, new AttrContext());
   250         localEnv.toplevel = tree;
   251         localEnv.enclClass = predefClassDef;
   252         localEnv.info.scope = tree.toplevelScope;
   253         localEnv.info.lint = lint;
   254         return localEnv;
   255     }
   256 
   257     /** The scope in which a member definition in environment env is to be entered
   258      *  This is usually the environment's scope, except for class environments,
   259      *  where the local scope is for type variables, and the this and super symbol
   260      *  only, and members go into the class member scope.
   261      */
   262     WriteableScope enterScope(Env<AttrContext> env) {
   263         return (env.tree.hasTag(JCTree.Tag.CLASSDEF))
   264             ? ((JCClassDecl) env.tree).sym.members_field
   265             : env.info.scope;
   266     }
   267 
   268     /** Create a fresh environment for modules.
   269      *
   270      *  @param tree     The module definition.
   271      *  @param env      The environment current outside of the module definition.
   272      */
   273     public Env<AttrContext> moduleEnv(JCModuleDecl tree, Env<AttrContext> env) {
   274         Assert.checkNonNull(tree.sym);
   275         Env<AttrContext> localEnv =
   276             env.dup(tree, env.info.dup(WriteableScope.create(tree.sym)));
   277         localEnv.enclClass = predefClassDef;
   278         localEnv.outer = env;
   279         localEnv.info.isSelfCall = false;
   280         localEnv.info.lint = null; // leave this to be filled in by Attr,
   281                                    // when annotations have been processed
   282         return localEnv;
   283     }
   284 
   285     public void shadowTypeEnvs(boolean b) {
   286         if (b) {
   287             assert typeEnvsShadow == null;
   288             typeEnvsShadow = new HashMap<TypeSymbol,Env<AttrContext>>();
   289         } else {
   290             for (Map.Entry<TypeSymbol, Env<AttrContext>> entry : typeEnvsShadow.entrySet()) {
   291                 if (entry.getValue() == null)
   292                     typeEnvs.remove(entry.getKey());
   293                 else
   294                     typeEnvs.put(entry.getKey(), entry.getValue());
   295             }
   296             typeEnvsShadow = null;
   297         }
   298     }
   299     
   300     public boolean isShadowed() {
   301         return typeEnvsShadow != null;
   302     }
   303 
   304 /* ************************************************************************
   305  * Visitor methods for phase 1: class enter
   306  *************************************************************************/
   307 
   308     /** Visitor argument: the current environment.
   309      */
   310     protected Env<AttrContext> env;
   311 
   312     /** Visitor result: the computed type.
   313      */
   314     Type result;
   315 
   316     /** Visitor method: enter all classes in given tree, catching any
   317      *  completion failure exceptions. Return the tree's type.
   318      *
   319      *  @param tree    The tree to be visited.
   320      *  @param env     The environment visitor argument.
   321      */
   322     Type classEnter(JCTree tree, Env<AttrContext> env) {
   323         Env<AttrContext> prevEnv = this.env;
   324         try {
   325             this.env = env;
   326             annotate.blockAnnotations();
   327             tree.accept(this);
   328             return result;
   329         }  catch (CompletionFailure ex) {
   330             return chk.completionError(tree.pos(), ex);
   331         } finally {
   332             annotate.unblockAnnotations();
   333             this.env = prevEnv;
   334         }
   335     }
   336 
   337     /** Visitor method: enter classes of a list of trees, returning a list of types.
   338      */
   339     <T extends JCTree> List<Type> classEnter(List<T> trees, Env<AttrContext> env) {
   340         ListBuffer<Type> ts = new ListBuffer<>();
   341         for (List<T> l = trees; l.nonEmpty(); l = l.tail) {
   342             Type t = classEnter(l.head, env);
   343             if (t != null)
   344                 ts.append(t);
   345         }
   346         return ts.toList();
   347     }
   348 
   349     @Override
   350     public void visitTopLevel(JCCompilationUnit tree) {
   351 //        Assert.checkNonNull(tree.modle, tree.sourcefile.toString());
   352 
   353         JavaFileObject prev = log.useSource(tree.sourcefile);
   354         boolean addEnv = false;
   355         boolean isPkgInfo = tree.sourcefile.isNameCompatible("package-info",
   356                                                              JavaFileObject.Kind.SOURCE);
   357         if (TreeInfo.isModuleInfo(tree)) {
   358             JCPackageDecl pd = tree.getPackage();
   359             if (pd != null) {
   360                 log.error(pd.pos(), Errors.NoPkgInModuleInfoJava);
   361             }
   362             tree.packge = syms.rootPackage;
   363             Env<AttrContext> topEnv = topLevelEnv(tree);
   364             if (tree.modle != syms.noModule) {
   365                 classEnter(tree.defs, topEnv);
   366                 tree.modle.usesProvidesCompleter = modules.getUsesProvidesCompleter();
   367             }
   368         } else {
   369             JCPackageDecl pd = tree.getPackage();
   370             if (pd != null) {
   371                 tree.packge = pd.packge = syms.enterPackage(tree.modle, TreeInfo.fullName(pd.pid));
   372                 PackageAttributer.attrib(pd.pid, tree.packge);
   373                 if (   pd.annotations.nonEmpty()
   374                     || pkginfoOpt == PkgInfo.ALWAYS
   375                     || tree.docComments != null) {
   376                     if (isPkgInfo) {
   377                         addEnv = true;
   378                     } else if (pd.annotations.nonEmpty()) {
   379                         log.error(pd.annotations.head.pos(),
   380                                   "pkg.annotations.sb.in.package-info.java");
   381                     }
   382                 }
   383             } else {
   384                 tree.packge = tree.modle.unnamedPackage;
   385             }
   386 
   387             Map<Name, PackageSymbol> visiblePackages = tree.modle.visiblePackages;
   388             Optional<ModuleSymbol> dependencyWithPackage =
   389                 syms.listPackageModules(tree.packge.fullname)
   390                     .stream()
   391                     .filter(m -> m != tree.modle)
   392                     .filter(cand -> visiblePackages != null && visiblePackages.get(tree.packge.fullname) == syms.getPackage(cand, tree.packge.fullname))
   393                     .findAny();
   394 
   395             if (dependencyWithPackage.isPresent()) {
   396                 log.error(pd, Errors.PackageInOtherModule(dependencyWithPackage.get()));
   397             }
   398 
   399             tree.packge.complete(); // Find all classes in package.
   400 
   401             Env<AttrContext> topEnv = topLevelEnv(tree);
   402             Env<AttrContext> packageEnv = isPkgInfo ? topEnv.dup(pd) : null;
   403 
   404             // Save environment of package-info.java file.
   405             if (isPkgInfo) {
   406                 Env<AttrContext> env0 = typeEnvs.get(tree.packge);
   407                 if (env0 != null) {
   408                     JCCompilationUnit tree0 = env0.toplevel;
   409                     if (!fileManager.isSameFile(tree.sourcefile, tree0.sourcefile)) {
   410                         log.warning(pd != null ? pd.pid.pos() : null,
   411                                     "pkg-info.already.seen",
   412                                     tree.packge);
   413                     }
   414                 }
   415                 typeEnvs.put(tree.packge, packageEnv);
   416 
   417                 for (Symbol q = tree.packge; q != null && q.kind == PCK; q = q.owner)
   418                     q.flags_field |= EXISTS;
   419 
   420                 Name name = names.package_info;
   421                 ClassSymbol c = syms.enterClass(tree.modle, name, tree.packge);
   422                 c.flatname = names.fromString(tree.packge + "." + name);
   423                 c.sourcefile = tree.sourcefile;
   424                 c.completer = Completer.NULL_COMPLETER;
   425                 c.members_field = WriteableScope.create(c);
   426                 tree.packge.package_info = c;
   427             }
   428             compilationUnits.put(tree.sourcefile.toUri(), tree);
   429             classEnter(tree.defs, topEnv);
   430             if (addEnv) {
   431                 if ((tree.packge.flags_field & APT_CLEANED) != 0)
   432                     todo.remove(tree.packge);
   433                 todo.append(packageEnv);
   434             }
   435         }
   436         log.useSource(prev);
   437         result = null;
   438     }
   439 
   440     private static class PackageAttributer extends TreeScanner {
   441 
   442         private Symbol pkg;
   443 
   444         public static void attrib(JCExpression pid, Symbol pkg) {
   445             PackageAttributer pa = new PackageAttributer();
   446             pa.pkg = pkg;
   447             pa.scan(pid);
   448         }
   449 
   450         @Override
   451         public void visitIdent(JCIdent that) {
   452             that.sym = pkg;
   453         }
   454 
   455         @Override
   456         public void visitSelect(JCFieldAccess that) {
   457             that.sym = pkg;
   458             pkg = pkg.owner;
   459             super.visitSelect(that);
   460         }
   461     }
   462 
   463 
   464     @Override
   465     public void visitClassDef(JCClassDecl tree) {
   466         Symbol owner = env.info.scope.owner;
   467         WriteableScope enclScope = enterScope(env);
   468         ClassSymbol c = null;
   469         boolean doEnterClass = true;
   470         boolean reattr=false, noctx=false;
   471         if (owner.kind == PCK) {
   472             // We are seeing a toplevel class.
   473             PackageSymbol packge = (PackageSymbol)owner;
   474             for (Symbol q = packge; q != null && q.kind == PCK; q = q.owner)
   475                 q.flags_field |= EXISTS;
   476             c = syms.enterClass(env.toplevel.modle, tree.name, packge);
   477             packge.members().enterIfAbsent(c);
   478             if ((tree.mods.flags & PUBLIC) != 0 && !classNameMatchesFileName(c, env)) {
   479                 KindName topElement = KindName.CLASS;
   480                 if ((tree.mods.flags & ENUM) != 0) {
   481                     topElement = KindName.ENUM;
   482                 } else if ((tree.mods.flags & INTERFACE) != 0) {
   483                     topElement = KindName.INTERFACE;
   484                 }
   485                 log.error(tree.pos(),
   486                           "class.public.should.be.in.file", topElement, tree.name);
   487             }
   488         } else {
   489             if ((enclScope.owner.flags_field & FROMCLASS) != 0) {
   490                 for (Symbol sym : enclScope.getSymbolsByName(tree.name)) {
   491                     if (sym.kind == TYP) {
   492                         c = (ClassSymbol)sym;
   493                         break;
   494                     }
   495                 }
   496                 if (c != null) {
   497                     if (chk.getCompiled(c) != null) {
   498                         c = null;
   499                     } else {
   500                         reattr = true;
   501                         if (owner.kind == TYP) {
   502                             if ((owner.flags_field & INTERFACE) != 0) {
   503                                 tree.mods.flags |= PUBLIC | STATIC;
   504                             }
   505                         }
   506                         doEnterClass = false;
   507                     }
   508                 } else if ((enclScope.owner.flags_field & APT_CLEANED) == 0) {
   509                     ClassSymbol cs = enclScope.owner.outermostClass();
   510                     treeLoader.couplingError(cs, tree);
   511                     doEnterClass = false;
   512                 }
   513             }
   514             if (c == null) {
   515                 if (!tree.name.isEmpty() &&
   516                         !chk.checkUniqueClassName(tree.pos(), tree.name, enclScope)) {
   517                     result = types.createErrorType(tree.name, owner, Type.noType);
   518                     tree.sym = (ClassSymbol)result.tsym;
   519                     Env<AttrContext> localEnv = classEnv(tree, env);
   520                     typeEnvs.put(tree.sym, localEnv);
   521                     tree.sym.completer = typeEnter;
   522                     ((ClassType)result).typarams_field = classEnter(tree.typarams, localEnv);
   523                     if (!tree.sym.isLocal() && uncompleted != null) uncompleted.append(tree.sym);
   524                     tree.type = tree.sym.type;
   525                     return;
   526                 }
   527                 if (owner.kind == TYP || owner.kind == ERR) {
   528                     // We are seeing a member class.
   529                     c = syms.enterClass(env.toplevel.modle, tree.name, (TypeSymbol)owner);
   530                     if (c.owner != owner) {
   531                         //anonymous class loaded from a classfile may be recreated from source (see below)
   532                         //if this class is a member of such an anonymous class, fix the owner:
   533                         Assert.check(owner.owner.kind != TYP && owner.owner.kind != ERR, owner::toString);
   534                         Symbol own = c.owner;
   535                         Assert.check(c.owner.kind == TYP || c.owner.kind == ERR, own::toString);
   536                         ClassSymbol cowner = (ClassSymbol) c.owner;
   537                         if (cowner.members_field != null) {
   538                             cowner.members_field.remove(c);
   539                         }
   540                         c.owner = owner;
   541                     }
   542                     if ((owner.flags_field & INTERFACE) != 0) {
   543                         tree.mods.flags |= PUBLIC | STATIC;
   544                     }
   545                     Symbol q = owner;
   546                     while(q != null && q.kind.matches(KindSelector.TYP)) {
   547                         q = q.owner;
   548                     }
   549                     if (q != null && q.kind != PCK && chk.getCompiled(c) != null) {
   550                         reattr = true;
   551                     }
   552                 } else {
   553                     // We are seeing a local class.
   554                     if (getIndex(tree) == -1) {
   555                         c = syms.defineClass(tree.name, owner);
   556                         c.flatname = chk.localClassName(c);
   557                         noctx = true;
   558                     }
   559                     else {
   560                         Name flatname = chk.localClassName(owner.enclClass(), tree.name, getIndex(tree));
   561                         if ((c=chk.getCompiled(env.toplevel.modle, flatname)) != null) {
   562                             reattr = true;
   563                         }
   564                         else {
   565                             c = syms.enterClass(env.toplevel.modle, flatname, tree.name, owner);
   566                             if (c.completer.isTerminal())
   567                                 reattr = true;
   568                         }
   569                     }
   570                     if (!c.name.isEmpty())
   571                         chk.checkTransparentClass(tree.pos(), c, env.info.scope);
   572                 }
   573             }
   574         }
   575         tree.sym = c;
   576 
   577         if (c.kind == ERR && c.type.isErroneous()) {
   578             c.flags_field &= ~FROMCLASS;
   579             c.kind = TYP;
   580             c.type = new ClassType(Type.noType, List.<Type>nil(), c);
   581         } else if (reattr && c.completer.isTerminal()) {
   582             new ElementScanner6<Void, Void>() {
   583                 @Override
   584                 public Void visitType(TypeElement te, Void p) {
   585                     if (te instanceof ClassSymbol && ((ClassSymbol) te).completer.isTerminal()) {
   586                         ((ClassSymbol) te).flags_field |= FROMCLASS;
   587                         for (Symbol sym : ((ClassSymbol) te).members().getSymbols()) {
   588                             try {
   589                                 if (sym != null && sym.owner == te)
   590                                     scan(sym);
   591                             } catch (CompletionFailure cf) {}
   592                         }
   593                     }
   594                     return null;
   595                 }
   596                 @Override
   597                 public Void visitExecutable(ExecutableElement ee, Void p) {
   598                     if (ee instanceof MethodSymbol)
   599                         ((MethodSymbol) ee).flags_field |= FROMCLASS;
   600                     return null;
   601                 }
   602                 @Override
   603                 public Void visitVariable(VariableElement ve, Void p) {
   604                     if (ve instanceof VarSymbol)
   605                         ((VarSymbol) ve).flags_field |= FROMCLASS;
   606                     return null;
   607                 }
   608             }.scan(c);
   609         }
   610 
   611         // Enter class into `compiled' table and enclosing scope.
   612         if (!reattr && !noctx && (chk.getCompiled(c) != null
   613                 || (!c.isLocal() && duplicateClassChecker != null && duplicateClassChecker.check(c.fullname, env.toplevel.getSourceFile())))) {
   614             duplicateClass(tree.pos(), c);
   615             result = types.createErrorType(tree.name, owner, Type.noType);
   616             tree.sym = c = (ClassSymbol)result.tsym;
   617         } else {
   618             chk.putCompiled(c);
   619         }
   620         if (doEnterClass) {
   621             enclScope.enter(c);
   622         }
   623 
   624         if (typeEnvsShadow != null) {
   625             Env<AttrContext> localEnv = typeEnvs.get(c);
   626             typeEnvsShadow.put(c, localEnv);
   627         }
   628         // Set up an environment for class block and store in `typeEnvs'
   629         // table, to be retrieved later in memberEnter and attribution.
   630         Env<AttrContext> localEnv = classEnv(tree, env);
   631         typeEnvs.put(c, localEnv);
   632 
   633         // Fill out class fields.
   634         boolean notYetCompleted = !c.completer.isTerminal();
   635         c.completer = Completer.NULL_COMPLETER; // do not allow the initial completer linger on.
   636         c.sourcefile = env.toplevel.sourcefile;
   637         if (notYetCompleted || (c.flags_field & FROMCLASS) == 0 && (enclScope.owner.flags_field & FROMCLASS) == 0) {
   638             c.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, c, tree);
   639             c.members_field = WriteableScope.create(c);
   640 
   641             ClassType ct = (ClassType)c.type;
   642             if (owner.kind != PCK && (c.flags_field & STATIC) == 0) {
   643                 // We are seeing a local or inner class.
   644                 // Set outer_field of this class to closest enclosing class
   645                 // which contains this class in a non-static context
   646                 // (its "enclosing instance class"), provided such a class exists.
   647                 Symbol owner1 = owner;
   648                 while (owner1.kind.matches(KindSelector.VAL_MTH) &&
   649                        (owner1.flags_field & STATIC) == 0) {
   650                     owner1 = owner1.owner;
   651                 }
   652                 if (owner1.kind == TYP) {
   653                     ct.setEnclosingType(owner1.type);
   654                 }
   655             }
   656             // Enter type parameters.
   657             ct.typarams_field = classEnter(tree.typarams, localEnv);
   658             ct.allparams_field = null;
   659         } else {
   660             c.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, c, tree) | (c.flags_field & (FROMCLASS | APT_CLEANED));
   661             ClassType ct = (ClassType)c.type;
   662             if (owner.kind != PCK && (c.flags_field & STATIC) == 0) {
   663                 // We are seeing a local or inner class.
   664                 // Set outer_field of this class to closest enclosing class
   665                 // which contains this class in a non-static context
   666                 // (its "enclosing instance class"), provided such a class exists.
   667                 Symbol owner1 = owner;
   668                 while (owner1.kind.matches(KindSelector.VAL_MTH) &&
   669                         (owner1.flags_field & STATIC) == 0) {
   670                     owner1 = owner1.owner;
   671                 }
   672                 if (owner1.kind == TYP) {
   673                     ct.setEnclosingType(owner1.type);
   674                 }
   675             }
   676             boolean wasNull = false;
   677             if (ct.typarams_field != null) {
   678                 for (List<Type> l = ct.typarams_field; l.nonEmpty(); l = l.tail)
   679                     localEnv.info.scope.enter(l.head.tsym);
   680             } else {
   681                 wasNull = true;
   682             }
   683             List<Type> classEnter = classEnter(tree.typarams, localEnv);
   684             if (wasNull) {
   685                 if (!classEnter.isEmpty()) {
   686                     //the symbol from class does not have any type parameters,
   687                     //but the symbol in the source code does:
   688                     ClassSymbol cs = env.info.scope.owner.outermostClass();
   689                     treeLoader.couplingError(cs, tree);
   690                 } else {
   691                     ct.typarams_field = List.nil();
   692                     ct.allparams_field = null;
   693                 }
   694             }
   695             if (c.members_field == null) {
   696                 c.members_field = WriteableScope.create(c);
   697                 c.flags_field &= ~FROMCLASS;
   698             }
   699             if (c.owner.kind.matches(KindSelector.VAL_MTH)) {
   700                 // local or anonymous class
   701                 for (Symbol ctor : c.members_field.getSymbolsByName(names.init)) {
   702                     c.members_field.remove(ctor);
   703                 }
   704             }
   705        }
   706 
   707         // install further completer for this type.
   708         c.completer = typeEnter;
   709 
   710         // Add non-local class to uncompleted, to make sure it will be
   711         // completed later.
   712         if (!c.isLocal() && uncompleted != null) uncompleted.append(c);
   713 //      System.err.println("entering " + c.fullname + " in " + c.owner);//DEBUG
   714 
   715         // Recursively enter all member classes.
   716         classEnter(tree.defs, localEnv);
   717 
   718         result = tree.type = c.type;
   719     }
   720     //where
   721         /** Does class have the same name as the file it appears in?
   722          */
   723         private static boolean classNameMatchesFileName(ClassSymbol c,
   724                                                         Env<AttrContext> env) {
   725             return env.toplevel.sourcefile.isNameCompatible(c.name.toString(),
   726                                                             JavaFileObject.Kind.SOURCE);
   727         }
   728 
   729     /** Complain about a duplicate class. */
   730     protected void duplicateClass(DiagnosticPosition pos, ClassSymbol c) {
   731         log.error(pos, "duplicate.class", c.fullname);
   732     }
   733 
   734     protected int getIndex(JCClassDecl clazz) {
   735         return -1;
   736     }
   737 
   738     /** Class enter visitor method for type parameters.
   739      *  Enter a symbol for type parameter in local scope, after checking that it
   740      *  is unique.
   741      */
   742     @Override
   743     public void visitTypeParameter(JCTypeParameter tree) {
   744         result = null;
   745         if ((env.info.scope.owner.flags_field & FROMCLASS) != 0) {
   746             for (Symbol sym : env.info.scope.getSymbolsByName(tree.name)) {
   747                 if (sym.kind == TYP) {
   748                     result = sym.type;
   749                     tree.type = result;
   750                     break;
   751                 }
   752             }
   753             if (result != null)
   754                 return;
   755             if ((env.info.scope.owner.flags_field & APT_CLEANED) == 0) {
   756                 ClassSymbol cs = env.info.scope.owner.outermostClass();
   757                 treeLoader.couplingError(cs, tree);
   758             }
   759         }
   760         TypeVar a = (tree.type != null)
   761         ? (TypeVar)tree.type
   762                 : new TypeVar(tree.name, env.info.scope.owner, syms.botType);
   763         tree.type = a;
   764         if (chk.checkUnique(tree.pos(), a.tsym, env.info.scope)) {
   765             env.info.scope.enter(a.tsym);
   766         }
   767         result = a;
   768     }
   769 
   770     @Override
   771     public void visitModuleDef(JCModuleDecl tree) {
   772         Env<AttrContext> moduleEnv = moduleEnv(tree, env);
   773         typeEnvs.put(tree.sym, moduleEnv);
   774         if (modules.isInModuleGraph(tree.sym)) {
   775             todo.append(moduleEnv);
   776         }
   777     }
   778 
   779     /** Default class enter visitor method: do nothing.
   780      */
   781     @Override
   782     public void visitTree(JCTree tree) {
   783         result = null;
   784     }
   785 
   786     /** Main method: enter all classes in a list of toplevel trees.
   787      *  @param trees      The list of trees to be processed.
   788      */
   789     public void main(List<JCCompilationUnit> trees) {
   790         complete(trees, null);
   791     }
   792 
   793     /** Main method: enter classes from the list of toplevel trees, possibly
   794      *  skipping TypeEnter for all but 'c' by placing them on the uncompleted
   795      *  list.
   796      *  @param trees      The list of trees to be processed.
   797      *  @param c          The class symbol to be processed or null to process all.
   798      */
   799     public void complete(List<JCCompilationUnit> trees, ClassSymbol c) {
   800         annotate.blockAnnotations();
   801         ListBuffer<ClassSymbol> prevUncompleted = uncompleted;
   802         if (typeEnter.completionEnabled) uncompleted = new ListBuffer<>();
   803 
   804         try {
   805             // enter all classes, and construct uncompleted list
   806             classEnter(trees, null);
   807 
   808             // complete all uncompleted classes in memberEnter
   809             if (typeEnter.completionEnabled) {
   810                 while (uncompleted.nonEmpty()) {
   811                     ClassSymbol clazz = uncompleted.next();
   812                     if (c == null || c == clazz || prevUncompleted == null)
   813                         clazz.complete();
   814                     else
   815                         // defer
   816                         prevUncompleted.append(clazz);
   817                 }
   818 
   819                 if (!modules.modulesInitialized()) {
   820                     for (JCCompilationUnit cut : trees) {
   821                         if (TreeInfo.isModuleInfo(cut)) {
   822                             unfinishedModules.append(cut);
   823                         } else {
   824                             typeEnter.ensureImportsChecked(List.of(cut));
   825                         }
   826                     }
   827                 } else {
   828                     typeEnter.ensureImportsChecked(unfinishedModules.toList());
   829                     unfinishedModules.clear();
   830                     typeEnter.ensureImportsChecked(trees);
   831                 }
   832             }
   833         } finally {
   834             uncompleted = prevUncompleted;
   835             annotate.unblockAnnotations();
   836         }
   837     }
   838 
   839     public void newRound() {
   840         typeEnvs.clear();
   841     }
   842 }