1 /*
   2  * Copyright (c) 2003, 2019, 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 import java.util.stream.Collectors;
  32 
  33 import javax.lang.model.element.ElementKind;
  34 import javax.tools.JavaFileObject;
  35 
  36 import com.sun.tools.javac.code.*;
  37 import com.sun.tools.javac.code.Lint.LintCategory;
  38 import com.sun.tools.javac.code.Scope.ImportFilter;
  39 import com.sun.tools.javac.code.Scope.NamedImportScope;
  40 import com.sun.tools.javac.code.Scope.StarImportScope;
  41 import com.sun.tools.javac.code.Scope.WriteableScope;
  42 import com.sun.tools.javac.code.Source.Feature;
  43 import com.sun.tools.javac.comp.Annotate.AnnotationTypeMetadata;
  44 import com.sun.tools.javac.tree.*;
  45 import com.sun.tools.javac.util.*;
  46 import com.sun.tools.javac.util.DefinedBy.Api;
  47 
  48 import com.sun.tools.javac.code.Symbol.*;
  49 import com.sun.tools.javac.code.Type.*;
  50 import com.sun.tools.javac.resources.CompilerProperties.Errors;
  51 import com.sun.tools.javac.tree.JCTree.*;
  52 
  53 import static com.sun.tools.javac.code.Flags.*;
  54 import static com.sun.tools.javac.code.Flags.ANNOTATION;
  55 import static com.sun.tools.javac.code.Scope.LookupKind.NON_RECURSIVE;
  56 import static com.sun.tools.javac.code.Kinds.Kind.*;
  57 import static com.sun.tools.javac.code.TypeTag.CLASS;
  58 import static com.sun.tools.javac.code.TypeTag.ERROR;
  59 import static com.sun.tools.javac.code.TypeTag.NONE;
  60 
  61 import com.sun.tools.javac.resources.CompilerProperties.Fragments;
  62 
  63 import static com.sun.tools.javac.tree.JCTree.Tag.*;
  64 
  65 import com.sun.tools.javac.util.Dependencies.CompletionCause;
  66 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
  67 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
  68 
  69 /** This is the second phase of Enter, in which classes are completed
  70  *  by resolving their headers and entering their members in the into
  71  *  the class scope. See Enter for an overall overview.
  72  *
  73  *  This class uses internal phases to process the classes. When a phase
  74  *  processes classes, the lower phases are not invoked until all classes
  75  *  pass through the current phase. Note that it is possible that upper phases
  76  *  are run due to recursive completion. The internal phases are:
  77  *  - ImportPhase: shallow pass through imports, adds information about imports
  78  *                 the NamedImportScope and StarImportScope, but avoids queries
  79  *                 about class hierarchy.
  80  *  - HierarchyPhase: resolves the supertypes of the given class. Does not handle
  81  *                    type parameters of the class or type argument of the supertypes.
  82  *  - HeaderPhase: finishes analysis of the header of the given class by resolving
  83  *                 type parameters, attributing supertypes including type arguments
  84  *                 and scheduling full annotation attribution. This phase also adds
  85  *                 a synthetic default constructor if needed and synthetic "this" field.
  86  *  - MembersPhase: resolves headers for fields, methods and constructors in the given class.
  87  *                  Also generates synthetic enum members.
  88  *
  89  *  <p><b>This is NOT part of any supported API.
  90  *  If you write code that depends on this, you do so at your own risk.
  91  *  This code and its internal interfaces are subject to change or
  92  *  deletion without notice.</b>
  93  */
  94 public class TypeEnter implements Completer {
  95     protected static final Context.Key<TypeEnter> typeEnterKey = new Context.Key<>();
  96 
  97     /** A switch to determine whether we check for package/class conflicts
  98      */
  99     final static boolean checkClash = true;
 100 
 101     private final Names names;
 102     private final Enter enter;
 103     private final MemberEnter memberEnter;
 104     private final Log log;
 105     private final Check chk;
 106     private final Attr attr;
 107     private final Symtab syms;
 108     private final TreeMaker make;
 109     private final Todo todo;
 110     private final Annotate annotate;
 111     private final TypeAnnotations typeAnnotations;
 112     private final Types types;
 113     private final JCDiagnostic.Factory diags;
 114     private final DeferredLintHandler deferredLintHandler;
 115     private final Lint lint;
 116     private final TypeEnvs typeEnvs;
 117     private final Dependencies dependencies;
 118 
 119     public static TypeEnter instance(Context context) {
 120         TypeEnter instance = context.get(typeEnterKey);
 121         if (instance == null)
 122             instance = new TypeEnter(context);
 123         return instance;
 124     }
 125 
 126     protected TypeEnter(Context context) {
 127         context.put(typeEnterKey, this);
 128         names = Names.instance(context);
 129         enter = Enter.instance(context);
 130         memberEnter = MemberEnter.instance(context);
 131         log = Log.instance(context);
 132         chk = Check.instance(context);
 133         attr = Attr.instance(context);
 134         syms = Symtab.instance(context);
 135         make = TreeMaker.instance(context);
 136         todo = Todo.instance(context);
 137         annotate = Annotate.instance(context);
 138         typeAnnotations = TypeAnnotations.instance(context);
 139         types = Types.instance(context);
 140         diags = JCDiagnostic.Factory.instance(context);
 141         deferredLintHandler = DeferredLintHandler.instance(context);
 142         lint = Lint.instance(context);
 143         typeEnvs = TypeEnvs.instance(context);
 144         dependencies = Dependencies.instance(context);
 145         Source source = Source.instance(context);
 146         allowTypeAnnos = Feature.TYPE_ANNOTATIONS.allowedInSource(source);
 147         allowDeprecationOnImport = Feature.DEPRECATION_ON_IMPORT.allowedInSource(source);
 148         Options options = Options.instance(context);
 149         dontErrorIfSealedExtended = options.isSet("dontErrorIfSealedExtended");
 150     }
 151 
 152     /** Switch: support type annotations.
 153      */
 154     boolean allowTypeAnnos;
 155 
 156     /**
 157      * Switch: should deprecation warnings be issued on import
 158      */
 159     boolean allowDeprecationOnImport;
 160 
 161     /** A flag to disable completion from time to time during member
 162      *  enter, as we only need to look up types.  This avoids
 163      *  unnecessarily deep recursion.
 164      */
 165     boolean completionEnabled = true;
 166 
 167     /**
 168      * Temporary switch, false by default but if set, allows generating classes that can extend a sealed class
 169      * even if not listed as a permitted subtype. This allows testing the VM runtime. Should be removed before sealed types
 170      * gets integrated
 171      */
 172     boolean dontErrorIfSealedExtended;
 173 
 174     /* Verify Imports:
 175      */
 176     protected void ensureImportsChecked(List<JCCompilationUnit> trees) {
 177         // if there remain any unimported toplevels (these must have
 178         // no classes at all), process their import statements as well.
 179         for (JCCompilationUnit tree : trees) {
 180             if (!tree.starImportScope.isFilled()) {
 181                 Env<AttrContext> topEnv = enter.topLevelEnv(tree);
 182                 finishImports(tree, () -> { completeClass.resolveImports(tree, topEnv); });
 183             }
 184         }
 185     }
 186 
 187 /* ********************************************************************
 188  * Source completer
 189  *********************************************************************/
 190 
 191     /** Complete entering a class.
 192      *  @param sym         The symbol of the class to be completed.
 193      */
 194     @Override
 195     public void complete(Symbol sym) throws CompletionFailure {
 196         // Suppress some (recursive) MemberEnter invocations
 197         if (!completionEnabled) {
 198             // Re-install same completer for next time around and return.
 199             Assert.check((sym.flags() & Flags.COMPOUND) == 0);
 200             sym.completer = this;
 201             return;
 202         }
 203 
 204         try {
 205             annotate.blockAnnotations();
 206             sym.flags_field |= UNATTRIBUTED;
 207 
 208             List<Env<AttrContext>> queue;
 209 
 210             dependencies.push((ClassSymbol) sym, CompletionCause.MEMBER_ENTER);
 211             try {
 212                 queue = completeClass.completeEnvs(List.of(typeEnvs.get((ClassSymbol) sym)));
 213             } finally {
 214                 dependencies.pop();
 215             }
 216 
 217             if (!queue.isEmpty()) {
 218                 Set<JCCompilationUnit> seen = new HashSet<>();
 219 
 220                 for (Env<AttrContext> env : queue) {
 221                     if (env.toplevel.defs.contains(env.enclClass) && seen.add(env.toplevel)) {
 222                         finishImports(env.toplevel, () -> {});
 223                     }
 224                 }
 225             }
 226         } finally {
 227             annotate.unblockAnnotations();
 228         }
 229     }
 230 
 231     void finishImports(JCCompilationUnit toplevel, Runnable resolve) {
 232         JavaFileObject prev = log.useSource(toplevel.sourcefile);
 233         try {
 234             resolve.run();
 235             chk.checkImportsUnique(toplevel);
 236             chk.checkImportsResolvable(toplevel);
 237             chk.checkImportedPackagesObservable(toplevel);
 238             toplevel.namedImportScope.finalizeScope();
 239             toplevel.starImportScope.finalizeScope();
 240         } catch (CompletionFailure cf) {
 241             chk.completionError(toplevel.pos(), cf);
 242         } finally {
 243             log.useSource(prev);
 244         }
 245     }
 246 
 247     abstract class Phase {
 248         private final ListBuffer<Env<AttrContext>> queue = new ListBuffer<>();
 249         private final Phase next;
 250         private final CompletionCause phaseName;
 251 
 252         Phase(CompletionCause phaseName, Phase next) {
 253             this.phaseName = phaseName;
 254             this.next = next;
 255         }
 256 
 257         public final List<Env<AttrContext>> completeEnvs(List<Env<AttrContext>> envs) {
 258             boolean firstToComplete = queue.isEmpty();
 259 
 260             Phase prevTopLevelPhase = topLevelPhase;
 261             boolean success = false;
 262 
 263             try {
 264                 topLevelPhase = this;
 265                 doCompleteEnvs(envs);
 266                 success = true;
 267             } finally {
 268                 topLevelPhase = prevTopLevelPhase;
 269                 if (!success && firstToComplete) {
 270                     //an exception was thrown, e.g. BreakAttr:
 271                     //the queue would become stale, clear it:
 272                     queue.clear();
 273                 }
 274             }
 275 
 276             if (firstToComplete) {
 277                 List<Env<AttrContext>> out = queue.toList();
 278 
 279                 queue.clear();
 280                 return next != null ? next.completeEnvs(out) : out;
 281             } else {
 282                 return List.nil();
 283             }
 284         }
 285 
 286         protected void doCompleteEnvs(List<Env<AttrContext>> envs) {
 287             for (Env<AttrContext> env : envs) {
 288                 JCClassDecl tree = (JCClassDecl)env.tree;
 289 
 290                 queue.add(env);
 291 
 292                 JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
 293                 DiagnosticPosition prevLintPos = deferredLintHandler.setPos(tree.pos());
 294                 try {
 295                     dependencies.push(env.enclClass.sym, phaseName);
 296                     runPhase(env);
 297                 } catch (CompletionFailure ex) {
 298                     chk.completionError(tree.pos(), ex);
 299                 } finally {
 300                     dependencies.pop();
 301                     deferredLintHandler.setPos(prevLintPos);
 302                     log.useSource(prev);
 303                 }
 304             }
 305         }
 306 
 307         protected abstract void runPhase(Env<AttrContext> env);
 308     }
 309 
 310     private final ImportsPhase completeClass = new ImportsPhase();
 311     private Phase topLevelPhase;
 312 
 313     /**Analyze import clauses.
 314      */
 315     private final class ImportsPhase extends Phase {
 316 
 317         public ImportsPhase() {
 318             super(CompletionCause.IMPORTS_PHASE, new HierarchyPhase());
 319         }
 320 
 321         Env<AttrContext> env;
 322         ImportFilter staticImportFilter;
 323         ImportFilter typeImportFilter;
 324         BiConsumer<JCImport, CompletionFailure> cfHandler =
 325                 (imp, cf) -> chk.completionError(imp.pos(), cf);
 326 
 327         @Override
 328         protected void runPhase(Env<AttrContext> env) {
 329             JCClassDecl tree = env.enclClass;
 330             ClassSymbol sym = tree.sym;
 331 
 332             // If sym is a toplevel-class, make sure any import
 333             // clauses in its source file have been seen.
 334             if (sym.owner.kind == PCK) {
 335                 resolveImports(env.toplevel, env.enclosing(TOPLEVEL));
 336                 todo.append(env);
 337             }
 338 
 339             if (sym.owner.kind == TYP)
 340                 sym.owner.complete();
 341         }
 342 
 343         private void resolveImports(JCCompilationUnit tree, Env<AttrContext> env) {
 344             if (tree.starImportScope.isFilled()) {
 345                 // we must have already processed this toplevel
 346                 return;
 347             }
 348 
 349             ImportFilter prevStaticImportFilter = staticImportFilter;
 350             ImportFilter prevTypeImportFilter = typeImportFilter;
 351             DiagnosticPosition prevLintPos = deferredLintHandler.immediate();
 352             Lint prevLint = chk.setLint(lint);
 353             Env<AttrContext> prevEnv = this.env;
 354             try {
 355                 this.env = env;
 356                 final PackageSymbol packge = env.toplevel.packge;
 357                 this.staticImportFilter =
 358                         (origin, sym) -> sym.isStatic() &&
 359                                          chk.importAccessible(sym, packge) &&
 360                                          sym.isMemberOf((TypeSymbol) origin.owner, types);
 361                 this.typeImportFilter =
 362                         (origin, sym) -> sym.kind == TYP &&
 363                                          chk.importAccessible(sym, packge);
 364 
 365                 // Import-on-demand java.lang.
 366                 PackageSymbol javaLang = syms.enterPackage(syms.java_base, names.java_lang);
 367                 if (javaLang.members().isEmpty() && !javaLang.exists())
 368                     throw new FatalError(diags.fragment(Fragments.FatalErrNoJavaLang));
 369                 importAll(make.at(tree.pos()).Import(make.QualIdent(javaLang), false), javaLang, env);
 370 
 371                 JCModuleDecl decl = tree.getModuleDecl();
 372 
 373                 // Process the package def and all import clauses.
 374                 if (tree.getPackage() != null && decl == null)
 375                     checkClassPackageClash(tree.getPackage());
 376 
 377                 for (JCImport imp : tree.getImports()) {
 378                     doImport(imp);
 379                 }
 380 
 381                 if (decl != null) {
 382                     //check @Deprecated:
 383                     markDeprecated(decl.sym, decl.mods.annotations, env);
 384                     // process module annotations
 385                     annotate.annotateLater(decl.mods.annotations, env, env.toplevel.modle, null);
 386                 }
 387             } finally {
 388                 this.env = prevEnv;
 389                 chk.setLint(prevLint);
 390                 deferredLintHandler.setPos(prevLintPos);
 391                 this.staticImportFilter = prevStaticImportFilter;
 392                 this.typeImportFilter = prevTypeImportFilter;
 393             }
 394         }
 395 
 396         private void checkClassPackageClash(JCPackageDecl tree) {
 397             // check that no class exists with same fully qualified name as
 398             // toplevel package
 399             if (checkClash && tree.pid != null) {
 400                 Symbol p = env.toplevel.packge;
 401                 while (p.owner != syms.rootPackage) {
 402                     p.owner.complete(); // enter all class members of p
 403                     //need to lookup the owning module/package:
 404                     PackageSymbol pack = syms.lookupPackage(env.toplevel.modle, p.owner.getQualifiedName());
 405                     if (syms.getClass(pack.modle, p.getQualifiedName()) != null) {
 406                         log.error(tree.pos,
 407                                   Errors.PkgClashesWithClassOfSameName(p));
 408                     }
 409                     p = p.owner;
 410                 }
 411             }
 412             // process package annotations
 413             annotate.annotateLater(tree.annotations, env, env.toplevel.packge, null);
 414         }
 415 
 416         private void doImport(JCImport tree) {
 417             JCFieldAccess imp = (JCFieldAccess)tree.qualid;
 418             Name name = TreeInfo.name(imp);
 419 
 420             // Create a local environment pointing to this tree to disable
 421             // effects of other imports in Resolve.findGlobalType
 422             Env<AttrContext> localEnv = env.dup(tree);
 423 
 424             TypeSymbol p = attr.attribImportQualifier(tree, localEnv).tsym;
 425             if (name == names.asterisk) {
 426                 // Import on demand.
 427                 chk.checkCanonical(imp.selected);
 428                 if (tree.staticImport)
 429                     importStaticAll(tree, p, env);
 430                 else
 431                     importAll(tree, p, env);
 432             } else {
 433                 // Named type import.
 434                 if (tree.staticImport) {
 435                     importNamedStatic(tree, p, name, localEnv);
 436                     chk.checkCanonical(imp.selected);
 437                 } else {
 438                     Type importedType = attribImportType(imp, localEnv);
 439                     Type originalType = importedType.getOriginalType();
 440                     TypeSymbol c = originalType.hasTag(CLASS) ? originalType.tsym : importedType.tsym;
 441                     chk.checkCanonical(imp);
 442                     importNamed(tree.pos(), c, env, tree);
 443                 }
 444             }
 445         }
 446 
 447         Type attribImportType(JCTree tree, Env<AttrContext> env) {
 448             Assert.check(completionEnabled);
 449             Lint prevLint = chk.setLint(allowDeprecationOnImport ?
 450                     lint : lint.suppress(LintCategory.DEPRECATION, LintCategory.REMOVAL));
 451             try {
 452                 // To prevent deep recursion, suppress completion of some
 453                 // types.
 454                 completionEnabled = false;
 455                 return attr.attribType(tree, env);
 456             } finally {
 457                 completionEnabled = true;
 458                 chk.setLint(prevLint);
 459             }
 460         }
 461 
 462         /** Import all classes of a class or package on demand.
 463          *  @param imp           The import that is being handled.
 464          *  @param tsym          The class or package the members of which are imported.
 465          *  @param env           The env in which the imported classes will be entered.
 466          */
 467         private void importAll(JCImport imp,
 468                                final TypeSymbol tsym,
 469                                Env<AttrContext> env) {
 470             env.toplevel.starImportScope.importAll(types, tsym.members(), typeImportFilter, imp, cfHandler);
 471         }
 472 
 473         /** Import all static members of a class or package on demand.
 474          *  @param imp           The import that is being handled.
 475          *  @param tsym          The class or package the members of which are imported.
 476          *  @param env           The env in which the imported classes will be entered.
 477          */
 478         private void importStaticAll(JCImport imp,
 479                                      final TypeSymbol tsym,
 480                                      Env<AttrContext> env) {
 481             final StarImportScope toScope = env.toplevel.starImportScope;
 482             final TypeSymbol origin = tsym;
 483 
 484             toScope.importAll(types, origin.members(), staticImportFilter, imp, cfHandler);
 485         }
 486 
 487         /** Import statics types of a given name.  Non-types are handled in Attr.
 488          *  @param imp           The import that is being handled.
 489          *  @param tsym          The class from which the name is imported.
 490          *  @param name          The (simple) name being imported.
 491          *  @param env           The environment containing the named import
 492          *                  scope to add to.
 493          */
 494         private void importNamedStatic(final JCImport imp,
 495                                        final TypeSymbol tsym,
 496                                        final Name name,
 497                                        final Env<AttrContext> env) {
 498             if (tsym.kind != TYP) {
 499                 log.error(DiagnosticFlag.RECOVERABLE, imp.pos(), Errors.StaticImpOnlyClassesAndInterfaces);
 500                 return;
 501             }
 502 
 503             final NamedImportScope toScope = env.toplevel.namedImportScope;
 504             final Scope originMembers = tsym.members();
 505 
 506             imp.importScope = toScope.importByName(types, originMembers, name, staticImportFilter, imp, cfHandler);
 507         }
 508 
 509         /** Import given class.
 510          *  @param pos           Position to be used for error reporting.
 511          *  @param tsym          The class to be imported.
 512          *  @param env           The environment containing the named import
 513          *                  scope to add to.
 514          */
 515         private void importNamed(DiagnosticPosition pos, final Symbol tsym, Env<AttrContext> env, JCImport imp) {
 516             if (tsym.kind == TYP)
 517                 imp.importScope = env.toplevel.namedImportScope.importType(tsym.owner.members(), tsym.owner.members(), tsym);
 518         }
 519 
 520     }
 521 
 522     /**Defines common utility methods used by the HierarchyPhase and HeaderPhase.
 523      */
 524     private abstract class AbstractHeaderPhase extends Phase {
 525 
 526         public AbstractHeaderPhase(CompletionCause phaseName, Phase next) {
 527             super(phaseName, next);
 528         }
 529 
 530         protected Env<AttrContext> baseEnv(JCClassDecl tree, Env<AttrContext> env) {
 531             WriteableScope baseScope = WriteableScope.create(tree.sym);
 532             //import already entered local classes into base scope
 533             for (Symbol sym : env.outer.info.scope.getSymbols(NON_RECURSIVE)) {
 534                 if (sym.isLocal()) {
 535                     baseScope.enter(sym);
 536                 }
 537             }
 538             //import current type-parameters into base scope
 539             if (tree.typarams != null)
 540                 for (List<JCTypeParameter> typarams = tree.typarams;
 541                      typarams.nonEmpty();
 542                      typarams = typarams.tail)
 543                     baseScope.enter(typarams.head.type.tsym);
 544             Env<AttrContext> outer = env.outer; // the base clause can't see members of this class
 545             Env<AttrContext> localEnv = outer.dup(tree, outer.info.dup(baseScope));
 546             localEnv.baseClause = true;
 547             localEnv.outer = outer;
 548             localEnv.info.isSelfCall = false;
 549             return localEnv;
 550         }
 551 
 552         /** Generate a base clause for an enum type.
 553          *  @param pos              The position for trees and diagnostics, if any
 554          *  @param c                The class symbol of the enum
 555          */
 556         protected  JCExpression enumBase(int pos, ClassSymbol c) {
 557             JCExpression result = make.at(pos).
 558                 TypeApply(make.QualIdent(syms.enumSym),
 559                           List.of(make.Type(c.type)));
 560             return result;
 561         }
 562 
 563         protected Type modelMissingTypes(Env<AttrContext> env, Type t, final JCExpression tree, final boolean interfaceExpected) {
 564             if (!t.hasTag(ERROR))
 565                 return t;
 566 
 567             return new ErrorType(t.getOriginalType(), t.tsym) {
 568                 private Type modelType;
 569 
 570                 @Override
 571                 public Type getModelType() {
 572                     if (modelType == null)
 573                         modelType = new Synthesizer(env.toplevel.modle, getOriginalType(), interfaceExpected).visit(tree);
 574                     return modelType;
 575                 }
 576             };
 577         }
 578             // where:
 579             private class Synthesizer extends JCTree.Visitor {
 580                 ModuleSymbol msym;
 581                 Type originalType;
 582                 boolean interfaceExpected;
 583                 List<ClassSymbol> synthesizedSymbols = List.nil();
 584                 Type result;
 585 
 586                 Synthesizer(ModuleSymbol msym, Type originalType, boolean interfaceExpected) {
 587                     this.msym = msym;
 588                     this.originalType = originalType;
 589                     this.interfaceExpected = interfaceExpected;
 590                 }
 591 
 592                 Type visit(JCTree tree) {
 593                     tree.accept(this);
 594                     return result;
 595                 }
 596 
 597                 List<Type> visit(List<? extends JCTree> trees) {
 598                     ListBuffer<Type> lb = new ListBuffer<>();
 599                     for (JCTree t: trees)
 600                         lb.append(visit(t));
 601                     return lb.toList();
 602                 }
 603 
 604                 @Override
 605                 public void visitTree(JCTree tree) {
 606                     result = syms.errType;
 607                 }
 608 
 609                 @Override
 610                 public void visitIdent(JCIdent tree) {
 611                     if (!tree.type.hasTag(ERROR)) {
 612                         result = tree.type;
 613                     } else {
 614                         result = synthesizeClass(tree.name, msym.unnamedPackage).type;
 615                     }
 616                 }
 617 
 618                 @Override
 619                 public void visitSelect(JCFieldAccess tree) {
 620                     if (!tree.type.hasTag(ERROR)) {
 621                         result = tree.type;
 622                     } else {
 623                         Type selectedType;
 624                         boolean prev = interfaceExpected;
 625                         try {
 626                             interfaceExpected = false;
 627                             selectedType = visit(tree.selected);
 628                         } finally {
 629                             interfaceExpected = prev;
 630                         }
 631                         ClassSymbol c = synthesizeClass(tree.name, selectedType.tsym);
 632                         result = c.type;
 633                     }
 634                 }
 635 
 636                 @Override
 637                 public void visitTypeApply(JCTypeApply tree) {
 638                     if (!tree.type.hasTag(ERROR)) {
 639                         result = tree.type;
 640                     } else {
 641                         ClassType clazzType = (ClassType) visit(tree.clazz);
 642                         if (synthesizedSymbols.contains(clazzType.tsym))
 643                             synthesizeTyparams((ClassSymbol) clazzType.tsym, tree.arguments.size());
 644                         final List<Type> actuals = visit(tree.arguments);
 645                         result = new ErrorType(tree.type, clazzType.tsym) {
 646                             @Override @DefinedBy(Api.LANGUAGE_MODEL)
 647                             public List<Type> getTypeArguments() {
 648                                 return actuals;
 649                             }
 650                         };
 651                     }
 652                 }
 653 
 654                 ClassSymbol synthesizeClass(Name name, Symbol owner) {
 655                     int flags = interfaceExpected ? INTERFACE : 0;
 656                     ClassSymbol c = new ClassSymbol(flags, name, owner);
 657                     c.members_field = new Scope.ErrorScope(c);
 658                     c.type = new ErrorType(originalType, c) {
 659                         @Override @DefinedBy(Api.LANGUAGE_MODEL)
 660                         public List<Type> getTypeArguments() {
 661                             return typarams_field;
 662                         }
 663                     };
 664                     synthesizedSymbols = synthesizedSymbols.prepend(c);
 665                     return c;
 666                 }
 667 
 668                 void synthesizeTyparams(ClassSymbol sym, int n) {
 669                     ClassType ct = (ClassType) sym.type;
 670                     Assert.check(ct.typarams_field.isEmpty());
 671                     if (n == 1) {
 672                         TypeVar v = new TypeVar(names.fromString("T"), sym, syms.botType);
 673                         ct.typarams_field = ct.typarams_field.prepend(v);
 674                     } else {
 675                         for (int i = n; i > 0; i--) {
 676                             TypeVar v = new TypeVar(names.fromString("T" + i), sym,
 677                                                     syms.botType);
 678                             ct.typarams_field = ct.typarams_field.prepend(v);
 679                         }
 680                     }
 681                 }
 682             }
 683 
 684         protected void attribSuperTypes(Env<AttrContext> env, Env<AttrContext> baseEnv) {
 685             JCClassDecl tree = env.enclClass;
 686             ClassSymbol sym = tree.sym;
 687             ClassType ct = (ClassType)sym.type;
 688             // Determine supertype.
 689             Type supertype;
 690             JCExpression extending;
 691 
 692             if (tree.extending != null) {
 693                 extending = clearTypeParams(tree.extending);
 694                 supertype = attr.attribBase(extending, sym, baseEnv, true, false, true);
 695             } else {
 696                 extending = null;
 697                 supertype = ((tree.mods.flags & Flags.ENUM) != 0)
 698                 ? attr.attribBase(enumBase(tree.pos, sym), sym, baseEnv,
 699                                   true, false, false)
 700                 : (sym.fullname == names.java_lang_Object)
 701                 ? Type.noType
 702                 : syms.objectType;
 703             }
 704             ct.supertype_field = modelMissingTypes(baseEnv, supertype, extending, false);
 705 
 706             // Determine interfaces.
 707             ListBuffer<Type> interfaces = new ListBuffer<>();
 708             ListBuffer<Type> all_interfaces = null; // lazy init
 709             List<JCExpression> interfaceTrees = tree.implementing;
 710             for (JCExpression iface : interfaceTrees) {
 711                 iface = clearTypeParams(iface);
 712                 Type it = attr.attribBase(iface, sym, baseEnv, false, true, true);
 713                 if (it.hasTag(CLASS)) {
 714                     interfaces.append(it);
 715                     if (all_interfaces != null) all_interfaces.append(it);
 716                 } else {
 717                     if (all_interfaces == null)
 718                         all_interfaces = new ListBuffer<Type>().appendList(interfaces);
 719                     all_interfaces.append(modelMissingTypes(baseEnv, it, iface, true));
 720                 }
 721             }
 722 
 723             // Determine permits.
 724             ListBuffer<Type> permittedSubtypes = new ListBuffer<>();
 725             List<JCExpression> permittedTrees = tree.permitting;
 726             for (JCExpression permitted : permittedTrees) {
 727                 permitted = clearTypeParams(permitted);
 728                 Type pt = attr.attribBase(permitted, sym, baseEnv, false, false, false);
 729                 permittedSubtypes.append(pt);
 730             }
 731 
 732             if ((sym.flags_field & ANNOTATION) != 0) {
 733                 ct.interfaces_field = List.of(syms.annotationType);
 734                 ct.all_interfaces_field = ct.interfaces_field;
 735             }  else {
 736                 ct.interfaces_field = interfaces.toList();
 737                 ct.all_interfaces_field = (all_interfaces == null)
 738                         ? ct.interfaces_field : all_interfaces.toList();
 739             }
 740 
 741             ct.permitted = permittedSubtypes.toList();
 742             ct.isPermittedExplicit = !permittedSubtypes.isEmpty();
 743         }
 744             //where:
 745             protected JCExpression clearTypeParams(JCExpression superType) {
 746                 return superType;
 747             }
 748     }
 749 
 750     private final class HierarchyPhase extends AbstractHeaderPhase implements Completer {
 751 
 752         public HierarchyPhase() {
 753             super(CompletionCause.HIERARCHY_PHASE, new HeaderPhase());
 754         }
 755 
 756         @Override
 757         protected void doCompleteEnvs(List<Env<AttrContext>> envs) {
 758             //The ClassSymbols in the envs list may not be in the dependency order.
 759             //To get proper results, for every class or interface C, the supertypes of
 760             //C must be processed by the HierarchyPhase phase before C.
 761             //To achieve that, the HierarchyPhase is registered as the Completer for
 762             //all the classes first, and then all the classes are completed.
 763             for (Env<AttrContext> env : envs) {
 764                 env.enclClass.sym.completer = this;
 765             }
 766             for (Env<AttrContext> env : envs) {
 767                 env.enclClass.sym.complete();
 768             }
 769         }
 770 
 771         @Override
 772         protected void runPhase(Env<AttrContext> env) {
 773             JCClassDecl tree = env.enclClass;
 774             ClassSymbol sym = tree.sym;
 775             ClassType ct = (ClassType)sym.type;
 776 
 777             Env<AttrContext> baseEnv = baseEnv(tree, env);
 778 
 779             attribSuperTypes(env, baseEnv);
 780 
 781             if (sym.fullname == names.java_lang_Object) {
 782                 if (tree.extending != null) {
 783                     chk.checkNonCyclic(tree.extending.pos(),
 784                                        ct.supertype_field);
 785                     ct.supertype_field = Type.noType;
 786                 }
 787                 else if (tree.implementing.nonEmpty()) {
 788                     chk.checkNonCyclic(tree.implementing.head.pos(),
 789                                        ct.interfaces_field.head);
 790                     ct.interfaces_field = List.nil();
 791                 }
 792             }
 793 
 794             markDeprecated(sym, tree.mods.annotations, baseEnv);
 795 
 796             chk.checkNonCyclicDecl(tree);
 797         }
 798             //where:
 799             @Override
 800             protected JCExpression clearTypeParams(JCExpression superType) {
 801                 switch (superType.getTag()) {
 802                     case TYPEAPPLY:
 803                         return ((JCTypeApply) superType).clazz;
 804                 }
 805 
 806                 return superType;
 807             }
 808 
 809         @Override
 810         public void complete(Symbol sym) throws CompletionFailure {
 811             Assert.check((topLevelPhase instanceof ImportsPhase) ||
 812                          (topLevelPhase == this));
 813 
 814             if (topLevelPhase != this) {
 815                 //only do the processing based on dependencies in the HierarchyPhase:
 816                 sym.completer = this;
 817                 return ;
 818             }
 819 
 820             Env<AttrContext> env = typeEnvs.get((ClassSymbol) sym);
 821 
 822             super.doCompleteEnvs(List.of(env));
 823         }
 824 
 825     }
 826 
 827     private final class HeaderPhase extends AbstractHeaderPhase {
 828 
 829         public HeaderPhase() {
 830             super(CompletionCause.HEADER_PHASE, new RecordPhase());
 831         }
 832 
 833         @Override
 834         protected void runPhase(Env<AttrContext> env) {
 835             JCClassDecl tree = env.enclClass;
 836             ClassSymbol sym = tree.sym;
 837             ClassType ct = (ClassType)sym.type;
 838 
 839             // create an environment for evaluating the base clauses
 840             Env<AttrContext> baseEnv = baseEnv(tree, env);
 841 
 842             if (tree.extending != null)
 843                 annotate.queueScanTreeAndTypeAnnotate(tree.extending, baseEnv, sym, tree.pos());
 844             for (JCExpression impl : tree.implementing)
 845                 annotate.queueScanTreeAndTypeAnnotate(impl, baseEnv, sym, tree.pos());
 846             annotate.flush();
 847 
 848             attribSuperTypes(env, baseEnv);
 849 
 850             Set<Type> interfaceSet = new HashSet<>();
 851 
 852             for (JCExpression iface : tree.implementing) {
 853                 Type it = iface.type;
 854                 if (it.hasTag(CLASS))
 855                     chk.checkNotRepeated(iface.pos(), types.erasure(it), interfaceSet);
 856             }
 857 
 858             annotate.annotateLater(tree.mods.annotations, baseEnv,
 859                         sym, tree.pos());
 860             attr.attribTypeVariables(tree.typarams, baseEnv, false);
 861 
 862             for (JCTypeParameter tp : tree.typarams)
 863                 annotate.queueScanTreeAndTypeAnnotate(tp, baseEnv, sym, tree.pos());
 864 
 865             // check that no package exists with same fully qualified name,
 866             // but admit classes in the unnamed package which have the same
 867             // name as a top-level package.
 868             if (checkClash &&
 869                 sym.owner.kind == PCK && sym.owner != env.toplevel.modle.unnamedPackage &&
 870                 syms.packageExists(env.toplevel.modle, sym.fullname)) {
 871                 log.error(tree.pos, Errors.ClashWithPkgOfSameName(Kinds.kindName(sym),sym));
 872             }
 873             if (sym.owner.kind == PCK && (sym.flags_field & PUBLIC) == 0 &&
 874                 !env.toplevel.sourcefile.isNameCompatible(sym.name.toString(),JavaFileObject.Kind.SOURCE)) {
 875                 sym.flags_field |= AUXILIARY;
 876             }
 877         }
 878     }
 879 
 880     private abstract class AbstractMembersPhase extends Phase {
 881 
 882         public AbstractMembersPhase(CompletionCause completionCause, Phase next) {
 883             super(completionCause, next);
 884         }
 885 
 886         private boolean completing;
 887         private List<Env<AttrContext>> todo = List.nil();
 888 
 889         @Override
 890         protected void doCompleteEnvs(List<Env<AttrContext>> envs) {
 891             todo = todo.prependList(envs);
 892             if (completing) {
 893                 return ; //the top-level invocation will handle all envs
 894             }
 895             boolean prevCompleting = completing;
 896             completing = true;
 897             try {
 898                 while (todo.nonEmpty()) {
 899                     Env<AttrContext> head = todo.head;
 900                     todo = todo.tail;
 901                     super.doCompleteEnvs(List.of(head));
 902                 }
 903             } finally {
 904                 completing = prevCompleting;
 905             }
 906         }
 907     }
 908 
 909     private final class RecordPhase extends AbstractMembersPhase {
 910 
 911         public RecordPhase() {
 912             super(CompletionCause.RECORD_PHASE, new MembersPhase());
 913         }
 914 
 915         @Override
 916         protected void runPhase(Env<AttrContext> env) {
 917             JCClassDecl tree = env.enclClass;
 918             ClassSymbol sym = tree.sym;
 919             if ((sym.flags_field & RECORD) != 0) {
 920                 memberEnter.memberEnter(TreeInfo.recordFields(tree), env);
 921             }
 922         }
 923     }
 924 
 925     /** Enter member fields and methods of a class
 926      */
 927     private final class MembersPhase extends AbstractMembersPhase {
 928 
 929         public MembersPhase() {
 930             super(CompletionCause.MEMBERS_PHASE, null);
 931         }
 932 
 933         @Override
 934         protected void runPhase(Env<AttrContext> env) {
 935             JCClassDecl tree = env.enclClass;
 936             ClassSymbol sym = tree.sym;
 937             ClassType ct = (ClassType)sym.type;
 938             boolean defaultConstructorGenerated = false;
 939 
 940             // Add default constructor if needed.
 941             if ((sym.flags() & INTERFACE) == 0 &&
 942                 !TreeInfo.hasConstructors(tree.defs)) {
 943                 DefaultConstructorHelper helper = new BasicConstructorHelper(sym);
 944                 if (sym.name.isEmpty()) {
 945                     JCNewClass nc = (JCNewClass)env.next.tree;
 946                     if (nc.constructor != null) {
 947                         if (nc.constructor.kind != ERR) {
 948                             helper = new AnonClassConstructorHelper(sym, (MethodSymbol)nc.constructor, nc.encl);
 949                         } else {
 950                             helper = null;
 951                         }
 952                     }
 953                 } else if ((sym.flags() & RECORD) != 0) {
 954                     helper = new RecordConstructorHelper(sym, TreeInfo.recordFields(tree));
 955                 }
 956                 if (helper != null) {
 957                     JCTree constrDef = defaultConstructor(make.at(tree.pos), helper);
 958                     tree.defs = tree.defs.prepend(constrDef);
 959                     defaultConstructorGenerated = true;
 960                 }
 961             } else {
 962                 if ((sym.flags() & RECORD) != 0) {
 963                     // there are constructors but they could be incomplete
 964                     for (JCTree def : tree.defs) {
 965                         if (TreeInfo.isConstructor(def)) {
 966                             Name constructorInvocationName =
 967                                     TreeInfo.getConstructorInvocationName(((JCMethodDecl)def).body.stats, names, true);
 968                             if (constructorInvocationName == names.empty ||
 969                                     constructorInvocationName == names._super) {
 970                                 RecordConstructorHelper helper = new RecordConstructorHelper(sym, TreeInfo.recordFields(tree));
 971                                 JCMethodDecl methDecl = (JCMethodDecl)def;
 972                                 if (constructorInvocationName == names.empty) {
 973                                     JCStatement supCall = make.at(methDecl.body.pos).Exec(make.Apply(List.nil(),
 974                                             make.Ident(names._super), List.nil()));
 975                                     methDecl.body.stats = methDecl.body.stats.prepend(supCall);
 976                                 }
 977                                 ListBuffer<JCStatement> initializations = new ListBuffer<>();
 978                                 List<Name> inits = helper.inits();
 979                                 InitializationFinder initFinder = new InitializationFinder(inits);
 980                                 initFinder.scan(methDecl.body.stats);
 981                                 List<Name> found = initFinder.found.toList();
 982                                 inits = inits.diff(found);
 983                                 if (!inits.isEmpty()) {
 984                                     for (Name initName : inits) {
 985                                         initializations.add(make.Exec(make.Assign(make.Select(make.Ident(names._this),
 986                                                 initName), make.Ident(initName))));
 987                                     }
 988                                     methDecl.body.stats = methDecl.body.stats.appendList(initializations.toList());
 989                                 }
 990                             }
 991                         }
 992                     }
 993                 }
 994             }
 995             // enter symbols for 'this' into current scope.
 996             VarSymbol thisSym =
 997                 new VarSymbol(FINAL | HASINIT, names._this, sym.type, sym);
 998             thisSym.pos = Position.FIRSTPOS;
 999             env.info.scope.enter(thisSym);
1000             // if this is a class, enter symbol for 'super' into current scope.
1001             if ((sym.flags_field & INTERFACE) == 0 &&
1002                     ct.supertype_field.hasTag(CLASS)) {
1003                 VarSymbol superSym =
1004                     new VarSymbol(FINAL | HASINIT, names._super,
1005                                   ct.supertype_field, sym);
1006                 superSym.pos = Position.FIRSTPOS;
1007                 env.info.scope.enter(superSym);
1008             }
1009 
1010             if (!tree.typarams.isEmpty()) {
1011                 for (JCTypeParameter tvar : tree.typarams) {
1012                     chk.checkNonCyclic(tvar, (TypeVar)tvar.type);
1013                 }
1014             }
1015 
1016             finishClass(tree, env, defaultConstructorGenerated);
1017 
1018             if (allowTypeAnnos) {
1019                 typeAnnotations.organizeTypeAnnotationsSignatures(env, (JCClassDecl)env.tree);
1020                 typeAnnotations.validateTypeAnnotationsSignatures(env, (JCClassDecl)env.tree);
1021             }
1022         }
1023 
1024         class InitializationFinder extends TreeScanner {
1025             List<Name> fieldNames;
1026             ListBuffer<Name> found = new ListBuffer<>();
1027 
1028             public InitializationFinder(List<Name> fieldNames) {
1029                 this.fieldNames = fieldNames;
1030             }
1031 
1032             @Override
1033             public void visitAssign(JCAssign tree) {
1034                 super.visitAssign(tree);
1035                 if (tree.lhs.hasTag(SELECT)) {
1036                     JCFieldAccess select = (JCFieldAccess)tree.lhs;
1037                     if ((select.selected.hasTag(IDENT)) &&
1038                             ((JCIdent)select.selected).name == names._this) {
1039                         if (fieldNames.contains(select.name)) {
1040                             found.add(select.name);
1041                         }
1042                     }
1043                 }
1044             }
1045         }
1046 
1047         /** Enter members for a class.
1048          */
1049         void finishClass(JCClassDecl tree, Env<AttrContext> env, boolean defaultConstructorGenerated) {
1050             if ((tree.mods.flags & Flags.ENUM) != 0 &&
1051                 !tree.sym.type.hasTag(ERROR) &&
1052                 (types.supertype(tree.sym.type).tsym.flags() & Flags.ENUM) == 0) {
1053                 addEnumMembers(tree, env);
1054             }
1055             boolean isRecord = (tree.sym.flags_field & RECORD) != 0;
1056             List<JCTree> defsToEnter = isRecord ?
1057                     tree.defs.diff(List.convert(JCTree.class, TreeInfo.recordFields(tree))) : tree.defs;
1058             memberEnter.memberEnter(defsToEnter, env);
1059             List<JCTree> defsBeforeAddingNewMembers = tree.defs;
1060             if (isRecord) {
1061                 addRecordMembersIfNeeded(tree, env, defaultConstructorGenerated);
1062                 addAccessorsIfNeeded(tree, env);
1063             }
1064             // now we need to enter any additional mandated member that could have been added in the previous step
1065             memberEnter.memberEnter(tree.defs.diff(List.convert(JCTree.class, defsBeforeAddingNewMembers)), env);
1066 
1067             if (tree.sym.isAnnotationType()) {
1068                 Assert.check(tree.sym.isCompleted());
1069                 tree.sym.setAnnotationTypeMetadata(new AnnotationTypeMetadata(tree.sym, annotate.annotationTypeSourceCompleter()));
1070             }
1071 
1072             Type st = types.supertype(tree.sym.type);
1073             boolean anyParentIsSealed = false;
1074             ListBuffer<Pair<ClassType, JCExpression>> potentiallySealedParents = new ListBuffer<>();
1075             if (st != Type.noType && (st.tsym.isSealed())) {
1076                 potentiallySealedParents.add(new Pair<>((ClassType)st, tree.extending));
1077                 anyParentIsSealed = true;
1078             }
1079 
1080             if (tree.implementing != null) {
1081                 for (JCExpression expr : tree.implementing) {
1082                     if (expr.type.tsym.isSealed()) {
1083                         potentiallySealedParents.add(new Pair<>((ClassType)expr.type, expr));
1084                         anyParentIsSealed = true;
1085                     }
1086                 }
1087             }
1088 
1089             for (Pair<ClassType, JCExpression> sealedParentPair: potentiallySealedParents) {
1090                 if (!sealedParentPair.fst.permitted.map(t -> t.tsym).contains(tree.sym.type.tsym)) {
1091                     boolean areInSameCompilationUnit = TreeInfo.declarationFor(sealedParentPair.fst.tsym, env.toplevel) != null &&
1092                             TreeInfo.declarationFor(tree.sym.outermostClass(), env.toplevel) != null;
1093                     boolean isSealed = sealedParentPair.fst.tsym.isSealed();
1094                     if (areInSameCompilationUnit) {
1095                         if (sealedParentPair.fst.tsym.isSealed() && !((ClassType)sealedParentPair.fst.tsym.type).isPermittedExplicit) {
1096                             if (tree.sym.isAnonymous()) {
1097                                 log.error(sealedParentPair.snd, Errors.CantInheritFromSealed(sealedParentPair.fst.tsym));
1098                             } else {
1099                                 sealedParentPair.fst.permitted = sealedParentPair.fst.permitted.prepend(tree.sym.type);
1100                             }
1101                         } else if (!dontErrorIfSealedExtended) {
1102                             log.error(sealedParentPair.snd, Errors.CantInheritFromSealed(sealedParentPair.fst.tsym));
1103                         }
1104                     } else if (!dontErrorIfSealedExtended) {
1105                         log.error(sealedParentPair.snd, Errors.CantInheritFromSealed(sealedParentPair.fst.tsym));
1106                     }
1107                 }
1108             }
1109 
1110             if (anyParentIsSealed && ((tree.sym.flags_field & Flags.NON_SEALED) == 0) ) {
1111                 // once we have the non-final keyword this will change
1112                 tree.sym.flags_field |= (tree.sym.flags_field & ABSTRACT) != 0 ? SEALED : FINAL;
1113             }
1114 
1115             if (!anyParentIsSealed && ((tree.sym.flags_field & Flags.NON_SEALED) != 0) ) {
1116                 log.error(tree, Errors.NonSealedWithNoSealedSupertype);
1117             }
1118         }
1119 
1120         /** Add the accessors for fields to the symbol table.
1121          */
1122         private void addAccessorsIfNeeded(JCClassDecl tree, Env<AttrContext> env) {
1123             tree.defs.stream()
1124                     .filter(t -> t.hasTag(VARDEF))
1125                     .map(t -> (JCVariableDecl)t)
1126                     .filter(vd -> vd.accessors != null && vd.accessors.nonEmpty())
1127                     .forEach(vd -> addAccessors(vd, env));
1128         }
1129 
1130         private void addAccessors(JCVariableDecl tree, Env<AttrContext> env) {
1131             for (Pair<Accessors.Kind, Name> accessor : tree.accessors) {
1132                 Type accessorType = accessor.fst.accessorType(syms, tree.sym.type);
1133                 MethodSymbol implSym = lookupMethod(env.enclClass.sym, accessor.snd, accessorType.getParameterTypes());
1134                 if (implSym == null || (implSym.flags_field & MANDATED) != 0) {
1135                     JCMethodDecl getter = make.at(tree.pos).MethodDef(make.Modifiers(Flags.PUBLIC | Flags.MANDATED, tree.mods.annotations),
1136                               accessor.snd,
1137                               make.Type(accessorType.getReturnType()),
1138                               List.nil(),
1139                               accessorType.getParameterTypes().stream()
1140                                       .map(ptype -> make.Param(tree.name, tree.sym.type, env.enclClass.sym))
1141                                       .collect(List.collector()),
1142                               List.nil(), // thrown
1143                               null,
1144                               null);
1145                     memberEnter.memberEnter(getter, env);
1146                     tree.sym.accessors = tree.sym.accessors.prepend(new Pair<>(accessor.fst, getter.sym));
1147                 } else if (implSym != null) {
1148                     if ((implSym.flags() & Flags.PUBLIC) == 0) {
1149                         log.error(TreeInfo.declarationFor(implSym, env.enclClass), Errors.MethodMustBePublic(implSym.name));
1150                     }
1151                     if (!types.isSameType(implSym.type.getReturnType(), tree.sym.type)) {
1152                         log.error(TreeInfo.declarationFor(implSym, env.enclClass), Errors.AccessorReturnTypeDoesntMatch(tree.sym.type, implSym.type.getReturnType()));
1153                     }
1154                 }
1155             }
1156         }
1157 
1158         /** Add the implicit members for an enum type
1159          *  to the symbol table.
1160          */
1161         private void addEnumMembers(JCClassDecl tree, Env<AttrContext> env) {
1162             JCExpression valuesType = make.Type(new ArrayType(tree.sym.type, syms.arrayClass));
1163 
1164             // public static T[] values() { return ???; }
1165             JCMethodDecl values = make.
1166                 MethodDef(make.Modifiers(Flags.PUBLIC|Flags.STATIC),
1167                           names.values,
1168                           valuesType,
1169                           List.nil(),
1170                           List.nil(),
1171                           List.nil(), // thrown
1172                           null, //make.Block(0, Tree.emptyList.prepend(make.Return(make.Ident(names._null)))),
1173                           null);
1174             memberEnter.memberEnter(values, env);
1175 
1176             // public static T valueOf(String name) { return ???; }
1177             JCMethodDecl valueOf = make.
1178                 MethodDef(make.Modifiers(Flags.PUBLIC|Flags.STATIC),
1179                           names.valueOf,
1180                           make.Type(tree.sym.type),
1181                           List.nil(),
1182                           List.of(make.VarDef(make.Modifiers(Flags.PARAMETER |
1183                                                              Flags.MANDATED),
1184                                                 names.fromString("name"),
1185                                                 make.Type(syms.stringType), null)),
1186                           List.nil(), // thrown
1187                           null, //make.Block(0, Tree.emptyList.prepend(make.Return(make.Ident(names._null)))),
1188                           null);
1189             memberEnter.memberEnter(valueOf, env);
1190         }
1191 
1192         /** Add the implicit members for a record
1193          *  to the symbol table.
1194          */
1195         private void addRecordMembersIfNeeded(JCClassDecl tree, Env<AttrContext> env, boolean defaultConstructorGenerated) {
1196             if (!defaultConstructorGenerated) {
1197                 // let's check if there is a constructor with exactly the same arguments as the record components
1198                 List<Type> recordComponentTypes = TreeInfo.recordFields(tree).map(vd -> vd.sym.type);
1199                 List<Type> erasedTypes = types.erasure(recordComponentTypes);
1200                 JCMethodDecl canonicalDecl = null;
1201                 for (JCTree def : tree.defs) {
1202                     if (TreeInfo.isConstructor(def)) {
1203                         JCMethodDecl mdecl = (JCMethodDecl)def;
1204                         if (types.isSameTypes(mdecl.sym.type.getParameterTypes(), erasedTypes)) {
1205                             canonicalDecl = mdecl;
1206                             break;
1207                         }
1208                     }
1209                 }
1210                 if (canonicalDecl != null && !types.isSameTypes(erasedTypes, recordComponentTypes)) {
1211                     // error we found a constructor with the same erasure as the canonical constructor
1212                     log.error(canonicalDecl, Errors.ConstructorWithSameErasureAsCanonical);
1213                 }
1214                 MethodSymbol canonicalInit = canonicalDecl == null ?
1215                         null :
1216                         canonicalDecl.sym;
1217                 if (canonicalInit == null) {
1218                     RecordConstructorHelper helper = new RecordConstructorHelper(tree.sym, TreeInfo.recordFields(tree));
1219                     JCTree constrDef = defaultConstructor(make.at(tree.pos), helper);
1220                     tree.defs = tree.defs.prepend(constrDef);
1221                     defaultConstructorGenerated = true;
1222                 } else {
1223                     /* there is an explicit constructor that match the canonical constructor by type
1224                        let's check that the match is also by name
1225                     */
1226                     List<Name> recordComponentNames = TreeInfo.recordFields(tree).map(vd -> vd.sym.name);
1227                     List<Name> initParamNames = canonicalInit.params.map(p -> p.name);
1228                     if (!initParamNames.equals(recordComponentNames)) {
1229                         log.error(canonicalDecl, Errors.CanonicalWithNameMismatch);
1230                     }
1231                     // let's use the RECORD flag to mark it as the canonical constructor
1232                     canonicalInit.flags_field |= Flags.RECORD;
1233                 }
1234             }
1235 
1236             if (lookupMethod(tree.sym, names.toString, List.nil()) == null) {
1237                 // public String toString() { return ???; }
1238                 JCMethodDecl toString = make.
1239                     MethodDef(make.Modifiers(Flags.PUBLIC | Flags.RECORD | Flags.MANDATED),
1240                               names.toString,
1241                               make.Type(syms.stringType),
1242                               List.nil(),
1243                               List.nil(),
1244                               List.nil(), // thrown
1245                               null,
1246                               null);
1247                 memberEnter.memberEnter(toString, env);
1248             }
1249 
1250             if (lookupMethod(tree.sym, names.hashCode, List.nil()) == null) {
1251                 // public int hashCode() { return ???; }
1252                 JCMethodDecl hashCode = make.
1253                     MethodDef(make.Modifiers(Flags.PUBLIC | Flags.RECORD | Flags.FINAL | Flags.MANDATED),
1254                               names.hashCode,
1255                               make.Type(syms.intType),
1256                               List.nil(),
1257                               List.nil(),
1258                               List.nil(), // thrown
1259                               null,
1260                               null);
1261                 memberEnter.memberEnter(hashCode, env);
1262             }
1263 
1264             if (lookupMethod(tree.sym, names.equals, List.of(syms.objectType)) == null) {
1265                 // public boolean equals(Object o) { return ???; }
1266                 JCMethodDecl equals = make.
1267                     MethodDef(make.Modifiers(Flags.PUBLIC | Flags.RECORD | Flags.FINAL | Flags.MANDATED),
1268                               names.equals,
1269                               make.Type(syms.booleanType),
1270                               List.nil(),
1271                               List.of(make.VarDef(make.Modifiers(Flags.PARAMETER),
1272                                                 names.fromString("o"),
1273                                                 make.Type(syms.objectType), null)),
1274                               List.nil(), // thrown
1275                               null,
1276                               null);
1277                 memberEnter.memberEnter(equals, env);
1278             }
1279 
1280             if (attr.isSerializable(tree.sym.type)) {
1281                 if (lookupMethod(tree.sym, names.readResolve, List.nil()) == null &&
1282                     lookupMethod(tree.sym, names.readObject, List.nil()) == null) {
1283                     // private Object readResolve() { return ???; }
1284                     JCMethodDecl readResolve = make.
1285                         MethodDef(make.Modifiers(Flags.PRIVATE | Flags.RECORD | Flags.FINAL | Flags.MANDATED),
1286                                   names.readResolve,
1287                                   make.Type(syms.objectType),
1288                                   List.nil(),
1289                                   List.nil(),
1290                                   List.nil(), // thrown
1291                                   null,
1292                                   null);
1293                     memberEnter.memberEnter(readResolve, env);
1294                 }
1295             }
1296         }
1297     }
1298 
1299     private MethodSymbol lookupMethod(TypeSymbol tsym, Name name, List<Type> argtypes) {
1300         for (Symbol s : tsym.members().getSymbolsByName(name, s -> s.kind == MTH)) {
1301             if (types.isSameTypes(s.type.getParameterTypes(), argtypes)) {
1302                 return (MethodSymbol) s;
1303             }
1304         }
1305         return null;
1306     }
1307 
1308 /* ***************************************************************************
1309  * tree building
1310  ****************************************************************************/
1311 
1312     interface DefaultConstructorHelper {
1313        Type constructorType();
1314        MethodSymbol constructorSymbol();
1315        Type enclosingType();
1316        TypeSymbol owner();
1317        List<Name> superArgs();
1318        List<Name> inits();
1319        default JCMethodDecl finalAdjustment(JCMethodDecl md) { return md; }
1320     }
1321 
1322     class BasicConstructorHelper implements DefaultConstructorHelper {
1323 
1324         TypeSymbol owner;
1325         Type constructorType;
1326         MethodSymbol constructorSymbol;
1327 
1328         BasicConstructorHelper(TypeSymbol owner) {
1329             this.owner = owner;
1330         }
1331 
1332         @Override
1333         public Type constructorType() {
1334             if (constructorType == null) {
1335                 constructorType = new MethodType(List.nil(), syms.voidType, List.nil(), syms.methodClass);
1336             }
1337             return constructorType;
1338         }
1339 
1340         @Override
1341         public MethodSymbol constructorSymbol() {
1342             if (constructorSymbol == null) {
1343                 long flags;
1344                 if ((owner().flags() & ENUM) != 0 &&
1345                     (types.supertype(owner().type).tsym == syms.enumSym)) {
1346                     // constructors of true enums are private
1347                     flags = PRIVATE | GENERATEDCONSTR;
1348                 } else {
1349                     flags = (owner().flags() & AccessFlags) | GENERATEDCONSTR;
1350                 }
1351                 constructorSymbol = new MethodSymbol(flags, names.init,
1352                     constructorType(), owner());
1353             }
1354             return constructorSymbol;
1355         }
1356 
1357         @Override
1358         public Type enclosingType() {
1359             return Type.noType;
1360         }
1361 
1362         @Override
1363         public TypeSymbol owner() {
1364             return owner;
1365         }
1366 
1367         @Override
1368         public List<Name> superArgs() {
1369             return List.nil();
1370         }
1371 
1372         @Override
1373         public List<Name> inits() {
1374             return List.nil();
1375         }
1376     }
1377 
1378     class AnonClassConstructorHelper extends BasicConstructorHelper {
1379 
1380         MethodSymbol constr;
1381         Type encl;
1382         boolean based = false;
1383 
1384         AnonClassConstructorHelper(TypeSymbol owner, MethodSymbol constr, JCExpression encl) {
1385             super(owner);
1386             this.constr = constr;
1387             this.encl = encl != null ? encl.type : Type.noType;
1388         }
1389 
1390         @Override
1391         public Type constructorType() {
1392             if (constructorType == null) {
1393                 Type ctype = types.memberType(owner.type, constr);
1394                 if (!enclosingType().hasTag(NONE)) {
1395                     ctype = types.createMethodTypeWithParameters(ctype, ctype.getParameterTypes().prepend(enclosingType()));
1396                     based = true;
1397                 }
1398                 constructorType = ctype;
1399             }
1400             return constructorType;
1401         }
1402 
1403         @Override
1404         public MethodSymbol constructorSymbol() {
1405             MethodSymbol csym = super.constructorSymbol();
1406             csym.flags_field |= ANONCONSTR | (constr.flags() & VARARGS);
1407             csym.flags_field |= based ? ANONCONSTR_BASED : 0;
1408             ListBuffer<VarSymbol> params = new ListBuffer<>();
1409             List<Type> argtypes = constructorType().getParameterTypes();
1410             if (!enclosingType().hasTag(NONE)) {
1411                 argtypes = argtypes.tail;
1412                 params = params.prepend(new VarSymbol(PARAMETER, make.paramName(0), enclosingType(), csym));
1413             }
1414             if (constr.params != null) {
1415                 for (VarSymbol p : constr.params) {
1416                     params.add(new VarSymbol(PARAMETER | p.flags(), p.name, argtypes.head, csym));
1417                     argtypes = argtypes.tail;
1418                 }
1419             }
1420             csym.params = params.toList();
1421             return csym;
1422         }
1423 
1424         @Override
1425         public Type enclosingType() {
1426             return encl;
1427         }
1428 
1429         @Override
1430         public List<Name> superArgs() {
1431             List<JCVariableDecl> params = make.Params(constructorType().getParameterTypes(), constructorSymbol());
1432             if (!enclosingType().hasTag(NONE)) {
1433                 params = params.tail;
1434             }
1435             return params.map(vd -> vd.name);
1436         }
1437     }
1438 
1439     class RecordConstructorHelper extends BasicConstructorHelper {
1440 
1441         List<VarSymbol> recordFieldSymbols;
1442         List<JCVariableDecl> recordFieldDecls;
1443 
1444         RecordConstructorHelper(TypeSymbol owner, List<JCVariableDecl> recordFieldDecls) {
1445             super(owner);
1446             this.recordFieldDecls = recordFieldDecls;
1447             this.recordFieldSymbols = recordFieldDecls.map(vd -> vd.sym);
1448         }
1449 
1450         @Override
1451         public Type constructorType() {
1452             if (constructorType == null) {
1453                 List<Type> argtypes = recordFieldSymbols.map(v -> v.type);
1454                 constructorType = new MethodType(argtypes, syms.voidType, List.nil(), syms.methodClass);
1455             }
1456             return constructorType;
1457         }
1458 
1459         @Override
1460         public MethodSymbol constructorSymbol() {
1461             MethodSymbol csym = super.constructorSymbol();
1462             ListBuffer<VarSymbol> params = new ListBuffer<>();
1463             for (VarSymbol p : recordFieldSymbols) {
1464                 params.add(new VarSymbol(MANDATED | PARAMETER | RECORD, p.name, p.type, csym));
1465             }
1466             csym.params = params.toList();
1467             csym.flags_field |= RECORD | PUBLIC;
1468             return csym;
1469         }
1470 
1471         @Override
1472         public List<Name> inits() {
1473             return recordFieldSymbols.map(v -> v.name);
1474         }
1475 
1476         @Override
1477         public JCMethodDecl finalAdjustment(JCMethodDecl md) {
1478             List<JCVariableDecl> tmpRecordFieldDecls = recordFieldDecls;
1479             for (JCVariableDecl arg : md.params) {
1480                 arg.mods.annotations = tmpRecordFieldDecls.head.mods.annotations;
1481                 tmpRecordFieldDecls = tmpRecordFieldDecls.tail;
1482             }
1483             return md;
1484         }
1485     }
1486 
1487     JCTree defaultConstructor(TreeMaker make, DefaultConstructorHelper helper) {
1488         Type initType = helper.constructorType();
1489         MethodSymbol initSym = helper.constructorSymbol();
1490         ListBuffer<JCStatement> stats = new ListBuffer<>();
1491         if (helper.owner().type != syms.objectType) {
1492             JCExpression meth;
1493             if (!helper.enclosingType().hasTag(NONE)) {
1494                 meth = make.Select(make.Ident(initSym.params.head), names._super);
1495             } else {
1496                 meth = make.Ident(names._super);
1497             }
1498             List<JCExpression> typeargs = initType.getTypeArguments().nonEmpty() ?
1499                     make.Types(initType.getTypeArguments()) : null;
1500             JCStatement superCall = make.Exec(make.Apply(typeargs, meth, helper.superArgs().map(make::Ident)));
1501             stats.add(superCall);
1502         }
1503         helper.inits().forEach((initName) -> {
1504             stats.add(make.Exec(make.Assign(make.Select(make.Ident(names._this), initName), make.Ident(initName))));
1505         });
1506         JCMethodDecl result = make.MethodDef(initSym, make.Block(0, stats.toList()));
1507         return helper.finalAdjustment(result);
1508     }
1509 
1510     /**
1511      * Mark sym deprecated if annotations contain @Deprecated annotation.
1512      */
1513     public void markDeprecated(Symbol sym, List<JCAnnotation> annotations, Env<AttrContext> env) {
1514         // In general, we cannot fully process annotations yet,  but we
1515         // can attribute the annotation types and then check to see if the
1516         // @Deprecated annotation is present.
1517         attr.attribAnnotationTypes(annotations, env);
1518         handleDeprecatedAnnotations(annotations, sym);
1519     }
1520 
1521     /**
1522      * If a list of annotations contains a reference to java.lang.Deprecated,
1523      * set the DEPRECATED flag.
1524      * If the annotation is marked forRemoval=true, also set DEPRECATED_REMOVAL.
1525      **/
1526     private void handleDeprecatedAnnotations(List<JCAnnotation> annotations, Symbol sym) {
1527         for (List<JCAnnotation> al = annotations; !al.isEmpty(); al = al.tail) {
1528             JCAnnotation a = al.head;
1529             if (a.annotationType.type == syms.deprecatedType) {
1530                 sym.flags_field |= (Flags.DEPRECATED | Flags.DEPRECATED_ANNOTATION);
1531                 a.args.stream()
1532                         .filter(e -> e.hasTag(ASSIGN))
1533                         .map(e -> (JCAssign) e)
1534                         .filter(assign -> TreeInfo.name(assign.lhs) == names.forRemoval)
1535                         .findFirst()
1536                         .ifPresent(assign -> {
1537                             JCExpression rhs = TreeInfo.skipParens(assign.rhs);
1538                             if (rhs.hasTag(LITERAL)
1539                                     && Boolean.TRUE.equals(((JCLiteral) rhs).getValue())) {
1540                                 sym.flags_field |= DEPRECATED_REMOVAL;
1541                             }
1542                         });
1543             }
1544         }
1545     }
1546 }