Tue, 28 Dec 2010 15:54:52 -0800
6962318: Update copyright year
Reviewed-by: xdono
1 /*
2 * Copyright (c) 1999, 2010, 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.RecognizedOptions.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 intered 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>
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 Scope.ScopeCounter scopeCounter;
99 Check chk;
100 TreeMaker make;
101 ClassReader reader;
102 Annotate annotate;
103 MemberEnter memberEnter;
104 Types types;
105 Lint lint;
106 Names names;
107 JavaFileManager fileManager;
108 PkgInfo pkginfoOpt;
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 scopeCounter = Scope.ScopeCounter.instance(context);
127 chk = Check.instance(context);
128 memberEnter = MemberEnter.instance(context);
129 types = Types.instance(context);
130 annotate = Annotate.instance(context);
131 lint = Lint.instance(context);
132 names = Names.instance(context);
134 predefClassDef = make.ClassDef(
135 make.Modifiers(PUBLIC),
136 syms.predefClass.name, null, null, null, null);
137 predefClassDef.sym = syms.predefClass;
138 todo = Todo.instance(context);
139 fileManager = context.get(JavaFileManager.class);
141 Options options = Options.instance(context);
142 pkginfoOpt = PkgInfo.get(options);
143 }
145 /** A hashtable mapping classes and packages to the environments current
146 * at the points of their definitions.
147 */
148 Map<TypeSymbol,Env<AttrContext>> typeEnvs =
149 new HashMap<TypeSymbol,Env<AttrContext>>();
151 /** Accessor for typeEnvs
152 */
153 public Env<AttrContext> getEnv(TypeSymbol sym) {
154 return typeEnvs.get(sym);
155 }
157 public Env<AttrContext> getClassEnv(TypeSymbol sym) {
158 Env<AttrContext> localEnv = getEnv(sym);
159 Env<AttrContext> lintEnv = localEnv;
160 while (lintEnv.info.lint == null)
161 lintEnv = lintEnv.next;
162 localEnv.info.lint = lintEnv.info.lint.augment(sym.attributes_field, sym.flags());
163 return localEnv;
164 }
166 /** The queue of all classes that might still need to be completed;
167 * saved and initialized by main().
168 */
169 ListBuffer<ClassSymbol> uncompleted;
171 /** A dummy class to serve as enclClass for toplevel environments.
172 */
173 private JCClassDecl predefClassDef;
175 /* ************************************************************************
176 * environment construction
177 *************************************************************************/
180 /** Create a fresh environment for class bodies.
181 * This will create a fresh scope for local symbols of a class, referred
182 * to by the environments info.scope field.
183 * This scope will contain
184 * - symbols for this and super
185 * - symbols for any type parameters
186 * In addition, it serves as an anchor for scopes of methods and initializers
187 * which are nested in this scope via Scope.dup().
188 * This scope should not be confused with the members scope of a class.
189 *
190 * @param tree The class definition.
191 * @param env The environment current outside of the class definition.
192 */
193 public Env<AttrContext> classEnv(JCClassDecl tree, Env<AttrContext> env) {
194 Env<AttrContext> localEnv =
195 env.dup(tree, env.info.dup(new Scope.ClassScope(tree.sym, scopeCounter)));
196 localEnv.enclClass = tree;
197 localEnv.outer = env;
198 localEnv.info.isSelfCall = false;
199 localEnv.info.lint = null; // leave this to be filled in by Attr,
200 // when annotations have been processed
201 return localEnv;
202 }
204 /** Create a fresh environment for toplevels.
205 * @param tree The toplevel tree.
206 */
207 Env<AttrContext> topLevelEnv(JCCompilationUnit tree) {
208 Env<AttrContext> localEnv = new Env<AttrContext>(tree, new AttrContext());
209 localEnv.toplevel = tree;
210 localEnv.enclClass = predefClassDef;
211 tree.namedImportScope = new ImportScope(tree.packge);
212 tree.starImportScope = new StarImportScope(tree.packge);
213 localEnv.info.scope = tree.namedImportScope;
214 localEnv.info.lint = lint;
215 return localEnv;
216 }
218 public Env<AttrContext> getTopLevelEnv(JCCompilationUnit tree) {
219 Env<AttrContext> localEnv = new Env<AttrContext>(tree, new AttrContext());
220 localEnv.toplevel = tree;
221 localEnv.enclClass = predefClassDef;
222 localEnv.info.scope = tree.namedImportScope;
223 localEnv.info.lint = lint;
224 return localEnv;
225 }
227 /** The scope in which a member definition in environment env is to be entered
228 * This is usually the environment's scope, except for class environments,
229 * where the local scope is for type variables, and the this and super symbol
230 * only, and members go into the class member scope.
231 */
232 Scope enterScope(Env<AttrContext> env) {
233 return (env.tree.getTag() == JCTree.CLASSDEF)
234 ? ((JCClassDecl) env.tree).sym.members_field
235 : env.info.scope;
236 }
238 /* ************************************************************************
239 * Visitor methods for phase 1: class enter
240 *************************************************************************/
242 /** Visitor argument: the current environment.
243 */
244 protected Env<AttrContext> env;
246 /** Visitor result: the computed type.
247 */
248 Type result;
250 /** Visitor method: enter all classes in given tree, catching any
251 * completion failure exceptions. Return the tree's type.
252 *
253 * @param tree The tree to be visited.
254 * @param env The environment visitor argument.
255 */
256 Type classEnter(JCTree tree, Env<AttrContext> env) {
257 Env<AttrContext> prevEnv = this.env;
258 try {
259 this.env = env;
260 tree.accept(this);
261 return result;
262 } catch (CompletionFailure ex) {
263 return chk.completionError(tree.pos(), ex);
264 } finally {
265 this.env = prevEnv;
266 }
267 }
269 /** Visitor method: enter classes of a list of trees, returning a list of types.
270 */
271 <T extends JCTree> List<Type> classEnter(List<T> trees, Env<AttrContext> env) {
272 ListBuffer<Type> ts = new ListBuffer<Type>();
273 for (List<T> l = trees; l.nonEmpty(); l = l.tail) {
274 Type t = classEnter(l.head, env);
275 if (t != null)
276 ts.append(t);
277 }
278 return ts.toList();
279 }
281 @Override
282 public void visitTopLevel(JCCompilationUnit tree) {
283 JavaFileObject prev = log.useSource(tree.sourcefile);
284 boolean addEnv = false;
285 boolean isPkgInfo = tree.sourcefile.isNameCompatible("package-info",
286 JavaFileObject.Kind.SOURCE);
287 if (tree.pid != null) {
288 tree.packge = reader.enterPackage(TreeInfo.fullName(tree.pid));
289 if (tree.packageAnnotations.nonEmpty() || pkginfoOpt == PkgInfo.ALWAYS) {
290 if (isPkgInfo) {
291 addEnv = true;
292 } else {
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.get(tree) != null)) {
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.ClassScope(c, scopeCounter);
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.ClassScope(c, scopeCounter);
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 }