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