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