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