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