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