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