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.jvm.Target;
  45 import com.sun.tools.javac.tree.*;
  46 import com.sun.tools.javac.util.*;
  47 import com.sun.tools.javac.util.DefinedBy.Api;
  48 
  49 import com.sun.tools.javac.code.Symbol.*;
  50 import com.sun.tools.javac.code.Type.*;
  51 import com.sun.tools.javac.resources.CompilerProperties.Errors;
  52 import com.sun.tools.javac.tree.JCTree.*;
  53 
  54 import static com.sun.tools.javac.code.Flags.*;
  55 import static com.sun.tools.javac.code.Flags.ANNOTATION;
  56 import static com.sun.tools.javac.code.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 import com.sun.tools.javac.resources.CompilerProperties.Fragments;
  61 
  62 import static com.sun.tools.javac.code.TypeTag.*;
  63 import static com.sun.tools.javac.tree.JCTree.Tag.*;
  64 
  65 import com.sun.tools.javac.util.Dependencies.CompletionCause;
  66 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag;
  67 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
  68 
  69 /** This is the second phase of Enter, in which classes are completed
  70  *  by resolving their headers and entering their members in the into
  71  *  the class scope. See Enter for an overall overview.
  72  *
  73  *  This class uses internal phases to process the classes. When a phase
  74  *  processes classes, the lower phases are not invoked until all classes
  75  *  pass through the current phase. Note that it is possible that upper phases
  76  *  are run due to recursive completion. The internal phases are:
  77  *  - ImportPhase: shallow pass through imports, adds information about imports
  78  *                 the NamedImportScope and StarImportScope, but avoids queries
  79  *                 about class hierarchy.
  80  *  - HierarchyPhase: resolves the supertypes of the given class. Does not handle
  81  *                    type parameters of the class or type argument of the supertypes.
  82  *  - HeaderPhase: finishes analysis of the header of the given class by resolving
  83  *                 type parameters, attributing supertypes including type arguments
  84  *                 and scheduling full annotation attribution. This phase also adds
  85  *                 a synthetic default constructor if needed and synthetic "this" field.
  86  *  - MembersPhase: resolves headers for fields, methods and constructors in the given class.
  87  *                  Also generates synthetic enum members.
  88  *
  89  *  <p><b>This is NOT part of any supported API.
  90  *  If you write code that depends on this, you do so at your own risk.
  91  *  This code and its internal interfaces are subject to change or
  92  *  deletion without notice.</b>
  93  */
  94 public class TypeEnter implements Completer {
  95     protected static final Context.Key<TypeEnter> typeEnterKey = new Context.Key<>();
  96 
  97     /** A switch to determine whether we check for package/class conflicts
  98      */
  99     static final boolean checkClash = true;
 100 
 101     private final Names names;
 102     private final Enter enter;
 103     private final MemberEnter memberEnter;
 104     private final Log log;
 105     private final Check chk;
 106     private final Attr attr;
 107     private final Symtab syms;
 108     private final TreeMaker make;
 109     private final Todo todo;
 110     private final Annotate annotate;
 111     private final TypeAnnotations typeAnnotations;
 112     private final Types types;
 113     private final JCDiagnostic.Factory diags;
 114     private final DeferredLintHandler deferredLintHandler;
 115     private final Lint lint;
 116     private final TypeEnvs typeEnvs;
 117     private final Dependencies dependencies;
 118     private final Preview preview;
 119 
 120     public static TypeEnter instance(Context context) {
 121         TypeEnter instance = context.get(typeEnterKey);
 122         if (instance == null)
 123             instance = new TypeEnter(context);
 124         return instance;
 125     }
 126 
 127     protected TypeEnter(Context context) {
 128         context.put(typeEnterKey, this);
 129         names = Names.instance(context);
 130         enter = Enter.instance(context);
 131         memberEnter = MemberEnter.instance(context);
 132         log = Log.instance(context);
 133         chk = Check.instance(context);
 134         attr = Attr.instance(context);
 135         syms = Symtab.instance(context);
 136         make = TreeMaker.instance(context);
 137         todo = Todo.instance(context);
 138         annotate = Annotate.instance(context);
 139         typeAnnotations = TypeAnnotations.instance(context);
 140         types = Types.instance(context);
 141         diags = JCDiagnostic.Factory.instance(context);
 142         deferredLintHandler = DeferredLintHandler.instance(context);
 143         lint = Lint.instance(context);
 144         typeEnvs = TypeEnvs.instance(context);
 145         dependencies = Dependencies.instance(context);
 146         preview = Preview.instance(context);
 147         Source source = Source.instance(context);
 148         allowTypeAnnos = Feature.TYPE_ANNOTATIONS.allowedInSource(source);
 149         allowDeprecationOnImport = Feature.DEPRECATION_ON_IMPORT.allowedInSource(source);
 150     }
 151 
 152     /** Switch: support type annotations.
 153      */
 154     boolean allowTypeAnnos;
 155 
 156     /**
 157      * Switch: should deprecation warnings be issued on import
 158      */
 159     boolean allowDeprecationOnImport;
 160 
 161     /** A flag to disable completion from time to time during member
 162      *  enter, as we only need to look up types.  This avoids
 163      *  unnecessarily deep recursion.
 164      */
 165     boolean completionEnabled = true;
 166 
 167     /* Verify Imports:
 168      */
 169     protected void ensureImportsChecked(List<JCCompilationUnit> trees) {
 170         // if there remain any unimported toplevels (these must have
 171         // no classes at all), process their import statements as well.
 172         for (JCCompilationUnit tree : trees) {
 173             if (!tree.starImportScope.isFilled()) {
 174                 Env<AttrContext> topEnv = enter.topLevelEnv(tree);
 175                 finishImports(tree, () -> { completeClass.resolveImports(tree, topEnv); });
 176             }
 177         }
 178     }
 179 
 180 /* ********************************************************************
 181  * Source completer
 182  *********************************************************************/
 183 
 184     /** Complete entering a class.
 185      *  @param sym         The symbol of the class to be completed.
 186      */
 187     @Override
 188     public void complete(Symbol sym) throws CompletionFailure {
 189         // Suppress some (recursive) MemberEnter invocations
 190         if (!completionEnabled) {
 191             // Re-install same completer for next time around and return.
 192             Assert.check((sym.flags() & Flags.COMPOUND) == 0);
 193             sym.completer = this;
 194             return;
 195         }
 196 
 197         try {
 198             annotate.blockAnnotations();
 199             sym.flags_field |= UNATTRIBUTED;
 200 
 201             List<Env<AttrContext>> queue;
 202 
 203             dependencies.push((ClassSymbol) sym, CompletionCause.MEMBER_ENTER);
 204             try {
 205                 queue = completeClass.completeEnvs(List.of(typeEnvs.get((ClassSymbol) sym)));
 206             } finally {
 207                 dependencies.pop();
 208             }
 209 
 210             if (!queue.isEmpty()) {
 211                 Set<JCCompilationUnit> seen = new HashSet<>();
 212 
 213                 for (Env<AttrContext> env : queue) {
 214                     if (env.toplevel.defs.contains(env.enclClass) && seen.add(env.toplevel)) {
 215                         finishImports(env.toplevel, () -> {});
 216                     }
 217                 }
 218             }
 219         } finally {
 220             annotate.unblockAnnotations();
 221         }
 222     }
 223 
 224     void finishImports(JCCompilationUnit toplevel, Runnable resolve) {
 225         JavaFileObject prev = log.useSource(toplevel.sourcefile);
 226         try {
 227             resolve.run();
 228             chk.checkImportsUnique(toplevel);
 229             chk.checkImportsResolvable(toplevel);
 230             chk.checkImportedPackagesObservable(toplevel);
 231             toplevel.namedImportScope.finalizeScope();
 232             toplevel.starImportScope.finalizeScope();
 233         } catch (CompletionFailure cf) {
 234             chk.completionError(toplevel.pos(), cf);
 235         } finally {
 236             log.useSource(prev);
 237         }
 238     }
 239 
 240     abstract class Phase {
 241         private final ListBuffer<Env<AttrContext>> queue = new ListBuffer<>();
 242         private final Phase next;
 243         private final CompletionCause phaseName;
 244 
 245         Phase(CompletionCause phaseName, Phase next) {
 246             this.phaseName = phaseName;
 247             this.next = next;
 248         }
 249 
 250         public final List<Env<AttrContext>> completeEnvs(List<Env<AttrContext>> envs) {
 251             boolean firstToComplete = queue.isEmpty();
 252 
 253             Phase prevTopLevelPhase = topLevelPhase;
 254             boolean success = false;
 255 
 256             try {
 257                 topLevelPhase = this;
 258                 doCompleteEnvs(envs);
 259                 success = true;
 260             } finally {
 261                 topLevelPhase = prevTopLevelPhase;
 262                 if (!success && firstToComplete) {
 263                     //an exception was thrown, e.g. BreakAttr:
 264                     //the queue would become stale, clear it:
 265                     queue.clear();
 266                 }
 267             }
 268 
 269             if (firstToComplete) {
 270                 List<Env<AttrContext>> out = queue.toList();
 271 
 272                 queue.clear();
 273                 return next != null ? next.completeEnvs(out) : out;
 274             } else {
 275                 return List.nil();
 276             }
 277         }
 278 
 279         protected void doCompleteEnvs(List<Env<AttrContext>> envs) {
 280             for (Env<AttrContext> env : envs) {
 281                 JCClassDecl tree = (JCClassDecl)env.tree;
 282 
 283                 queue.add(env);
 284 
 285                 JavaFileObject prev = log.useSource(env.toplevel.sourcefile);
 286                 DiagnosticPosition prevLintPos = deferredLintHandler.setPos(tree.pos());
 287                 try {
 288                     dependencies.push(env.enclClass.sym, phaseName);
 289                     runPhase(env);
 290                 } catch (CompletionFailure ex) {
 291                     chk.completionError(tree.pos(), ex);
 292                 } finally {
 293                     dependencies.pop();
 294                     deferredLintHandler.setPos(prevLintPos);
 295                     log.useSource(prev);
 296                 }
 297             }
 298         }
 299 
 300         protected abstract void runPhase(Env<AttrContext> env);
 301     }
 302 
 303     private final ImportsPhase completeClass = new ImportsPhase();
 304     private Phase topLevelPhase;
 305 
 306     /**Analyze import clauses.
 307      */
 308     private final class ImportsPhase extends Phase {
 309 
 310         public ImportsPhase() {
 311             super(CompletionCause.IMPORTS_PHASE, new HierarchyPhase());
 312         }
 313 
 314         Env<AttrContext> env;
 315         ImportFilter staticImportFilter;
 316         ImportFilter typeImportFilter;
 317         BiConsumer<JCImport, CompletionFailure> cfHandler =
 318                 (imp, cf) -> chk.completionError(imp.pos(), cf);
 319 
 320         @Override
 321         protected void runPhase(Env<AttrContext> env) {
 322             JCClassDecl tree = env.enclClass;
 323             ClassSymbol sym = tree.sym;
 324 
 325             // If sym is a toplevel-class, make sure any import
 326             // clauses in its source file have been seen.
 327             if (sym.owner.kind == PCK) {
 328                 resolveImports(env.toplevel, env.enclosing(TOPLEVEL));
 329                 todo.append(env);
 330             }
 331 
 332             if (sym.owner.kind == TYP)
 333                 sym.owner.complete();
 334         }
 335 
 336         private void resolveImports(JCCompilationUnit tree, Env<AttrContext> env) {
 337             if (tree.starImportScope.isFilled()) {
 338                 // we must have already processed this toplevel
 339                 return;
 340             }
 341 
 342             ImportFilter prevStaticImportFilter = staticImportFilter;
 343             ImportFilter prevTypeImportFilter = typeImportFilter;
 344             DiagnosticPosition prevLintPos = deferredLintHandler.immediate();
 345             Lint prevLint = chk.setLint(lint);
 346             Env<AttrContext> prevEnv = this.env;
 347             try {
 348                 this.env = env;
 349                 final PackageSymbol packge = env.toplevel.packge;
 350                 this.staticImportFilter =
 351                         (origin, sym) -> sym.isStatic() &&
 352                                          chk.importAccessible(sym, packge) &&
 353                                          sym.isMemberOf((TypeSymbol) origin.owner, types);
 354                 this.typeImportFilter =
 355                         (origin, sym) -> sym.kind == TYP &&
 356                                          chk.importAccessible(sym, packge);
 357 
 358                 // Import-on-demand java.lang.
 359                 PackageSymbol javaLang = syms.enterPackage(syms.java_base, names.java_lang);
 360                 if (javaLang.members().isEmpty() && !javaLang.exists())
 361                     throw new FatalError(diags.fragment(Fragments.FatalErrNoJavaLang));
 362                 importAll(make.at(tree.pos()).Import(make.QualIdent(javaLang), false), javaLang, env);
 363 
 364                 JCModuleDecl decl = tree.getModuleDecl();
 365 
 366                 // Process the package def and all import clauses.
 367                 if (tree.getPackage() != null && decl == null)
 368                     checkClassPackageClash(tree.getPackage());
 369 
 370                 for (JCImport imp : tree.getImports()) {
 371                     doImport(imp);
 372                 }
 373 
 374                 if (decl != null) {
 375                     //check @Deprecated:
 376                     markDeprecated(decl.sym, decl.mods.annotations, env);
 377                     // process module annotations
 378                     annotate.annotateLater(decl.mods.annotations, env, env.toplevel.modle, null);
 379                 }
 380             } finally {
 381                 this.env = prevEnv;
 382                 chk.setLint(prevLint);
 383                 deferredLintHandler.setPos(prevLintPos);
 384                 this.staticImportFilter = prevStaticImportFilter;
 385                 this.typeImportFilter = prevTypeImportFilter;
 386             }
 387         }
 388 
 389         private void checkClassPackageClash(JCPackageDecl tree) {
 390             // check that no class exists with same fully qualified name as
 391             // toplevel package
 392             if (checkClash && tree.pid != null) {
 393                 Symbol p = env.toplevel.packge;
 394                 while (p.owner != syms.rootPackage) {
 395                     p.owner.complete(); // enter all class members of p
 396                     //need to lookup the owning module/package:
 397                     PackageSymbol pack = syms.lookupPackage(env.toplevel.modle, p.owner.getQualifiedName());
 398                     if (syms.getClass(pack.modle, p.getQualifiedName()) != null) {
 399                         log.error(tree.pos,
 400                                   Errors.PkgClashesWithClassOfSameName(p));
 401                     }
 402                     p = p.owner;
 403                 }
 404             }
 405             // process package annotations
 406             annotate.annotateLater(tree.annotations, env, env.toplevel.packge, null);
 407         }
 408 
 409         private void doImport(JCImport tree) {
 410             JCFieldAccess imp = (JCFieldAccess)tree.qualid;
 411             Name name = TreeInfo.name(imp);
 412 
 413             // Create a local environment pointing to this tree to disable
 414             // effects of other imports in Resolve.findGlobalType
 415             Env<AttrContext> localEnv = env.dup(tree);
 416 
 417             TypeSymbol p = attr.attribImportQualifier(tree, localEnv).tsym;
 418             if (name == names.asterisk) {
 419                 // Import on demand.
 420                 chk.checkCanonical(imp.selected);
 421                 if (tree.staticImport)
 422                     importStaticAll(tree, p, env);
 423                 else
 424                     importAll(tree, p, env);
 425             } else {
 426                 // Named type import.
 427                 if (tree.staticImport) {
 428                     importNamedStatic(tree, p, name, localEnv);
 429                     chk.checkCanonical(imp.selected);
 430                 } else {
 431                     Type importedType = attribImportType(imp, localEnv);
 432                     Type originalType = importedType.getOriginalType();
 433                     TypeSymbol c = originalType.hasTag(CLASS) ? originalType.tsym : importedType.tsym;
 434                     chk.checkCanonical(imp);
 435                     importNamed(tree.pos(), c, env, tree);
 436                 }
 437             }
 438         }
 439 
 440         Type attribImportType(JCTree tree, Env<AttrContext> env) {
 441             Assert.check(completionEnabled);
 442             Lint prevLint = chk.setLint(allowDeprecationOnImport ?
 443                     lint : lint.suppress(LintCategory.DEPRECATION, LintCategory.REMOVAL, LintCategory.PREVIEW));
 444             try {
 445                 // To prevent deep recursion, suppress completion of some
 446                 // types.
 447                 completionEnabled = false;
 448                 return attr.attribType(tree, env);
 449             } finally {
 450                 completionEnabled = true;
 451                 chk.setLint(prevLint);
 452             }
 453         }
 454 
 455         /** Import all classes of a class or package on demand.
 456          *  @param imp           The import that is being handled.
 457          *  @param tsym          The class or package the members of which are imported.
 458          *  @param env           The env in which the imported classes will be entered.
 459          */
 460         private void importAll(JCImport imp,
 461                                final TypeSymbol tsym,
 462                                Env<AttrContext> env) {
 463             env.toplevel.starImportScope.importAll(types, tsym.members(), typeImportFilter, imp, cfHandler);
 464         }
 465 
 466         /** Import all static members of a class or package on demand.
 467          *  @param imp           The import that is being handled.
 468          *  @param tsym          The class or package the members of which are imported.
 469          *  @param env           The env in which the imported classes will be entered.
 470          */
 471         private void importStaticAll(JCImport imp,
 472                                      final TypeSymbol tsym,
 473                                      Env<AttrContext> env) {
 474             final StarImportScope toScope = env.toplevel.starImportScope;
 475             final TypeSymbol origin = tsym;
 476 
 477             toScope.importAll(types, origin.members(), staticImportFilter, imp, cfHandler);
 478         }
 479 
 480         /** Import statics types of a given name.  Non-types are handled in Attr.
 481          *  @param imp           The import that is being handled.
 482          *  @param tsym          The class from which the name is imported.
 483          *  @param name          The (simple) name being imported.
 484          *  @param env           The environment containing the named import
 485          *                  scope to add to.
 486          */
 487         private void importNamedStatic(final JCImport imp,
 488                                        final TypeSymbol tsym,
 489                                        final Name name,
 490                                        final Env<AttrContext> env) {
 491             if (tsym.kind != TYP) {
 492                 log.error(DiagnosticFlag.RECOVERABLE, imp.pos(), Errors.StaticImpOnlyClassesAndInterfaces);
 493                 return;
 494             }
 495 
 496             final NamedImportScope toScope = env.toplevel.namedImportScope;
 497             final Scope originMembers = tsym.members();
 498 
 499             imp.importScope = toScope.importByName(types, originMembers, name, staticImportFilter, imp, cfHandler);
 500         }
 501 
 502         /** Import given class.
 503          *  @param pos           Position to be used for error reporting.
 504          *  @param tsym          The class to be imported.
 505          *  @param env           The environment containing the named import
 506          *                  scope to add to.
 507          */
 508         private void importNamed(DiagnosticPosition pos, final Symbol tsym, Env<AttrContext> env, JCImport imp) {
 509             if (tsym.kind == TYP)
 510                 imp.importScope = env.toplevel.namedImportScope.importType(tsym.owner.members(), tsym.owner.members(), tsym);
 511         }
 512 
 513     }
 514 
 515     /**Defines common utility methods used by the HierarchyPhase and HeaderPhase.
 516      */
 517     private abstract class AbstractHeaderPhase extends Phase {
 518 
 519         public AbstractHeaderPhase(CompletionCause phaseName, Phase next) {
 520             super(phaseName, next);
 521         }
 522 
 523         protected Env<AttrContext> baseEnv(JCClassDecl tree, Env<AttrContext> env) {
 524             WriteableScope baseScope = WriteableScope.create(tree.sym);
 525             //import already entered local classes into base scope
 526             for (Symbol sym : env.outer.info.scope.getSymbols(NON_RECURSIVE)) {
 527                 if (sym.isDirectlyOrIndirectlyLocal()) {
 528                     baseScope.enter(sym);
 529                 }
 530             }
 531             //import current type-parameters into base scope
 532             if (tree.typarams != null)
 533                 for (List<JCTypeParameter> typarams = tree.typarams;
 534                      typarams.nonEmpty();
 535                      typarams = typarams.tail)
 536                     baseScope.enter(typarams.head.type.tsym);
 537             Env<AttrContext> outer = env.outer; // the base clause can't see members of this class
 538             Env<AttrContext> localEnv = outer.dup(tree, outer.info.dup(baseScope));
 539             localEnv.baseClause = true;
 540             localEnv.outer = outer;
 541             localEnv.info.isSelfCall = false;
 542             return localEnv;
 543         }
 544 
 545         /** Generate a base clause for an enum type.
 546          *  @param pos              The position for trees and diagnostics, if any
 547          *  @param c                The class symbol of the enum
 548          */
 549         protected  JCExpression enumBase(int pos, ClassSymbol c) {
 550             JCExpression result = make.at(pos).
 551                 TypeApply(make.QualIdent(syms.enumSym),
 552                           List.of(make.Type(c.type)));
 553             return result;
 554         }
 555 
 556         /** Generate a base clause for a record type.
 557          *  @param pos              The position for trees and diagnostics, if any
 558          *  @param c                The class symbol of the record
 559          */
 560         protected  JCExpression recordBase(int pos, ClassSymbol c) {
 561             JCExpression result = make.at(pos).
 562                 QualIdent(syms.recordType.tsym);
 563             return result;
 564         }
 565 
 566         protected Type modelMissingTypes(Env<AttrContext> env, Type t, final JCExpression tree, final boolean interfaceExpected) {
 567             if (!t.hasTag(ERROR))
 568                 return t;
 569 
 570             return new ErrorType(t.getOriginalType(), t.tsym) {
 571                 private Type modelType;
 572 
 573                 @Override
 574                 public Type getModelType() {
 575                     if (modelType == null)
 576                         modelType = new Synthesizer(env.toplevel.modle, getOriginalType(), interfaceExpected).visit(tree);
 577                     return modelType;
 578                 }
 579             };
 580         }
 581             // where:
 582             private class Synthesizer extends JCTree.Visitor {
 583                 ModuleSymbol msym;
 584                 Type originalType;
 585                 boolean interfaceExpected;
 586                 List<ClassSymbol> synthesizedSymbols = List.nil();
 587                 Type result;
 588 
 589                 Synthesizer(ModuleSymbol msym, Type originalType, boolean interfaceExpected) {
 590                     this.msym = msym;
 591                     this.originalType = originalType;
 592                     this.interfaceExpected = interfaceExpected;
 593                 }
 594 
 595                 Type visit(JCTree tree) {
 596                     tree.accept(this);
 597                     return result;
 598                 }
 599 
 600                 List<Type> visit(List<? extends JCTree> trees) {
 601                     ListBuffer<Type> lb = new ListBuffer<>();
 602                     for (JCTree t: trees)
 603                         lb.append(visit(t));
 604                     return lb.toList();
 605                 }
 606 
 607                 @Override
 608                 public void visitTree(JCTree tree) {
 609                     result = syms.errType;
 610                 }
 611 
 612                 @Override
 613                 public void visitIdent(JCIdent tree) {
 614                     if (!tree.type.hasTag(ERROR)) {
 615                         result = tree.type;
 616                     } else {
 617                         result = synthesizeClass(tree.name, msym.unnamedPackage).type;
 618                     }
 619                 }
 620 
 621                 @Override
 622                 public void visitSelect(JCFieldAccess tree) {
 623                     if (!tree.type.hasTag(ERROR)) {
 624                         result = tree.type;
 625                     } else {
 626                         Type selectedType;
 627                         boolean prev = interfaceExpected;
 628                         try {
 629                             interfaceExpected = false;
 630                             selectedType = visit(tree.selected);
 631                         } finally {
 632                             interfaceExpected = prev;
 633                         }
 634                         ClassSymbol c = synthesizeClass(tree.name, selectedType.tsym);
 635                         result = c.type;
 636                     }
 637                 }
 638 
 639                 @Override
 640                 public void visitTypeApply(JCTypeApply tree) {
 641                     if (!tree.type.hasTag(ERROR)) {
 642                         result = tree.type;
 643                     } else {
 644                         ClassType clazzType = (ClassType) visit(tree.clazz);
 645                         if (synthesizedSymbols.contains(clazzType.tsym))
 646                             synthesizeTyparams((ClassSymbol) clazzType.tsym, tree.arguments.size());
 647                         final List<Type> actuals = visit(tree.arguments);
 648                         result = new ErrorType(tree.type, clazzType.tsym) {
 649                             @Override @DefinedBy(Api.LANGUAGE_MODEL)
 650                             public List<Type> getTypeArguments() {
 651                                 return actuals;
 652                             }
 653                         };
 654                     }
 655                 }
 656 
 657                 ClassSymbol synthesizeClass(Name name, Symbol owner) {
 658                     int flags = interfaceExpected ? INTERFACE : 0;
 659                     ClassSymbol c = new ClassSymbol(flags, name, owner);
 660                     c.members_field = new Scope.ErrorScope(c);
 661                     c.type = new ErrorType(originalType, c) {
 662                         @Override @DefinedBy(Api.LANGUAGE_MODEL)
 663                         public List<Type> getTypeArguments() {
 664                             return typarams_field;
 665                         }
 666                     };
 667                     synthesizedSymbols = synthesizedSymbols.prepend(c);
 668                     return c;
 669                 }
 670 
 671                 void synthesizeTyparams(ClassSymbol sym, int n) {
 672                     ClassType ct = (ClassType) sym.type;
 673                     Assert.check(ct.typarams_field.isEmpty());
 674                     if (n == 1) {
 675                         TypeVar v = new TypeVar(names.fromString("T"), sym, syms.botType);
 676                         ct.typarams_field = ct.typarams_field.prepend(v);
 677                     } else {
 678                         for (int i = n; i > 0; i--) {
 679                             TypeVar v = new TypeVar(names.fromString("T" + i), sym,
 680                                                     syms.botType);
 681                             ct.typarams_field = ct.typarams_field.prepend(v);
 682                         }
 683                     }
 684                 }
 685             }
 686 
 687         protected void attribSuperTypes(Env<AttrContext> env, Env<AttrContext> baseEnv) {
 688             JCClassDecl tree = env.enclClass;
 689             ClassSymbol sym = tree.sym;
 690             ClassType ct = (ClassType)sym.type;
 691             // Determine supertype.
 692             Type supertype;
 693             JCExpression extending;
 694 
 695             if (tree.extending != null) {
 696                 extending = clearTypeParams(tree.extending);
 697                 supertype = attr.attribBase(extending, baseEnv, true, false, true);
 698                 if (supertype == syms.recordType) {
 699                     log.error(tree, Errors.InvalidSupertypeRecord(supertype.tsym));
 700                 }
 701             } else {
 702                 extending = null;
 703                 supertype = ((tree.mods.flags & Flags.ENUM) != 0)
 704                 ? attr.attribBase(extending = enumBase(tree.pos, sym), baseEnv,
 705                                   true, false, false)
 706                 : (sym.fullname == names.java_lang_Object)
 707                 ? Type.noType
 708                 : sym.isRecord()
 709                 ? attr.attribBase(extending = recordBase(tree.pos, sym), baseEnv,
 710                                   true, false, false)
 711                 : syms.objectType;
 712             }
 713             ct.supertype_field = modelMissingTypes(baseEnv, supertype, extending, false);
 714 
 715             // Determine interfaces.
 716             ListBuffer<Type> interfaces = new ListBuffer<>();
 717             ListBuffer<Type> all_interfaces = null; // lazy init
 718             List<JCExpression> interfaceTrees = tree.implementing;
 719             for (JCExpression iface : interfaceTrees) {
 720                 iface = clearTypeParams(iface);
 721                 Type it = attr.attribBase(iface, baseEnv, false, true, true);
 722                 if (it.hasTag(CLASS)) {
 723                     interfaces.append(it);
 724                     if (all_interfaces != null) all_interfaces.append(it);
 725                 } else {
 726                     if (all_interfaces == null)
 727                         all_interfaces = new ListBuffer<Type>().appendList(interfaces);
 728                     all_interfaces.append(modelMissingTypes(baseEnv, it, iface, true));
 729                 }
 730             }
 731 
 732             // Determine permits.
 733             ListBuffer<Symbol> permittedSubtypeSymbols = new ListBuffer<>();
 734             List<JCExpression> permittedTrees = tree.permitting;
 735             for (JCExpression permitted : permittedTrees) {
 736                 Type pt = attr.attribBase(permitted, baseEnv, false, false, false);
 737                 permittedSubtypeSymbols.append(pt.tsym);
 738             }
 739 
 740             if ((sym.flags_field & ANNOTATION) != 0) {
 741                 ct.interfaces_field = List.of(syms.annotationType);
 742                 ct.all_interfaces_field = ct.interfaces_field;
 743             }  else {
 744                 ct.interfaces_field = interfaces.toList();
 745                 ct.all_interfaces_field = (all_interfaces == null)
 746                         ? ct.interfaces_field : all_interfaces.toList();
 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 }