TypeEnter.java revision 3043:4914b013c305
1/*
2 * Copyright (c) 2003, 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 java.util.HashSet;
29import java.util.Set;
30import java.util.function.BiConsumer;
31
32import javax.tools.JavaFileObject;
33
34import com.sun.tools.javac.code.*;
35import com.sun.tools.javac.code.Lint.LintCategory;
36import com.sun.tools.javac.code.Scope.ImportFilter;
37import com.sun.tools.javac.code.Scope.NamedImportScope;
38import com.sun.tools.javac.code.Scope.StarImportScope;
39import com.sun.tools.javac.code.Scope.WriteableScope;
40import com.sun.tools.javac.comp.Annotate.AnnotationTypeMetadata;
41import com.sun.tools.javac.tree.*;
42import com.sun.tools.javac.util.*;
43import com.sun.tools.javac.util.DefinedBy.Api;
44
45import com.sun.tools.javac.code.Symbol.*;
46import com.sun.tools.javac.code.Type.*;
47import com.sun.tools.javac.tree.JCTree.*;
48
49import static com.sun.tools.javac.code.Flags.*;
50import static com.sun.tools.javac.code.Flags.ANNOTATION;
51import static com.sun.tools.javac.code.Scope.LookupKind.NON_RECURSIVE;
52import static com.sun.tools.javac.code.Kinds.Kind.*;
53import static com.sun.tools.javac.code.TypeTag.CLASS;
54import static com.sun.tools.javac.code.TypeTag.ERROR;
55import static com.sun.tools.javac.tree.JCTree.Tag.*;
56
57import com.sun.tools.javac.util.Dependencies.AttributionKind;
58import com.sun.tools.javac.util.Dependencies.CompletionCause;
59import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
60import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
61
62/** This is the second phase of Enter, in which classes are completed
63 *  by resolving their headers and entering their members in the into
64 *  the class scope. See Enter for an overall overview.
65 *
66 *  This class uses internal phases to process the classes. When a phase
67 *  processes classes, the lower phases are not invoked until all classes
68 *  pass through the current phase. Note that it is possible that upper phases
69 *  are run due to recursive completion. The internal phases are:
70 *  - ImportPhase: shallow pass through imports, adds information about imports
71 *                 the NamedImportScope and StarImportScope, but avoids queries
72 *                 about class hierarchy.
73 *  - HierarchyPhase: resolves the supertypes of the given class. Does not handle
74 *                    type parameters of the class or type argument of the supertypes.
75 *  - HeaderPhase: finishes analysis of the header of the given class by resolving
76 *                 type parameters, attributing supertypes including type arguments
77 *                 and scheduling full annotation attribution. This phase also adds
78 *                 a synthetic default constructor if needed and synthetic "this" field.
79 *  - MembersPhase: resolves headers for fields, methods and constructors in the given class.
80 *                  Also generates synthetic enum members.
81 *
82 *  <p><b>This is NOT part of any supported API.
83 *  If you write code that depends on this, you do so at your own risk.
84 *  This code and its internal interfaces are subject to change or
85 *  deletion without notice.</b>
86 */
87public class TypeEnter implements Completer {
88    protected static final Context.Key<TypeEnter> typeEnterKey = new Context.Key<>();
89
90    /** A switch to determine whether we check for package/class conflicts
91     */
92    final static boolean checkClash = true;
93
94    private final Names names;
95    private final Enter enter;
96    private final MemberEnter memberEnter;
97    private final Log log;
98    private final Check chk;
99    private final Attr attr;
100    private final Symtab syms;
101    private final TreeMaker make;
102    private final Todo todo;
103    private final Annotate annotate;
104    private final TypeAnnotations typeAnnotations;
105    private final Types types;
106    private final JCDiagnostic.Factory diags;
107    private final Source source;
108    private final DeferredLintHandler deferredLintHandler;
109    private final Lint lint;
110    private final TypeEnvs typeEnvs;
111    private final Dependencies dependencies;
112
113    public static TypeEnter instance(Context context) {
114        TypeEnter instance = context.get(typeEnterKey);
115        if (instance == null)
116            instance = new TypeEnter(context);
117        return instance;
118    }
119
120    protected TypeEnter(Context context) {
121        context.put(typeEnterKey, this);
122        names = Names.instance(context);
123        enter = Enter.instance(context);
124        memberEnter = MemberEnter.instance(context);
125        log = Log.instance(context);
126        chk = Check.instance(context);
127        attr = Attr.instance(context);
128        syms = Symtab.instance(context);
129        make = TreeMaker.instance(context);
130        todo = Todo.instance(context);
131        annotate = Annotate.instance(context);
132        typeAnnotations = TypeAnnotations.instance(context);
133        types = Types.instance(context);
134        diags = JCDiagnostic.Factory.instance(context);
135        source = Source.instance(context);
136        deferredLintHandler = DeferredLintHandler.instance(context);
137        lint = Lint.instance(context);
138        typeEnvs = TypeEnvs.instance(context);
139        dependencies = Dependencies.instance(context);
140        Source source = Source.instance(context);
141        allowTypeAnnos = source.allowTypeAnnotations();
142        allowDeprecationOnImport = source.allowDeprecationOnImport();
143    }
144
145    /** Switch: support type annotations.
146     */
147    boolean allowTypeAnnos;
148
149    /**
150     * Switch: should deprecation warnings be issued on import
151     */
152    boolean allowDeprecationOnImport;
153
154    /** A flag to disable completion from time to time during member
155     *  enter, as we only need to look up types.  This avoids
156     *  unnecessarily deep recursion.
157     */
158    boolean completionEnabled = true;
159
160    /* Verify Imports:
161     */
162    protected void ensureImportsChecked(List<JCCompilationUnit> trees) {
163        // if there remain any unimported toplevels (these must have
164        // no classes at all), process their import statements as well.
165        for (JCCompilationUnit tree : trees) {
166            if (!tree.starImportScope.isFilled()) {
167                Env<AttrContext> topEnv = enter.topLevelEnv(tree);
168                finishImports(tree, () -> { completeClass.resolveImports(tree, topEnv); });
169            }
170        }
171    }
172
173/* ********************************************************************
174 * Source completer
175 *********************************************************************/
176
177    /** Complete entering a class.
178     *  @param sym         The symbol of the class to be completed.
179     */
180    public void complete(Symbol sym) throws CompletionFailure {
181        // Suppress some (recursive) MemberEnter invocations
182        if (!completionEnabled) {
183            // Re-install same completer for next time around and return.
184            Assert.check((sym.flags() & Flags.COMPOUND) == 0);
185            sym.completer = this;
186            return;
187        }
188
189        try {
190            annotate.blockAnnotations();
191            sym.flags_field |= UNATTRIBUTED;
192
193            List<Env<AttrContext>> queue;
194
195            dependencies.push((ClassSymbol) sym, CompletionCause.MEMBER_ENTER);
196            try {
197                queue = completeClass.completeEnvs(List.of(typeEnvs.get((ClassSymbol) sym)));
198            } finally {
199                dependencies.pop();
200            }
201
202            if (!queue.isEmpty()) {
203                Set<JCCompilationUnit> seen = new HashSet<>();
204
205                for (Env<AttrContext> env : queue) {
206                    if (env.toplevel.defs.contains(env.enclClass) && seen.add(env.toplevel)) {
207                        finishImports(env.toplevel, () -> {});
208                    }
209                }
210            }
211        } finally {
212            annotate.unblockAnnotations();
213        }
214    }
215
216    void finishImports(JCCompilationUnit toplevel, Runnable resolve) {
217        JavaFileObject prev = log.useSource(toplevel.sourcefile);
218        try {
219            resolve.run();
220            chk.checkImportsUnique(toplevel);
221            chk.checkImportsResolvable(toplevel);
222            chk.checkImportedPackagesObservable(toplevel);
223            toplevel.namedImportScope.finalizeScope();
224            toplevel.starImportScope.finalizeScope();
225        } finally {
226            log.useSource(prev);
227        }
228    }
229
230    abstract class Phase {
231        private final ListBuffer<Env<AttrContext>> queue = new ListBuffer<>();
232        private final Phase next;
233        private final CompletionCause phaseName;
234
235        Phase(CompletionCause phaseName, Phase next) {
236            this.phaseName = phaseName;
237            this.next = next;
238        }
239
240        public final List<Env<AttrContext>> completeEnvs(List<Env<AttrContext>> envs) {
241            boolean firstToComplete = queue.isEmpty();
242
243            doCompleteEnvs(envs);
244
245            if (firstToComplete) {
246                List<Env<AttrContext>> out = queue.toList();
247
248                queue.clear();
249                return next != null ? next.completeEnvs(out) : out;
250            } else {
251                return List.nil();
252            }
253        }
254
255        protected void doCompleteEnvs(List<Env<AttrContext>> envs) {
256            for (Env<AttrContext> env : envs) {
257                JCClassDecl tree = (JCClassDecl)env.tree;
258
259                queue.add(env);
260
261                JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
262                DiagnosticPosition prevLintPos = deferredLintHandler.setPos(tree.pos());
263                try {
264                    dependencies.push(env.enclClass.sym, phaseName);
265                    runPhase(env);
266                } catch (CompletionFailure ex) {
267                    chk.completionError(tree.pos(), ex);
268                } finally {
269                    dependencies.pop();
270                    deferredLintHandler.setPos(prevLintPos);
271                    log.useSource(prev);
272                }
273            }
274        }
275
276        protected abstract void runPhase(Env<AttrContext> env);
277    }
278
279    private final ImportsPhase completeClass = new ImportsPhase();
280
281    /**Analyze import clauses.
282     */
283    private final class ImportsPhase extends Phase {
284
285        public ImportsPhase() {
286            super(CompletionCause.IMPORTS_PHASE, new HierarchyPhase());
287        }
288
289        Env<AttrContext> env;
290        ImportFilter staticImportFilter;
291        ImportFilter typeImportFilter;
292        BiConsumer<JCImport, CompletionFailure> cfHandler =
293                (imp, cf) -> chk.completionError(imp.pos(), cf);
294
295        @Override
296        protected void runPhase(Env<AttrContext> env) {
297            JCClassDecl tree = env.enclClass;
298            ClassSymbol sym = tree.sym;
299
300            // If sym is a toplevel-class, make sure any import
301            // clauses in its source file have been seen.
302            if (sym.owner.kind == PCK) {
303                resolveImports(env.toplevel, env.enclosing(TOPLEVEL));
304                todo.append(env);
305            }
306
307            if (sym.owner.kind == TYP)
308                sym.owner.complete();
309        }
310
311        private void resolveImports(JCCompilationUnit tree, Env<AttrContext> env) {
312            if (tree.starImportScope.isFilled()) {
313                // we must have already processed this toplevel
314                return;
315            }
316
317            ImportFilter prevStaticImportFilter = staticImportFilter;
318            ImportFilter prevTypeImportFilter = typeImportFilter;
319            DiagnosticPosition prevLintPos = deferredLintHandler.immediate();
320            Lint prevLint = chk.setLint(lint);
321            Env<AttrContext> prevEnv = this.env;
322            try {
323                this.env = env;
324                final PackageSymbol packge = env.toplevel.packge;
325                this.staticImportFilter =
326                        (origin, sym) -> sym.isStatic() &&
327                                         chk.importAccessible(sym, packge) &&
328                                         sym.isMemberOf((TypeSymbol) origin.owner, types);
329                this.typeImportFilter =
330                        (origin, sym) -> sym.kind == TYP &&
331                                         chk.importAccessible(sym, packge);
332
333                // Import-on-demand java.lang.
334                PackageSymbol javaLang = syms.enterPackage(names.java_lang);
335                if (javaLang.members().isEmpty() && !javaLang.exists())
336                    throw new FatalError(diags.fragment("fatal.err.no.java.lang"));
337                importAll(make.at(tree.pos()).Import(make.QualIdent(javaLang), false), javaLang, env);
338
339                // Process the package def and all import clauses.
340                if (tree.getPackage() != null)
341                    checkClassPackageClash(tree.getPackage());
342
343                for (JCImport imp : tree.getImports()) {
344                    doImport(imp);
345                }
346            } finally {
347                this.env = prevEnv;
348                chk.setLint(prevLint);
349                deferredLintHandler.setPos(prevLintPos);
350                this.staticImportFilter = prevStaticImportFilter;
351                this.typeImportFilter = prevTypeImportFilter;
352            }
353        }
354
355        private void checkClassPackageClash(JCPackageDecl tree) {
356            // check that no class exists with same fully qualified name as
357            // toplevel package
358            if (checkClash && tree.pid != null) {
359                Symbol p = env.toplevel.packge;
360                while (p.owner != syms.rootPackage) {
361                    p.owner.complete(); // enter all class members of p
362                    if (syms.classes.get(p.getQualifiedName()) != null) {
363                        log.error(tree.pos,
364                                  "pkg.clashes.with.class.of.same.name",
365                                  p);
366                    }
367                    p = p.owner;
368                }
369            }
370            // process package annotations
371            annotate.annotateLater(tree.annotations, env, env.toplevel.packge, null);
372        }
373
374        private void doImport(JCImport tree) {
375            dependencies.push(AttributionKind.IMPORT, tree);
376            JCFieldAccess imp = (JCFieldAccess)tree.qualid;
377            Name name = TreeInfo.name(imp);
378
379            // Create a local environment pointing to this tree to disable
380            // effects of other imports in Resolve.findGlobalType
381            Env<AttrContext> localEnv = env.dup(tree);
382
383            TypeSymbol p = attr.attribImportQualifier(tree, localEnv).tsym;
384            if (name == names.asterisk) {
385                // Import on demand.
386                chk.checkCanonical(imp.selected);
387                if (tree.staticImport)
388                    importStaticAll(tree, p, env);
389                else
390                    importAll(tree, p, env);
391            } else {
392                // Named type import.
393                if (tree.staticImport) {
394                    importNamedStatic(tree, p, name, localEnv);
395                    chk.checkCanonical(imp.selected);
396                } else {
397                    TypeSymbol c = attribImportType(imp, localEnv).tsym;
398                    chk.checkCanonical(imp);
399                    importNamed(tree.pos(), c, env, tree);
400                }
401            }
402            dependencies.pop();
403        }
404
405        Type attribImportType(JCTree tree, Env<AttrContext> env) {
406            Assert.check(completionEnabled);
407            Lint prevLint = chk.setLint(allowDeprecationOnImport ?
408                    lint : lint.suppress(LintCategory.DEPRECATION));
409            try {
410                // To prevent deep recursion, suppress completion of some
411                // types.
412                completionEnabled = false;
413                return attr.attribType(tree, env);
414            } finally {
415                completionEnabled = true;
416                chk.setLint(prevLint);
417            }
418        }
419
420        /** Import all classes of a class or package on demand.
421         *  @param imp           The import that is being handled.
422         *  @param tsym          The class or package the members of which are imported.
423         *  @param env           The env in which the imported classes will be entered.
424         */
425        private void importAll(JCImport imp,
426                               final TypeSymbol tsym,
427                               Env<AttrContext> env) {
428            env.toplevel.starImportScope.importAll(types, tsym.members(), typeImportFilter, imp, cfHandler);
429        }
430
431        /** Import all static members of a class or package on demand.
432         *  @param imp           The import that is being handled.
433         *  @param tsym          The class or package the members of which are imported.
434         *  @param env           The env in which the imported classes will be entered.
435         */
436        private void importStaticAll(JCImport imp,
437                                     final TypeSymbol tsym,
438                                     Env<AttrContext> env) {
439            final StarImportScope toScope = env.toplevel.starImportScope;
440            final TypeSymbol origin = tsym;
441
442            toScope.importAll(types, origin.members(), staticImportFilter, imp, cfHandler);
443        }
444
445        /** Import statics types of a given name.  Non-types are handled in Attr.
446         *  @param imp           The import that is being handled.
447         *  @param tsym          The class from which the name is imported.
448         *  @param name          The (simple) name being imported.
449         *  @param env           The environment containing the named import
450         *                  scope to add to.
451         */
452        private void importNamedStatic(final JCImport imp,
453                                       final TypeSymbol tsym,
454                                       final Name name,
455                                       final Env<AttrContext> env) {
456            if (tsym.kind != TYP) {
457                log.error(DiagnosticFlag.RECOVERABLE, imp.pos(), "static.imp.only.classes.and.interfaces");
458                return;
459            }
460
461            final NamedImportScope toScope = env.toplevel.namedImportScope;
462            final Scope originMembers = tsym.members();
463
464            imp.importScope = toScope.importByName(types, originMembers, name, staticImportFilter, imp, cfHandler);
465        }
466
467        /** Import given class.
468         *  @param pos           Position to be used for error reporting.
469         *  @param tsym          The class to be imported.
470         *  @param env           The environment containing the named import
471         *                  scope to add to.
472         */
473        private void importNamed(DiagnosticPosition pos, final Symbol tsym, Env<AttrContext> env, JCImport imp) {
474            if (tsym.kind == TYP)
475                imp.importScope = env.toplevel.namedImportScope.importType(tsym.owner.members(), tsym.owner.members(), tsym);
476        }
477
478    }
479
480    /**Defines common utility methods used by the HierarchyPhase and HeaderPhase.
481     */
482    private abstract class AbstractHeaderPhase extends Phase {
483
484        public AbstractHeaderPhase(CompletionCause phaseName, Phase next) {
485            super(phaseName, next);
486        }
487
488        protected Env<AttrContext> baseEnv(JCClassDecl tree, Env<AttrContext> env) {
489            WriteableScope baseScope = WriteableScope.create(tree.sym);
490            //import already entered local classes into base scope
491            for (Symbol sym : env.outer.info.scope.getSymbols(NON_RECURSIVE)) {
492                if (sym.isLocal()) {
493                    baseScope.enter(sym);
494                }
495            }
496            //import current type-parameters into base scope
497            if (tree.typarams != null)
498                for (List<JCTypeParameter> typarams = tree.typarams;
499                     typarams.nonEmpty();
500                     typarams = typarams.tail)
501                    baseScope.enter(typarams.head.type.tsym);
502            Env<AttrContext> outer = env.outer; // the base clause can't see members of this class
503            Env<AttrContext> localEnv = outer.dup(tree, outer.info.dup(baseScope));
504            localEnv.baseClause = true;
505            localEnv.outer = outer;
506            localEnv.info.isSelfCall = false;
507            return localEnv;
508        }
509
510        /** Generate a base clause for an enum type.
511         *  @param pos              The position for trees and diagnostics, if any
512         *  @param c                The class symbol of the enum
513         */
514        protected  JCExpression enumBase(int pos, ClassSymbol c) {
515            JCExpression result = make.at(pos).
516                TypeApply(make.QualIdent(syms.enumSym),
517                          List.<JCExpression>of(make.Type(c.type)));
518            return result;
519        }
520
521        protected Type modelMissingTypes(Type t, final JCExpression tree, final boolean interfaceExpected) {
522            if (!t.hasTag(ERROR))
523                return t;
524
525            return new ErrorType(t.getOriginalType(), t.tsym) {
526                private Type modelType;
527
528                @Override
529                public Type getModelType() {
530                    if (modelType == null)
531                        modelType = new Synthesizer(getOriginalType(), interfaceExpected).visit(tree);
532                    return modelType;
533                }
534            };
535        }
536            // where:
537            private class Synthesizer extends JCTree.Visitor {
538                Type originalType;
539                boolean interfaceExpected;
540                List<ClassSymbol> synthesizedSymbols = List.nil();
541                Type result;
542
543                Synthesizer(Type originalType, boolean interfaceExpected) {
544                    this.originalType = originalType;
545                    this.interfaceExpected = interfaceExpected;
546                }
547
548                Type visit(JCTree tree) {
549                    tree.accept(this);
550                    return result;
551                }
552
553                List<Type> visit(List<? extends JCTree> trees) {
554                    ListBuffer<Type> lb = new ListBuffer<>();
555                    for (JCTree t: trees)
556                        lb.append(visit(t));
557                    return lb.toList();
558                }
559
560                @Override
561                public void visitTree(JCTree tree) {
562                    result = syms.errType;
563                }
564
565                @Override
566                public void visitIdent(JCIdent tree) {
567                    if (!tree.type.hasTag(ERROR)) {
568                        result = tree.type;
569                    } else {
570                        result = synthesizeClass(tree.name, syms.unnamedPackage).type;
571                    }
572                }
573
574                @Override
575                public void visitSelect(JCFieldAccess tree) {
576                    if (!tree.type.hasTag(ERROR)) {
577                        result = tree.type;
578                    } else {
579                        Type selectedType;
580                        boolean prev = interfaceExpected;
581                        try {
582                            interfaceExpected = false;
583                            selectedType = visit(tree.selected);
584                        } finally {
585                            interfaceExpected = prev;
586                        }
587                        ClassSymbol c = synthesizeClass(tree.name, selectedType.tsym);
588                        result = c.type;
589                    }
590                }
591
592                @Override
593                public void visitTypeApply(JCTypeApply tree) {
594                    if (!tree.type.hasTag(ERROR)) {
595                        result = tree.type;
596                    } else {
597                        ClassType clazzType = (ClassType) visit(tree.clazz);
598                        if (synthesizedSymbols.contains(clazzType.tsym))
599                            synthesizeTyparams((ClassSymbol) clazzType.tsym, tree.arguments.size());
600                        final List<Type> actuals = visit(tree.arguments);
601                        result = new ErrorType(tree.type, clazzType.tsym) {
602                            @Override @DefinedBy(Api.LANGUAGE_MODEL)
603                            public List<Type> getTypeArguments() {
604                                return actuals;
605                            }
606                        };
607                    }
608                }
609
610                ClassSymbol synthesizeClass(Name name, Symbol owner) {
611                    int flags = interfaceExpected ? INTERFACE : 0;
612                    ClassSymbol c = new ClassSymbol(flags, name, owner);
613                    c.members_field = new Scope.ErrorScope(c);
614                    c.type = new ErrorType(originalType, c) {
615                        @Override @DefinedBy(Api.LANGUAGE_MODEL)
616                        public List<Type> getTypeArguments() {
617                            return typarams_field;
618                        }
619                    };
620                    synthesizedSymbols = synthesizedSymbols.prepend(c);
621                    return c;
622                }
623
624                void synthesizeTyparams(ClassSymbol sym, int n) {
625                    ClassType ct = (ClassType) sym.type;
626                    Assert.check(ct.typarams_field.isEmpty());
627                    if (n == 1) {
628                        TypeVar v = new TypeVar(names.fromString("T"), sym, syms.botType);
629                        ct.typarams_field = ct.typarams_field.prepend(v);
630                    } else {
631                        for (int i = n; i > 0; i--) {
632                            TypeVar v = new TypeVar(names.fromString("T" + i), sym,
633                                                    syms.botType);
634                            ct.typarams_field = ct.typarams_field.prepend(v);
635                        }
636                    }
637                }
638            }
639
640        protected void attribSuperTypes(Env<AttrContext> env, Env<AttrContext> baseEnv) {
641            JCClassDecl tree = env.enclClass;
642            ClassSymbol sym = tree.sym;
643            ClassType ct = (ClassType)sym.type;
644            // Determine supertype.
645            Type supertype;
646            JCExpression extending;
647
648            if (tree.extending != null) {
649                extending = clearTypeParams(tree.extending);
650                dependencies.push(AttributionKind.EXTENDS, tree.extending);
651                try {
652                    supertype = attr.attribBase(extending, baseEnv,
653                                                true, false, true);
654                } finally {
655                    dependencies.pop();
656                }
657            } else {
658                extending = null;
659                supertype = ((tree.mods.flags & Flags.ENUM) != 0)
660                ? attr.attribBase(enumBase(tree.pos, sym), baseEnv,
661                                  true, false, false)
662                : (sym.fullname == names.java_lang_Object)
663                ? Type.noType
664                : syms.objectType;
665            }
666            ct.supertype_field = modelMissingTypes(supertype, extending, false);
667
668            // Determine interfaces.
669            ListBuffer<Type> interfaces = new ListBuffer<>();
670            ListBuffer<Type> all_interfaces = null; // lazy init
671            List<JCExpression> interfaceTrees = tree.implementing;
672            for (JCExpression iface : interfaceTrees) {
673                iface = clearTypeParams(iface);
674                dependencies.push(AttributionKind.IMPLEMENTS, iface);
675                try {
676                    Type it = attr.attribBase(iface, baseEnv, false, true, true);
677                    if (it.hasTag(CLASS)) {
678                        interfaces.append(it);
679                        if (all_interfaces != null) all_interfaces.append(it);
680                    } else {
681                        if (all_interfaces == null)
682                            all_interfaces = new ListBuffer<Type>().appendList(interfaces);
683                        all_interfaces.append(modelMissingTypes(it, iface, true));
684
685                    }
686                } finally {
687                    dependencies.pop();
688                }
689            }
690
691            if ((sym.flags_field & ANNOTATION) != 0) {
692                ct.interfaces_field = List.of(syms.annotationType);
693                ct.all_interfaces_field = ct.interfaces_field;
694            }  else {
695                ct.interfaces_field = interfaces.toList();
696                ct.all_interfaces_field = (all_interfaces == null)
697                        ? ct.interfaces_field : all_interfaces.toList();
698            }
699        }
700            //where:
701            protected JCExpression clearTypeParams(JCExpression superType) {
702                return superType;
703            }
704    }
705
706    private final class HierarchyPhase extends AbstractHeaderPhase implements Completer {
707
708        public HierarchyPhase() {
709            super(CompletionCause.HIERARCHY_PHASE, new HeaderPhase());
710        }
711
712        @Override
713        protected void doCompleteEnvs(List<Env<AttrContext>> envs) {
714            //The ClassSymbols in the envs list may not be in the dependency order.
715            //To get proper results, for every class or interface C, the supertypes of
716            //C must be processed by the HierarchyPhase phase before C.
717            //To achieve that, the HierarchyPhase is registered as the Completer for
718            //all the classes first, and then all the classes are completed.
719            for (Env<AttrContext> env : envs) {
720                env.enclClass.sym.completer = this;
721            }
722            for (Env<AttrContext> env : envs) {
723                env.enclClass.sym.complete();
724            }
725        }
726
727        @Override
728        protected void runPhase(Env<AttrContext> env) {
729            JCClassDecl tree = env.enclClass;
730            ClassSymbol sym = tree.sym;
731            ClassType ct = (ClassType)sym.type;
732
733            Env<AttrContext> baseEnv = baseEnv(tree, env);
734
735            attribSuperTypes(env, baseEnv);
736
737            if (sym.fullname == names.java_lang_Object) {
738                if (tree.extending != null) {
739                    chk.checkNonCyclic(tree.extending.pos(),
740                                       ct.supertype_field);
741                    ct.supertype_field = Type.noType;
742                }
743                else if (tree.implementing.nonEmpty()) {
744                    chk.checkNonCyclic(tree.implementing.head.pos(),
745                                       ct.interfaces_field.head);
746                    ct.interfaces_field = List.nil();
747                }
748            }
749
750            // Annotations.
751            // In general, we cannot fully process annotations yet,  but we
752            // can attribute the annotation types and then check to see if the
753            // @Deprecated annotation is present.
754            attr.attribAnnotationTypes(tree.mods.annotations, baseEnv);
755            if (hasDeprecatedAnnotation(tree.mods.annotations))
756                sym.flags_field |= DEPRECATED;
757
758            chk.checkNonCyclicDecl(tree);
759        }
760            //where:
761            protected JCExpression clearTypeParams(JCExpression superType) {
762                switch (superType.getTag()) {
763                    case TYPEAPPLY:
764                        return ((JCTypeApply) superType).clazz;
765                }
766
767                return superType;
768            }
769
770            /**
771             * Check if a list of annotations contains a reference to
772             * java.lang.Deprecated.
773             **/
774            private boolean hasDeprecatedAnnotation(List<JCAnnotation> annotations) {
775                for (List<JCAnnotation> al = annotations; !al.isEmpty(); al = al.tail) {
776                    JCAnnotation a = al.head;
777                    if (a.annotationType.type == syms.deprecatedType && a.args.isEmpty())
778                        return true;
779                }
780                return false;
781            }
782
783        @Override
784        public void complete(Symbol sym) throws CompletionFailure {
785            Env<AttrContext> env = typeEnvs.get((ClassSymbol) sym);
786
787            super.doCompleteEnvs(List.of(env));
788        }
789
790    }
791
792    private final class HeaderPhase extends AbstractHeaderPhase {
793
794        public HeaderPhase() {
795            super(CompletionCause.HEADER_PHASE, new MembersPhase());
796        }
797
798        @Override
799        protected void runPhase(Env<AttrContext> env) {
800            JCClassDecl tree = env.enclClass;
801            ClassSymbol sym = tree.sym;
802            ClassType ct = (ClassType)sym.type;
803
804            // create an environment for evaluating the base clauses
805            Env<AttrContext> baseEnv = baseEnv(tree, env);
806
807            if (tree.extending != null)
808                annotate.queueScanTreeAndTypeAnnotate(tree.extending, baseEnv, sym, tree.pos());
809            for (JCExpression impl : tree.implementing)
810                annotate.queueScanTreeAndTypeAnnotate(impl, baseEnv, sym, tree.pos());
811            annotate.flush();
812
813            attribSuperTypes(env, baseEnv);
814
815            Set<Type> interfaceSet = new HashSet<>();
816
817            for (JCExpression iface : tree.implementing) {
818                Type it = iface.type;
819                if (it.hasTag(CLASS))
820                    chk.checkNotRepeated(iface.pos(), types.erasure(it), interfaceSet);
821            }
822
823            annotate.annotateLater(tree.mods.annotations, baseEnv,
824                        sym, tree.pos());
825
826            attr.attribTypeVariables(tree.typarams, baseEnv);
827            for (JCTypeParameter tp : tree.typarams)
828                annotate.queueScanTreeAndTypeAnnotate(tp, baseEnv, sym, tree.pos());
829
830            // check that no package exists with same fully qualified name,
831            // but admit classes in the unnamed package which have the same
832            // name as a top-level package.
833            if (checkClash &&
834                sym.owner.kind == PCK && sym.owner != syms.unnamedPackage &&
835                syms.packageExists(sym.fullname)) {
836                log.error(tree.pos, "clash.with.pkg.of.same.name", Kinds.kindName(sym), sym);
837            }
838            if (sym.owner.kind == PCK && (sym.flags_field & PUBLIC) == 0 &&
839                !env.toplevel.sourcefile.isNameCompatible(sym.name.toString(),JavaFileObject.Kind.SOURCE)) {
840                sym.flags_field |= AUXILIARY;
841            }
842        }
843    }
844
845    /** Enter member fields and methods of a class
846     */
847    private final class MembersPhase extends Phase {
848
849        public MembersPhase() {
850            super(CompletionCause.MEMBERS_PHASE, null);
851        }
852
853        @Override
854        protected void runPhase(Env<AttrContext> env) {
855            JCClassDecl tree = env.enclClass;
856            ClassSymbol sym = tree.sym;
857            ClassType ct = (ClassType)sym.type;
858
859            // Add default constructor if needed.
860            if ((sym.flags() & INTERFACE) == 0 &&
861                !TreeInfo.hasConstructors(tree.defs)) {
862                List<Type> argtypes = List.nil();
863                List<Type> typarams = List.nil();
864                List<Type> thrown = List.nil();
865                long ctorFlags = 0;
866                boolean based = false;
867                boolean addConstructor = true;
868                JCNewClass nc = null;
869                if (sym.name.isEmpty()) {
870                    nc = (JCNewClass)env.next.tree;
871                    if (nc.constructor != null) {
872                        addConstructor = nc.constructor.kind != ERR;
873                        Type superConstrType = types.memberType(sym.type,
874                                                                nc.constructor);
875                        argtypes = superConstrType.getParameterTypes();
876                        typarams = superConstrType.getTypeArguments();
877                        ctorFlags = nc.constructor.flags() & VARARGS;
878                        if (nc.encl != null) {
879                            argtypes = argtypes.prepend(nc.encl.type);
880                            based = true;
881                        }
882                        thrown = superConstrType.getThrownTypes();
883                    }
884                }
885                if (addConstructor) {
886                    MethodSymbol basedConstructor = nc != null ?
887                            (MethodSymbol)nc.constructor : null;
888                    JCTree constrDef = DefaultConstructor(make.at(tree.pos), sym,
889                                                        basedConstructor,
890                                                        typarams, argtypes, thrown,
891                                                        ctorFlags, based);
892                    tree.defs = tree.defs.prepend(constrDef);
893                }
894            }
895
896            // enter symbols for 'this' into current scope.
897            VarSymbol thisSym =
898                new VarSymbol(FINAL | HASINIT, names._this, sym.type, sym);
899            thisSym.pos = Position.FIRSTPOS;
900            env.info.scope.enter(thisSym);
901            // if this is a class, enter symbol for 'super' into current scope.
902            if ((sym.flags_field & INTERFACE) == 0 &&
903                    ct.supertype_field.hasTag(CLASS)) {
904                VarSymbol superSym =
905                    new VarSymbol(FINAL | HASINIT, names._super,
906                                  ct.supertype_field, sym);
907                superSym.pos = Position.FIRSTPOS;
908                env.info.scope.enter(superSym);
909            }
910
911            finishClass(tree, env);
912
913            if (allowTypeAnnos) {
914                typeAnnotations.organizeTypeAnnotationsSignatures(env, (JCClassDecl)env.tree);
915                typeAnnotations.validateTypeAnnotationsSignatures(env, (JCClassDecl)env.tree);
916            }
917        }
918
919        /** Enter members for a class.
920         */
921        void finishClass(JCClassDecl tree, Env<AttrContext> env) {
922            if ((tree.mods.flags & Flags.ENUM) != 0 &&
923                (types.supertype(tree.sym.type).tsym.flags() & Flags.ENUM) == 0) {
924                addEnumMembers(tree, env);
925            }
926            memberEnter.memberEnter(tree.defs, env);
927
928            if (tree.sym.isAnnotationType()) {
929                Assert.check(tree.sym.isCompleted());
930                tree.sym.setAnnotationTypeMetadata(new AnnotationTypeMetadata(tree.sym, annotate.annotationTypeSourceCompleter()));
931            }
932        }
933
934        /** Add the implicit members for an enum type
935         *  to the symbol table.
936         */
937        private void addEnumMembers(JCClassDecl tree, Env<AttrContext> env) {
938            JCExpression valuesType = make.Type(new ArrayType(tree.sym.type, syms.arrayClass));
939
940            // public static T[] values() { return ???; }
941            JCMethodDecl values = make.
942                MethodDef(make.Modifiers(Flags.PUBLIC|Flags.STATIC),
943                          names.values,
944                          valuesType,
945                          List.<JCTypeParameter>nil(),
946                          List.<JCVariableDecl>nil(),
947                          List.<JCExpression>nil(), // thrown
948                          null, //make.Block(0, Tree.emptyList.prepend(make.Return(make.Ident(names._null)))),
949                          null);
950            memberEnter.memberEnter(values, env);
951
952            // public static T valueOf(String name) { return ???; }
953            JCMethodDecl valueOf = make.
954                MethodDef(make.Modifiers(Flags.PUBLIC|Flags.STATIC),
955                          names.valueOf,
956                          make.Type(tree.sym.type),
957                          List.<JCTypeParameter>nil(),
958                          List.of(make.VarDef(make.Modifiers(Flags.PARAMETER |
959                                                             Flags.MANDATED),
960                                                names.fromString("name"),
961                                                make.Type(syms.stringType), null)),
962                          List.<JCExpression>nil(), // thrown
963                          null, //make.Block(0, Tree.emptyList.prepend(make.Return(make.Ident(names._null)))),
964                          null);
965            memberEnter.memberEnter(valueOf, env);
966        }
967
968    }
969
970/* ***************************************************************************
971 * tree building
972 ****************************************************************************/
973
974    /** Generate default constructor for given class. For classes different
975     *  from java.lang.Object, this is:
976     *
977     *    c(argtype_0 x_0, ..., argtype_n x_n) throws thrown {
978     *      super(x_0, ..., x_n)
979     *    }
980     *
981     *  or, if based == true:
982     *
983     *    c(argtype_0 x_0, ..., argtype_n x_n) throws thrown {
984     *      x_0.super(x_1, ..., x_n)
985     *    }
986     *
987     *  @param make     The tree factory.
988     *  @param c        The class owning the default constructor.
989     *  @param argtypes The parameter types of the constructor.
990     *  @param thrown   The thrown exceptions of the constructor.
991     *  @param based    Is first parameter a this$n?
992     */
993    JCTree DefaultConstructor(TreeMaker make,
994                            ClassSymbol c,
995                            MethodSymbol baseInit,
996                            List<Type> typarams,
997                            List<Type> argtypes,
998                            List<Type> thrown,
999                            long flags,
1000                            boolean based) {
1001        JCTree result;
1002        if ((c.flags() & ENUM) != 0 &&
1003            (types.supertype(c.type).tsym == syms.enumSym)) {
1004            // constructors of true enums are private
1005            flags = (flags & ~AccessFlags) | PRIVATE | GENERATEDCONSTR;
1006        } else
1007            flags |= (c.flags() & AccessFlags) | GENERATEDCONSTR;
1008        if (c.name.isEmpty()) {
1009            flags |= ANONCONSTR;
1010        }
1011        Type mType = new MethodType(argtypes, null, thrown, c);
1012        Type initType = typarams.nonEmpty() ?
1013            new ForAll(typarams, mType) :
1014            mType;
1015        MethodSymbol init = new MethodSymbol(flags, names.init,
1016                initType, c);
1017        init.params = createDefaultConstructorParams(make, baseInit, init,
1018                argtypes, based);
1019        List<JCVariableDecl> params = make.Params(argtypes, init);
1020        List<JCStatement> stats = List.nil();
1021        if (c.type != syms.objectType) {
1022            stats = stats.prepend(SuperCall(make, typarams, params, based));
1023        }
1024        result = make.MethodDef(init, make.Block(0, stats));
1025        return result;
1026    }
1027
1028    private List<VarSymbol> createDefaultConstructorParams(
1029            TreeMaker make,
1030            MethodSymbol baseInit,
1031            MethodSymbol init,
1032            List<Type> argtypes,
1033            boolean based) {
1034        List<VarSymbol> initParams = null;
1035        List<Type> argTypesList = argtypes;
1036        if (based) {
1037            /*  In this case argtypes will have an extra type, compared to baseInit,
1038             *  corresponding to the type of the enclosing instance i.e.:
1039             *
1040             *  Inner i = outer.new Inner(1){}
1041             *
1042             *  in the above example argtypes will be (Outer, int) and baseInit
1043             *  will have parameter's types (int). So in this case we have to add
1044             *  first the extra type in argtypes and then get the names of the
1045             *  parameters from baseInit.
1046             */
1047            initParams = List.nil();
1048            VarSymbol param = new VarSymbol(PARAMETER, make.paramName(0), argtypes.head, init);
1049            initParams = initParams.append(param);
1050            argTypesList = argTypesList.tail;
1051        }
1052        if (baseInit != null && baseInit.params != null &&
1053            baseInit.params.nonEmpty() && argTypesList.nonEmpty()) {
1054            initParams = (initParams == null) ? List.<VarSymbol>nil() : initParams;
1055            List<VarSymbol> baseInitParams = baseInit.params;
1056            while (baseInitParams.nonEmpty() && argTypesList.nonEmpty()) {
1057                VarSymbol param = new VarSymbol(baseInitParams.head.flags() | PARAMETER,
1058                        baseInitParams.head.name, argTypesList.head, init);
1059                initParams = initParams.append(param);
1060                baseInitParams = baseInitParams.tail;
1061                argTypesList = argTypesList.tail;
1062            }
1063        }
1064        return initParams;
1065    }
1066
1067    /** Generate call to superclass constructor. This is:
1068     *
1069     *    super(id_0, ..., id_n)
1070     *
1071     * or, if based == true
1072     *
1073     *    id_0.super(id_1,...,id_n)
1074     *
1075     *  where id_0, ..., id_n are the names of the given parameters.
1076     *
1077     *  @param make    The tree factory
1078     *  @param params  The parameters that need to be passed to super
1079     *  @param typarams  The type parameters that need to be passed to super
1080     *  @param based   Is first parameter a this$n?
1081     */
1082    JCExpressionStatement SuperCall(TreeMaker make,
1083                   List<Type> typarams,
1084                   List<JCVariableDecl> params,
1085                   boolean based) {
1086        JCExpression meth;
1087        if (based) {
1088            meth = make.Select(make.Ident(params.head), names._super);
1089            params = params.tail;
1090        } else {
1091            meth = make.Ident(names._super);
1092        }
1093        List<JCExpression> typeargs = typarams.nonEmpty() ? make.Types(typarams) : null;
1094        return make.Exec(make.Apply(typeargs, meth, make.Idents(params)));
1095    }
1096}
1097