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