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