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