Enter.java revision 2571:10fc81ac75b4
1/*
2 * Copyright (c) 1999, 2014, 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
26package com.sun.tools.javac.comp;
27
28import java.util.*;
29import javax.tools.JavaFileObject;
30import javax.tools.JavaFileManager;
31
32import com.sun.tools.javac.code.*;
33import com.sun.tools.javac.code.Scope.*;
34import com.sun.tools.javac.code.Symbol.*;
35import com.sun.tools.javac.code.Type.*;
36import com.sun.tools.javac.jvm.*;
37import com.sun.tools.javac.main.Option.PkgInfo;
38import com.sun.tools.javac.tree.*;
39import com.sun.tools.javac.tree.JCTree.*;
40import com.sun.tools.javac.util.*;
41import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
42import com.sun.tools.javac.util.List;
43
44
45import static com.sun.tools.javac.code.Flags.*;
46import static com.sun.tools.javac.code.Kinds.*;
47
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 */
92public class Enter extends JCTree.Visitor {
93    protected static final Context.Key<Enter> enterKey = new Context.Key<>();
94
95    Log log;
96    Symtab syms;
97    Check chk;
98    TreeMaker make;
99    Annotate annotate;
100    MemberEnter memberEnter;
101    Types types;
102    Lint lint;
103    Names names;
104    JavaFileManager fileManager;
105    PkgInfo pkginfoOpt;
106    TypeEnvs typeEnvs;
107
108    private final Todo todo;
109
110    public static Enter instance(Context context) {
111        Enter instance = context.get(enterKey);
112        if (instance == null)
113            instance = new Enter(context);
114        return instance;
115    }
116
117    protected Enter(Context context) {
118        context.put(enterKey, this);
119
120        log = Log.instance(context);
121        make = TreeMaker.instance(context);
122        syms = Symtab.instance(context);
123        chk = Check.instance(context);
124        memberEnter = MemberEnter.instance(context);
125        types = Types.instance(context);
126        annotate = Annotate.instance(context);
127        lint = Lint.instance(context);
128        names = Names.instance(context);
129
130        predefClassDef = make.ClassDef(
131            make.Modifiers(PUBLIC),
132            syms.predefClass.name,
133            List.<JCTypeParameter>nil(),
134            null,
135            List.<JCExpression>nil(),
136            List.<JCTree>nil());
137        predefClassDef.sym = syms.predefClass;
138        todo = Todo.instance(context);
139        fileManager = context.get(JavaFileManager.class);
140
141        Options options = Options.instance(context);
142        pkginfoOpt = PkgInfo.get(options);
143        typeEnvs = TypeEnvs.instance(context);
144    }
145
146    /** Accessor for typeEnvs
147     */
148    public Env<AttrContext> getEnv(TypeSymbol sym) {
149        return typeEnvs.get(sym);
150    }
151
152    public Iterable<Env<AttrContext>> getEnvs() {
153        return typeEnvs.values();
154    }
155
156    public Env<AttrContext> getClassEnv(TypeSymbol sym) {
157        Env<AttrContext> localEnv = getEnv(sym);
158        Env<AttrContext> lintEnv = localEnv;
159        while (lintEnv.info.lint == null)
160            lintEnv = lintEnv.next;
161        localEnv.info.lint = lintEnv.info.lint.augment(sym);
162        return localEnv;
163    }
164
165    /** The queue of all classes that might still need to be completed;
166     *  saved and initialized by main().
167     */
168    ListBuffer<ClassSymbol> uncompleted;
169
170    /** A dummy class to serve as enclClass for toplevel environments.
171     */
172    private JCClassDecl predefClassDef;
173
174/* ************************************************************************
175 * environment construction
176 *************************************************************************/
177
178
179    /** Create a fresh environment for class bodies.
180     *  This will create a fresh scope for local symbols of a class, referred
181     *  to by the environments info.scope field.
182     *  This scope will contain
183     *    - symbols for this and super
184     *    - symbols for any type parameters
185     *  In addition, it serves as an anchor for scopes of methods and initializers
186     *  which are nested in this scope via Scope.dup().
187     *  This scope should not be confused with the members scope of a class.
188     *
189     *  @param tree     The class definition.
190     *  @param env      The environment current outside of the class definition.
191     */
192    public Env<AttrContext> classEnv(JCClassDecl tree, Env<AttrContext> env) {
193        Env<AttrContext> localEnv =
194            env.dup(tree, env.info.dup(WriteableScope.create(tree.sym)));
195        localEnv.enclClass = tree;
196        localEnv.outer = env;
197        localEnv.info.isSelfCall = false;
198        localEnv.info.lint = null; // leave this to be filled in by Attr,
199                                   // when annotations have been processed
200        return localEnv;
201    }
202
203    /** Create a fresh environment for toplevels.
204     *  @param tree     The toplevel tree.
205     */
206    Env<AttrContext> topLevelEnv(JCCompilationUnit tree) {
207        Env<AttrContext> localEnv = new Env<>(tree, new AttrContext());
208        localEnv.toplevel = tree;
209        localEnv.enclClass = predefClassDef;
210        tree.toplevelScope = WriteableScope.create(tree.packge);
211        tree.namedImportScope = new NamedImportScope(tree.packge, tree.toplevelScope);
212        tree.starImportScope = new StarImportScope(tree.packge);
213        localEnv.info.scope = tree.toplevelScope;
214        localEnv.info.lint = lint;
215        return localEnv;
216    }
217
218    public Env<AttrContext> getTopLevelEnv(JCCompilationUnit tree) {
219        Env<AttrContext> localEnv = new Env<>(tree, new AttrContext());
220        localEnv.toplevel = tree;
221        localEnv.enclClass = predefClassDef;
222        localEnv.info.scope = tree.toplevelScope;
223        localEnv.info.lint = lint;
224        return localEnv;
225    }
226
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    WriteableScope enterScope(Env<AttrContext> env) {
233        return (env.tree.hasTag(JCTree.Tag.CLASSDEF))
234            ? ((JCClassDecl) env.tree).sym.members_field
235            : env.info.scope;
236    }
237
238/* ************************************************************************
239 * Visitor methods for phase 1: class enter
240 *************************************************************************/
241
242    /** Visitor argument: the current environment.
243     */
244    protected Env<AttrContext> env;
245
246    /** Visitor result: the computed type.
247     */
248    Type result;
249
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    }
268
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<>();
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    }
280
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        JCPackageDecl pd = tree.getPackage();
288        if (pd != null) {
289            tree.packge = pd.packge = syms.enterPackage(TreeInfo.fullName(pd.pid));
290            if (   pd.annotations.nonEmpty()
291                || pkginfoOpt == PkgInfo.ALWAYS
292                || tree.docComments != null) {
293                if (isPkgInfo) {
294                    addEnv = true;
295                } else if (pd.annotations.nonEmpty()) {
296                    log.error(pd.annotations.head.pos(),
297                              "pkg.annotations.sb.in.package-info.java");
298                }
299            }
300        } else {
301            tree.packge = syms.unnamedPackage;
302        }
303        tree.packge.complete(); // Find all classes in package.
304        Env<AttrContext> topEnv = topLevelEnv(tree);
305        Env<AttrContext> packageEnv = isPkgInfo ? topEnv.dup(pd) : null;
306
307        // Save environment of package-info.java file.
308        if (isPkgInfo) {
309            Env<AttrContext> env0 = typeEnvs.get(tree.packge);
310            if (env0 != null) {
311                JCCompilationUnit tree0 = env0.toplevel;
312                if (!fileManager.isSameFile(tree.sourcefile, tree0.sourcefile)) {
313                    log.warning(pd != null ? pd.pid.pos() : null,
314                                "pkg-info.already.seen",
315                                tree.packge);
316                }
317            }
318            typeEnvs.put(tree.packge, packageEnv);
319
320            for (Symbol q = tree.packge; q != null && q.kind == PCK; q = q.owner)
321                q.flags_field |= EXISTS;
322
323            Name name = names.package_info;
324            ClassSymbol c = syms.enterClass(name, tree.packge);
325            c.flatname = names.fromString(tree.packge + "." + name);
326            c.sourcefile = tree.sourcefile;
327            c.completer = null;
328            c.members_field = WriteableScope.create(c);
329            tree.packge.package_info = c;
330        }
331        classEnter(tree.defs, topEnv);
332        if (addEnv) {
333            todo.append(packageEnv);
334        }
335        log.useSource(prev);
336        result = null;
337    }
338
339    @Override
340    public void visitClassDef(JCClassDecl tree) {
341        Symbol owner = env.info.scope.owner;
342        WriteableScope enclScope = enterScope(env);
343        ClassSymbol c;
344        if (owner.kind == PCK) {
345            // We are seeing a toplevel class.
346            PackageSymbol packge = (PackageSymbol)owner;
347            for (Symbol q = packge; q != null && q.kind == PCK; q = q.owner)
348                q.flags_field |= EXISTS;
349            c = syms.enterClass(tree.name, packge);
350            packge.members().enterIfAbsent(c);
351            if ((tree.mods.flags & PUBLIC) != 0 && !classNameMatchesFileName(c, env)) {
352                log.error(tree.pos(),
353                          "class.public.should.be.in.file", tree.name);
354            }
355        } else {
356            if (!tree.name.isEmpty() &&
357                !chk.checkUniqueClassName(tree.pos(), tree.name, enclScope)) {
358                result = null;
359                return;
360            }
361            if (owner.kind == TYP) {
362                // We are seeing a member class.
363                c = syms.enterClass(tree.name, (TypeSymbol)owner);
364                if ((owner.flags_field & INTERFACE) != 0) {
365                    tree.mods.flags |= PUBLIC | STATIC;
366                }
367            } else {
368                // We are seeing a local class.
369                c = syms.defineClass(tree.name, owner);
370                c.flatname = chk.localClassName(c);
371                if (!c.name.isEmpty())
372                    chk.checkTransparentClass(tree.pos(), c, env.info.scope);
373            }
374        }
375        tree.sym = c;
376
377        // Enter class into `compiled' table and enclosing scope.
378        if (chk.compiled.get(c.flatname) != null) {
379            duplicateClass(tree.pos(), c);
380            result = types.createErrorType(tree.name, (TypeSymbol)owner, Type.noType);
381            tree.sym = (ClassSymbol)result.tsym;
382            return;
383        }
384        chk.compiled.put(c.flatname, c);
385        enclScope.enter(c);
386
387        // Set up an environment for class block and store in `typeEnvs'
388        // table, to be retrieved later in memberEnter and attribution.
389        Env<AttrContext> localEnv = classEnv(tree, env);
390        typeEnvs.put(c, localEnv);
391
392        // Fill out class fields.
393        c.completer = memberEnter;
394        c.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, c, tree);
395        c.sourcefile = env.toplevel.sourcefile;
396        c.members_field = WriteableScope.create(c);
397
398        ClassType ct = (ClassType)c.type;
399        if (owner.kind != PCK && (c.flags_field & STATIC) == 0) {
400            // We are seeing a local or inner class.
401            // Set outer_field of this class to closest enclosing class
402            // which contains this class in a non-static context
403            // (its "enclosing instance class"), provided such a class exists.
404            Symbol owner1 = owner;
405            while ((owner1.kind & (VAR | MTH)) != 0 &&
406                   (owner1.flags_field & STATIC) == 0) {
407                owner1 = owner1.owner;
408            }
409            if (owner1.kind == TYP) {
410                ct.setEnclosingType(owner1.type);
411            }
412        }
413
414        // Enter type parameters.
415        ct.typarams_field = classEnter(tree.typarams, localEnv);
416
417        // Add non-local class to uncompleted, to make sure it will be
418        // completed later.
419        if (!c.isLocal() && uncompleted != null) uncompleted.append(c);
420//      System.err.println("entering " + c.fullname + " in " + c.owner);//DEBUG
421
422        // Recursively enter all member classes.
423        classEnter(tree.defs, localEnv);
424
425        result = c.type;
426    }
427    //where
428        /** Does class have the same name as the file it appears in?
429         */
430        private static boolean classNameMatchesFileName(ClassSymbol c,
431                                                        Env<AttrContext> env) {
432            return env.toplevel.sourcefile.isNameCompatible(c.name.toString(),
433                                                            JavaFileObject.Kind.SOURCE);
434        }
435
436    /** Complain about a duplicate class. */
437    protected void duplicateClass(DiagnosticPosition pos, ClassSymbol c) {
438        log.error(pos, "duplicate.class", c.fullname);
439    }
440
441    /** Class enter visitor method for type parameters.
442     *  Enter a symbol for type parameter in local scope, after checking that it
443     *  is unique.
444     */
445    @Override
446    public void visitTypeParameter(JCTypeParameter tree) {
447        TypeVar a = (tree.type != null)
448            ? (TypeVar)tree.type
449            : new TypeVar(tree.name, env.info.scope.owner, syms.botType);
450        tree.type = a;
451        if (chk.checkUnique(tree.pos(), a.tsym, env.info.scope)) {
452            env.info.scope.enter(a.tsym);
453        }
454        result = a;
455    }
456
457    /** Default class enter visitor method: do nothing.
458     */
459    @Override
460    public void visitTree(JCTree tree) {
461        result = null;
462    }
463
464    /** Main method: enter all classes in a list of toplevel trees.
465     *  @param trees      The list of trees to be processed.
466     */
467    public void main(List<JCCompilationUnit> trees) {
468        complete(trees, null);
469    }
470
471    /** Main method: enter one class from a list of toplevel trees and
472     *  place the rest on uncompleted for later processing.
473     *  @param trees      The list of trees to be processed.
474     *  @param c          The class symbol to be processed.
475     */
476    public void complete(List<JCCompilationUnit> trees, ClassSymbol c) {
477        annotate.enterStart();
478        ListBuffer<ClassSymbol> prevUncompleted = uncompleted;
479        if (memberEnter.completionEnabled) uncompleted = new ListBuffer<>();
480
481        try {
482            // enter all classes, and construct uncompleted list
483            classEnter(trees, null);
484
485            // complete all uncompleted classes in memberEnter
486            if  (memberEnter.completionEnabled) {
487                while (uncompleted.nonEmpty()) {
488                    ClassSymbol clazz = uncompleted.next();
489                    if (c == null || c == clazz || prevUncompleted == null)
490                        clazz.complete();
491                    else
492                        // defer
493                        prevUncompleted.append(clazz);
494                }
495
496                // if there remain any unimported toplevels (these must have
497                // no classes at all), process their import statements as well.
498                for (JCCompilationUnit tree : trees) {
499                    if (tree.starImportScope.isEmpty()) {
500                        JavaFileObject prev = log.useSource(tree.sourcefile);
501                        Env<AttrContext> topEnv = topLevelEnv(tree);
502                        memberEnter.memberEnter(tree, topEnv);
503                        log.useSource(prev);
504                    }
505                }
506            }
507        } finally {
508            uncompleted = prevUncompleted;
509            annotate.enterDone();
510        }
511    }
512
513    public void newRound() {
514        typeEnvs.clear();
515    }
516}
517