001: /*
002: * Copyright 1999-2006 Sun Microsystems, Inc. All Rights Reserved.
003: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
004: *
005: * This code is free software; you can redistribute it and/or modify it
006: * under the terms of the GNU General Public License version 2 only, as
007: * published by the Free Software Foundation. Sun designates this
008: * particular file as subject to the "Classpath" exception as provided
009: * by Sun in the LICENSE file that accompanied this code.
010: *
011: * This code is distributed in the hope that it will be useful, but WITHOUT
012: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
013: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
014: * version 2 for more details (a copy is included in the LICENSE file that
015: * accompanied this code).
016: *
017: * You should have received a copy of the GNU General Public License version
018: * 2 along with this work; if not, write to the Free Software Foundation,
019: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
020: *
021: * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
022: * CA 95054 USA or visit www.sun.com if you need additional information or
023: * have any questions.
024: */
025:
026: package com.sun.tools.javac.comp;
027:
028: import java.util.*;
029: import java.util.Set;
030: import javax.tools.JavaFileObject;
031: import javax.tools.JavaFileManager;
032:
033: import com.sun.tools.javac.code.*;
034: import com.sun.tools.javac.jvm.*;
035: import com.sun.tools.javac.tree.*;
036: import com.sun.tools.javac.util.*;
037: import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
038: import com.sun.tools.javac.util.List;
039:
040: import com.sun.tools.javac.code.Type.*;
041: import com.sun.tools.javac.code.Symbol.*;
042: import com.sun.tools.javac.tree.JCTree.*;
043:
044: import static com.sun.tools.javac.code.Flags.*;
045: import static com.sun.tools.javac.code.Kinds.*;
046: import static com.sun.tools.javac.code.TypeTags.*;
047:
048: /** This class enters symbols for all encountered definitions into
049: * the symbol table. The pass consists of two phases, organized as
050: * follows:
051: *
052: * <p>In the first phase, all class symbols are intered into their
053: * enclosing scope, descending recursively down the tree for classes
054: * which are members of other classes. The class symbols are given a
055: * MemberEnter object as completer.
056: *
057: * <p>In the second phase classes are completed using
058: * MemberEnter.complete(). Completion might occur on demand, but
059: * any classes that are not completed that way will be eventually
060: * completed by processing the `uncompleted' queue. Completion
061: * entails (1) determination of a class's parameters, supertype and
062: * interfaces, as well as (2) entering all symbols defined in the
063: * class into its scope, with the exception of class symbols which
064: * have been entered in phase 1. (2) depends on (1) having been
065: * completed for a class and all its superclasses and enclosing
066: * classes. That's why, after doing (1), we put classes in a
067: * `halfcompleted' queue. Only when we have performed (1) for a class
068: * and all it's superclasses and enclosing classes, we proceed to
069: * (2).
070: *
071: * <p>Whereas the first phase is organized as a sweep through all
072: * compiled syntax trees, the second phase is demand. Members of a
073: * class are entered when the contents of a class are first
074: * accessed. This is accomplished by installing completer objects in
075: * class symbols for compiled classes which invoke the member-enter
076: * phase for the corresponding class tree.
077: *
078: * <p>Classes migrate from one phase to the next via queues:
079: *
080: * <pre>
081: * class enter -> (Enter.uncompleted) --> member enter (1)
082: * -> (MemberEnter.halfcompleted) --> member enter (2)
083: * -> (Todo) --> attribute
084: * (only for toplevel classes)
085: * </pre>
086: *
087: * <p><b>This is NOT part of any API supported by Sun Microsystems. If
088: * you write code that depends on this, you do so at your own risk.
089: * This code and its internal interfaces are subject to change or
090: * deletion without notice.</b>
091: */
092: @Version("@(#)Enter.java 1.141 07/06/14")
093: public class Enter extends JCTree.Visitor {
094: protected static final Context.Key<Enter> enterKey = new Context.Key<Enter>();
095:
096: Log log;
097: Symtab syms;
098: Check chk;
099: TreeMaker make;
100: ClassReader reader;
101: Annotate annotate;
102: MemberEnter memberEnter;
103: Lint lint;
104: JavaFileManager fileManager;
105:
106: private final Todo todo;
107:
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: }
114:
115: protected Enter(Context context) {
116: context.put(enterKey, this );
117:
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: annotate = Annotate.instance(context);
125: lint = Lint.instance(context);
126:
127: predefClassDef = make.ClassDef(make.Modifiers(PUBLIC),
128: syms.predefClass.name, null, null, null, null);
129: predefClassDef.sym = syms.predefClass;
130: todo = Todo.instance(context);
131: fileManager = context.get(JavaFileManager.class);
132: }
133:
134: /** A hashtable mapping classes and packages to the environments current
135: * at the points of their definitions.
136: */
137: Map<TypeSymbol, Env<AttrContext>> typeEnvs = new HashMap<TypeSymbol, Env<AttrContext>>();
138:
139: /** Accessor for typeEnvs
140: */
141: public Env<AttrContext> getEnv(TypeSymbol sym) {
142: return typeEnvs.get(sym);
143: }
144:
145: public Env<AttrContext> getClassEnv(TypeSymbol sym) {
146: Env<AttrContext> localEnv = getEnv(sym);
147: Env<AttrContext> lintEnv = localEnv;
148: while (lintEnv.info.lint == null)
149: lintEnv = lintEnv.next;
150: localEnv.info.lint = lintEnv.info.lint.augment(
151: sym.attributes_field, sym.flags());
152: return localEnv;
153: }
154:
155: /** The queue of all classes that might still need to be completed;
156: * saved and initialized by main().
157: */
158: ListBuffer<ClassSymbol> uncompleted;
159:
160: /** A dummy class to serve as enclClass for toplevel environments.
161: */
162: private JCClassDecl predefClassDef;
163:
164: /* ************************************************************************
165: * environment construction
166: *************************************************************************/
167:
168: /** Create a fresh environment for class bodies.
169: * This will create a fresh scope for local symbols of a class, referred
170: * to by the environments info.scope field.
171: * This scope will contain
172: * - symbols for this and super
173: * - symbols for any type parameters
174: * In addition, it serves as an anchor for scopes of methods and initializers
175: * which are nested in this scope via Scope.dup().
176: * This scope should not be confused with the members scope of a class.
177: *
178: * @param tree The class definition.
179: * @param env The environment current outside of the class definition.
180: */
181: public Env<AttrContext> classEnv(JCClassDecl tree,
182: Env<AttrContext> env) {
183: Env<AttrContext> localEnv = env.dup(tree, env.info
184: .dup(new Scope(tree.sym)));
185: localEnv.enclClass = tree;
186: localEnv.outer = env;
187: localEnv.info.isSelfCall = false;
188: localEnv.info.lint = null; // leave this to be filled in by Attr,
189: // when annotations have been processed
190: return localEnv;
191: }
192:
193: /** Create a fresh environment for toplevels.
194: * @param tree The toplevel tree.
195: */
196: Env<AttrContext> topLevelEnv(JCCompilationUnit tree) {
197: Env<AttrContext> localEnv = new Env<AttrContext>(tree,
198: new AttrContext());
199: localEnv.toplevel = tree;
200: localEnv.enclClass = predefClassDef;
201: tree.namedImportScope = new Scope.ImportScope(tree.packge);
202: tree.starImportScope = new Scope.ImportScope(tree.packge);
203: localEnv.info.scope = tree.namedImportScope;
204: localEnv.info.lint = lint;
205: return localEnv;
206: }
207:
208: public Env<AttrContext> getTopLevelEnv(JCCompilationUnit tree) {
209: Env<AttrContext> localEnv = new Env<AttrContext>(tree,
210: new AttrContext());
211: localEnv.toplevel = tree;
212: localEnv.enclClass = predefClassDef;
213: localEnv.info.scope = tree.namedImportScope;
214: localEnv.info.lint = lint;
215: return localEnv;
216: }
217:
218: /** The scope in which a member definition in environment env is to be entered
219: * This is usually the environment's scope, except for class environments,
220: * where the local scope is for type variables, and the this and super symbol
221: * only, and members go into the class member scope.
222: */
223: Scope enterScope(Env<AttrContext> env) {
224: return (env.tree.getTag() == JCTree.CLASSDEF) ? ((JCClassDecl) env.tree).sym.members_field
225: : env.info.scope;
226: }
227:
228: /* ************************************************************************
229: * Visitor methods for phase 1: class enter
230: *************************************************************************/
231:
232: /** Visitor argument: the current environment.
233: */
234: protected Env<AttrContext> env;
235:
236: /** Visitor result: the computed type.
237: */
238: Type result;
239:
240: /** Visitor method: enter all classes in given tree, catching any
241: * completion failure exceptions. Return the tree's type.
242: *
243: * @param tree The tree to be visited.
244: * @param env The environment visitor argument.
245: */
246: Type classEnter(JCTree tree, Env<AttrContext> env) {
247: Env<AttrContext> prevEnv = this .env;
248: try {
249: this .env = env;
250: tree.accept(this );
251: return result;
252: } catch (CompletionFailure ex) {
253: return chk.completionError(tree.pos(), ex);
254: } finally {
255: this .env = prevEnv;
256: }
257: }
258:
259: /** Visitor method: enter classes of a list of trees, returning a list of types.
260: */
261: <T extends JCTree> List<Type> classEnter(List<T> trees,
262: Env<AttrContext> env) {
263: ListBuffer<Type> ts = new ListBuffer<Type>();
264: for (List<T> l = trees; l.nonEmpty(); l = l.tail)
265: ts.append(classEnter(l.head, env));
266: return ts.toList();
267: }
268:
269: public void visitTopLevel(JCCompilationUnit tree) {
270: JavaFileObject prev = log.useSource(tree.sourcefile);
271: boolean addEnv = false;
272: boolean isPkgInfo = tree.sourcefile.isNameCompatible(
273: "package-info", JavaFileObject.Kind.SOURCE);
274: if (tree.pid != null) {
275: tree.packge = reader.enterPackage(TreeInfo
276: .fullName(tree.pid));
277: if (tree.packageAnnotations.nonEmpty()) {
278: if (isPkgInfo) {
279: addEnv = true;
280: } else {
281: log.error(tree.packageAnnotations.head.pos(),
282: "pkg.annotations.sb.in.package-info.java");
283: }
284: }
285: } else {
286: tree.packge = syms.unnamedPackage;
287: }
288: tree.packge.complete(); // Find all classes in package.
289: Env<AttrContext> env = topLevelEnv(tree);
290:
291: // Save environment of package-info.java file.
292: if (isPkgInfo) {
293: Env<AttrContext> env0 = typeEnvs.get(tree.packge);
294: if (env0 == null) {
295: typeEnvs.put(tree.packge, env);
296: } else {
297: JCCompilationUnit tree0 = env0.toplevel;
298: if (!fileManager.isSameFile(tree.sourcefile,
299: tree0.sourcefile)) {
300: log.warning(tree.pid != null ? tree.pid.pos()
301: : null, "pkg-info.already.seen",
302: tree.packge);
303: if (addEnv
304: || (tree0.packageAnnotations.isEmpty()
305: && tree.docComments != null && tree.docComments
306: .get(tree) != null)) {
307: typeEnvs.put(tree.packge, env);
308: }
309: }
310: }
311: }
312: classEnter(tree.defs, env);
313: if (addEnv) {
314: todo.append(env);
315: }
316: log.useSource(prev);
317: result = null;
318: }
319:
320: public void visitClassDef(JCClassDecl tree) {
321: Symbol owner = env.info.scope.owner;
322: Scope enclScope = enterScope(env);
323: ClassSymbol c;
324: if (owner.kind == PCK) {
325: // We are seeing a toplevel class.
326: PackageSymbol packge = (PackageSymbol) owner;
327: for (Symbol q = packge; q != null && q.kind == PCK; q = q.owner)
328: q.flags_field |= EXISTS;
329: c = reader.enterClass(tree.name, packge);
330: packge.members().enterIfAbsent(c);
331: if ((tree.mods.flags & PUBLIC) != 0
332: && !classNameMatchesFileName(c, env)) {
333: log.error(tree.pos(), "class.public.should.be.in.file",
334: tree.name);
335: }
336: } else {
337: if (tree.name.len != 0
338: && !chk.checkUniqueClassName(tree.pos(), tree.name,
339: enclScope)) {
340: result = null;
341: return;
342: }
343: if (owner.kind == TYP) {
344: // We are seeing a member class.
345: c = reader.enterClass(tree.name, (TypeSymbol) owner);
346: if ((owner.flags_field & INTERFACE) != 0) {
347: tree.mods.flags |= PUBLIC | STATIC;
348: }
349: } else {
350: // We are seeing a local class.
351: c = reader.defineClass(tree.name, owner);
352: c.flatname = chk.localClassName(c);
353: if (c.name.len != 0)
354: chk.checkTransparentClass(tree.pos(), c,
355: env.info.scope);
356: }
357: }
358: tree.sym = c;
359:
360: // Enter class into `compiled' table and enclosing scope.
361: if (chk.compiled.get(c.flatname) != null) {
362: duplicateClass(tree.pos(), c);
363: result = new ErrorType(tree.name, (TypeSymbol) owner);
364: tree.sym = (ClassSymbol) result.tsym;
365: return;
366: }
367: chk.compiled.put(c.flatname, c);
368: enclScope.enter(c);
369:
370: // Set up an environment for class block and store in `typeEnvs'
371: // table, to be retrieved later in memberEnter and attribution.
372: Env<AttrContext> localEnv = classEnv(tree, env);
373: typeEnvs.put(c, localEnv);
374:
375: // Fill out class fields.
376: c.completer = memberEnter;
377: c.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, c,
378: tree);
379: c.sourcefile = env.toplevel.sourcefile;
380: c.members_field = new Scope(c);
381:
382: ClassType ct = (ClassType) c.type;
383: if (owner.kind != PCK && (c.flags_field & STATIC) == 0) {
384: // We are seeing a local or inner class.
385: // Set outer_field of this class to closest enclosing class
386: // which contains this class in a non-static context
387: // (its "enclosing instance class"), provided such a class exists.
388: Symbol owner1 = owner;
389: while ((owner1.kind & (VAR | MTH)) != 0
390: && (owner1.flags_field & STATIC) == 0) {
391: owner1 = owner1.owner;
392: }
393: if (owner1.kind == TYP) {
394: ct.setEnclosingType(owner1.type);
395: }
396: }
397:
398: // Enter type parameters.
399: ct.typarams_field = classEnter(tree.typarams, localEnv);
400:
401: // Add non-local class to uncompleted, to make sure it will be
402: // completed later.
403: if (!c.isLocal() && uncompleted != null)
404: uncompleted.append(c);
405: // System.err.println("entering " + c.fullname + " in " + c.owner);//DEBUG
406:
407: // Recursively enter all member classes.
408: classEnter(tree.defs, localEnv);
409:
410: result = c.type;
411: }
412:
413: //where
414: /** Does class have the same name as the file it appears in?
415: */
416: private static boolean classNameMatchesFileName(ClassSymbol c,
417: Env<AttrContext> env) {
418: return env.toplevel.sourcefile.isNameCompatible(c.name
419: .toString(), JavaFileObject.Kind.SOURCE);
420: }
421:
422: /** Complain about a duplicate class. */
423: protected void duplicateClass(DiagnosticPosition pos, ClassSymbol c) {
424: log.error(pos, "duplicate.class", c.fullname);
425: }
426:
427: /** Class enter visitor method for type parameters.
428: * Enter a symbol for type parameter in local scope, after checking that it
429: * is unique.
430: */
431: public void visitTypeParameter(JCTypeParameter tree) {
432: TypeVar a = (tree.type != null) ? (TypeVar) tree.type
433: : new TypeVar(tree.name, env.info.scope.owner,
434: syms.botType);
435: tree.type = a;
436: if (chk.checkUnique(tree.pos(), a.tsym, env.info.scope)) {
437: env.info.scope.enter(a.tsym);
438: }
439: result = a;
440: }
441:
442: /** Default class enter visitor method: do nothing.
443: */
444: public void visitTree(JCTree tree) {
445: result = null;
446: }
447:
448: /** Main method: enter all classes in a list of toplevel trees.
449: * @param trees The list of trees to be processed.
450: */
451: public void main(List<JCCompilationUnit> trees) {
452: complete(trees, null);
453: }
454:
455: /** Main method: enter one class from a list of toplevel trees and
456: * place the rest on uncompleted for later processing.
457: * @param trees The list of trees to be processed.
458: * @param c The class symbol to be processed.
459: */
460: public void complete(List<JCCompilationUnit> trees, ClassSymbol c) {
461: annotate.enterStart();
462: ListBuffer<ClassSymbol> prevUncompleted = uncompleted;
463: if (memberEnter.completionEnabled)
464: uncompleted = new ListBuffer<ClassSymbol>();
465:
466: try {
467: // enter all classes, and construct uncompleted list
468: classEnter(trees, null);
469:
470: // complete all uncompleted classes in memberEnter
471: if (memberEnter.completionEnabled) {
472: while (uncompleted.nonEmpty()) {
473: ClassSymbol clazz = uncompleted.next();
474: if (c == null || c == clazz
475: || prevUncompleted == null)
476: clazz.complete();
477: else
478: // defer
479: prevUncompleted.append(clazz);
480: }
481:
482: // if there remain any unimported toplevels (these must have
483: // no classes at all), process their import statements as well.
484: for (JCCompilationUnit tree : trees) {
485: if (tree.starImportScope.elems == null) {
486: JavaFileObject prev = log
487: .useSource(tree.sourcefile);
488: Env<AttrContext> env = typeEnvs.get(tree);
489: if (env == null)
490: env = topLevelEnv(tree);
491: memberEnter.memberEnter(tree, env);
492: log.useSource(prev);
493: }
494: }
495: }
496: } finally {
497: uncompleted = prevUncompleted;
498: annotate.enterDone();
499: }
500: }
501: }
|