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