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