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             final boolean isPrimitiveClass = (tree.mods.flags & Flags.PRIMITIVE_CLASS) != 0;
 695 
 696             if (tree.extending != null) {
 697                 extending = clearTypeParams(tree.extending);
 698                 supertype = attr.attribBase(extending, baseEnv, true, false, true);
 699                 if (supertype == syms.recordType) {
 700                     log.error(tree, Errors.InvalidSupertypeRecord(supertype.tsym));
 701                 }
 702             } else {
 703                 extending = null;
 704                 supertype = ((tree.mods.flags & Flags.ENUM) != 0)
 705                 ? attr.attribBase(extending = enumBase(tree.pos, sym), baseEnv,
 706                                   true, false, false)
 707                 : (sym.fullname == names.java_lang_Object)
 708                 ? Type.noType
 709                 : sym.isRecord()
 710                 ? attr.attribBase(extending = recordBase(tree.pos, sym), baseEnv,
 711                                   true, false, false)
 712                 : syms.objectType;
 713             }
 714             ct.supertype_field = modelMissingTypes(baseEnv, supertype, extending, false);
 715 
 716             // Determine interfaces.
 717             ListBuffer<Type> interfaces = new ListBuffer<>();
 718             ListBuffer<Type> all_interfaces = null; // lazy init
 719             List<JCExpression> interfaceTrees = tree.implementing;
 720             for (JCExpression iface : interfaceTrees) {
 721                 iface = clearTypeParams(iface);
 722                 Type it = attr.attribBase(iface, baseEnv, false, true, true);
 723                 if (it.hasTag(CLASS)) {
 724                     if (isPrimitiveClass && it.tsym == syms.cloneableType.tsym) {
 725                         log.error(tree, Errors.PrimitiveClassMustNotImplementCloneable(ct));
 726                     }
 727                     interfaces.append(it);
 728                     if (all_interfaces != null) all_interfaces.append(it);
 729                 } else {
 730                     if (all_interfaces == null)
 731                         all_interfaces = new ListBuffer<Type>().appendList(interfaces);
 732                     all_interfaces.append(modelMissingTypes(baseEnv, it, iface, true));
 733                 }
 734             }
 735 
 736             // Determine permits.
 737             ListBuffer<Symbol> permittedSubtypeSymbols = new ListBuffer<>();
 738             List<JCExpression> permittedTrees = tree.permitting;
 739             for (JCExpression permitted : permittedTrees) {
 740                 Type pt = attr.attribBase(permitted, baseEnv, false, false, false);
 741                 permittedSubtypeSymbols.append(pt.tsym);
 742             }
 743 
 744             if ((sym.flags_field & ANNOTATION) != 0) {
 745                 ct.interfaces_field = List.of(syms.annotationType);
 746                 ct.all_interfaces_field = ct.interfaces_field;
 747             }  else {
 748                 ct.interfaces_field = interfaces.toList();
 749                 ct.all_interfaces_field = (all_interfaces == null)
 750                         ? ct.interfaces_field : all_interfaces.toList();
 751             }
 752             /* it could be that there are already some symbols in the permitted list, for the case
 753              * where there are subtypes in the same compilation unit but the permits list is empty
 754              * so don't overwrite the permitted list if it is not empty
 755              */
 756             if (!permittedSubtypeSymbols.isEmpty()) {
 757                 sym.permitted = permittedSubtypeSymbols.toList();
 758             }
 759             sym.isPermittedExplicit = !permittedSubtypeSymbols.isEmpty();
 760         }
 761             //where:
 762             protected JCExpression clearTypeParams(JCExpression superType) {
 763                 return superType;
 764             }
 765     }
 766 
 767     private final class HierarchyPhase extends AbstractHeaderPhase implements Completer {
 768 
 769         public HierarchyPhase() {
 770             super(CompletionCause.HIERARCHY_PHASE, new PermitsPhase());
 771         }
 772 
 773         @Override
 774         protected void doCompleteEnvs(List<Env<AttrContext>> envs) {
 775             //The ClassSymbols in the envs list may not be in the dependency order.
 776             //To get proper results, for every class or interface C, the supertypes of
 777             //C must be processed by the HierarchyPhase phase before C.
 778             //To achieve that, the HierarchyPhase is registered as the Completer for
 779             //all the classes first, and then all the classes are completed.
 780             for (Env<AttrContext> env : envs) {
 781                 env.enclClass.sym.completer = this;
 782             }
 783             for (Env<AttrContext> env : envs) {
 784                 env.enclClass.sym.complete();
 785             }
 786         }
 787 
 788         @Override
 789         protected void runPhase(Env<AttrContext> env) {
 790             JCClassDecl tree = env.enclClass;
 791             ClassSymbol sym = tree.sym;
 792             ClassType ct = (ClassType)sym.type;
 793 
 794             Env<AttrContext> baseEnv = baseEnv(tree, env);
 795 
 796             attribSuperTypes(env, baseEnv);
 797 
 798             if (sym.fullname == names.java_lang_Object) {
 799                 if (tree.extending != null) {
 800                     chk.checkNonCyclic(tree.extending.pos(),
 801                                        ct.supertype_field);
 802                     ct.supertype_field = Type.noType;
 803                 }
 804                 else if (tree.implementing.nonEmpty()) {
 805                     chk.checkNonCyclic(tree.implementing.head.pos(),
 806                                        ct.interfaces_field.head);
 807                     ct.interfaces_field = List.nil();
 808                 }
 809             }
 810 
 811             markDeprecated(sym, tree.mods.annotations, baseEnv);
 812 
 813             chk.checkNonCyclicDecl(tree);
 814         }
 815             //where:
 816             @Override
 817             protected JCExpression clearTypeParams(JCExpression superType) {
 818                 switch (superType.getTag()) {
 819                     case TYPEAPPLY:
 820                         return ((JCTypeApply) superType).clazz;
 821                 }
 822 
 823                 return superType;
 824             }
 825 
 826         @Override
 827         public void complete(Symbol sym) throws CompletionFailure {
 828             Assert.check((topLevelPhase instanceof ImportsPhase) ||
 829                          (topLevelPhase == this));
 830 
 831             if (topLevelPhase != this) {
 832                 //only do the processing based on dependencies in the HierarchyPhase:
 833                 sym.completer = this;
 834                 return ;
 835             }
 836 
 837             Env<AttrContext> env = typeEnvs.get((ClassSymbol) sym);
 838 
 839             super.doCompleteEnvs(List.of(env));
 840         }
 841 
 842     }
 843 
 844     private final class PermitsPhase extends AbstractHeaderPhase {
 845 
 846         public PermitsPhase() {
 847             super(CompletionCause.HIERARCHY_PHASE, new HeaderPhase());
 848         }
 849 
 850         @Override
 851         protected void runPhase(Env<AttrContext> env) {
 852             JCClassDecl tree = env.enclClass;
 853             if (!tree.sym.isAnonymous() || tree.sym.isEnum()) {
 854                 for (Type supertype : types.directSupertypes(tree.sym.type)) {
 855                     if (supertype.tsym.kind == TYP) {
 856                         ClassSymbol supClass = (ClassSymbol) supertype.tsym;
 857                         Env<AttrContext> supClassEnv = enter.getEnv(supClass);
 858                         if (supClass.isSealed() &&
 859                             !supClass.isPermittedExplicit &&
 860                             supClassEnv != null &&
 861                             supClassEnv.toplevel == env.toplevel) {
 862                             supClass.permitted = supClass.permitted.append(tree.sym);
 863                         }
 864                     }
 865                 }
 866             }
 867         }
 868 
 869     }
 870 
 871     private final class HeaderPhase extends AbstractHeaderPhase {
 872 
 873         public HeaderPhase() {
 874             super(CompletionCause.HEADER_PHASE, new RecordPhase());
 875         }
 876 
 877         @Override
 878         protected void runPhase(Env<AttrContext> env) {
 879             JCClassDecl tree = env.enclClass;
 880             ClassSymbol sym = tree.sym;
 881             ClassType ct = (ClassType)sym.type;
 882 
 883             // create an environment for evaluating the base clauses
 884             Env<AttrContext> baseEnv = baseEnv(tree, env);
 885 
 886             if (tree.extending != null)
 887                 annotate.queueScanTreeAndTypeAnnotate(tree.extending, baseEnv, sym, tree.pos());
 888             for (JCExpression impl : tree.implementing)
 889                 annotate.queueScanTreeAndTypeAnnotate(impl, baseEnv, sym, tree.pos());
 890             annotate.flush();
 891 
 892             attribSuperTypes(env, baseEnv);
 893 
 894             Set<Type> interfaceSet = new HashSet<>();
 895 
 896             for (JCExpression iface : tree.implementing) {
 897                 Type it = iface.type;
 898                 if (it.hasTag(CLASS))
 899                     chk.checkNotRepeated(iface.pos(), types.erasure(it), interfaceSet);
 900             }
 901 
 902             annotate.annotateLater(tree.mods.annotations, baseEnv,
 903                         sym, tree.pos());
 904             attr.attribTypeVariables(tree.typarams, baseEnv, false);
 905 
 906             for (JCTypeParameter tp : tree.typarams)
 907                 annotate.queueScanTreeAndTypeAnnotate(tp, baseEnv, sym, tree.pos());
 908 
 909             // check that no package exists with same fully qualified name,
 910             // but admit classes in the unnamed package which have the same
 911             // name as a top-level package.
 912             if (checkClash &&
 913                 sym.owner.kind == PCK && sym.owner != env.toplevel.modle.unnamedPackage &&
 914                 syms.packageExists(env.toplevel.modle, sym.fullname)) {
 915                 log.error(tree.pos, Errors.ClashWithPkgOfSameName(Kinds.kindName(sym),sym));
 916             }
 917             if (sym.owner.kind == PCK && (sym.flags_field & PUBLIC) == 0 &&
 918                 !env.toplevel.sourcefile.isNameCompatible(sym.name.toString(),JavaFileObject.Kind.SOURCE)) {
 919                 sym.flags_field |= AUXILIARY;
 920             }
 921         }
 922     }
 923 
 924     private abstract class AbstractMembersPhase extends Phase {
 925 
 926         public AbstractMembersPhase(CompletionCause completionCause, Phase next) {
 927             super(completionCause, next);
 928         }
 929 
 930         private boolean completing;
 931         private List<Env<AttrContext>> todo = List.nil();
 932 
 933         @Override
 934         protected void doCompleteEnvs(List<Env<AttrContext>> envs) {
 935             todo = todo.prependList(envs);
 936             if (completing) {
 937                 return ; //the top-level invocation will handle all envs
 938             }
 939             boolean prevCompleting = completing;
 940             completing = true;
 941             try {
 942                 while (todo.nonEmpty()) {
 943                     Env<AttrContext> head = todo.head;
 944                     todo = todo.tail;
 945                     super.doCompleteEnvs(List.of(head));
 946                 }
 947             } finally {
 948                 completing = prevCompleting;
 949             }
 950         }
 951 
 952         void enterThisAndSuper(ClassSymbol sym, Env<AttrContext> env) {
 953             ClassType ct = (ClassType)sym.type;
 954             // enter symbols for 'this' into current scope.
 955             VarSymbol thisSym =
 956                     new VarSymbol(FINAL | HASINIT, names._this, sym.type, sym);
 957             thisSym.pos = Position.FIRSTPOS;
 958             env.info.scope.enter(thisSym);
 959             // if this is a class, enter symbol for 'super' into current scope.
 960             if ((sym.flags_field & INTERFACE) == 0 &&
 961                     ct.supertype_field.hasTag(CLASS)) {
 962                 VarSymbol superSym =
 963                         new VarSymbol(FINAL | HASINIT, names._super,
 964                                 ct.supertype_field, sym);
 965                 superSym.pos = Position.FIRSTPOS;
 966                 env.info.scope.enter(superSym);
 967             }
 968         }
 969     }
 970 
 971     private final class RecordPhase extends AbstractMembersPhase {
 972 
 973         public RecordPhase() {
 974             super(CompletionCause.RECORD_PHASE, new MembersPhase());
 975         }
 976 
 977         @Override
 978         protected void runPhase(Env<AttrContext> env) {
 979             JCClassDecl tree = env.enclClass;
 980             ClassSymbol sym = tree.sym;
 981             if ((sym.flags_field & RECORD) != 0) {
 982                 List<JCVariableDecl> fields = TreeInfo.recordFields(tree);
 983                 memberEnter.memberEnter(fields, env);
 984                 for (JCVariableDecl field : fields) {
 985                     sym.getRecordComponent(field, true,
 986                             field.mods.annotations.isEmpty() ?
 987                                     List.nil() :
 988                                     new TreeCopier<JCTree>(make.at(field.pos)).copy(field.mods.annotations));
 989                 }
 990 
 991                 enterThisAndSuper(sym, env);
 992 
 993                 // lets enter all constructors
 994                 for (JCTree def : tree.defs) {
 995                     if (TreeInfo.isConstructor(def)) {
 996                         memberEnter.memberEnter(def, env);
 997                     }
 998                 }
 999             }
1000         }
1001     }
1002 
1003     /** Enter member fields and methods of a class
1004      */
1005     private final class MembersPhase extends AbstractMembersPhase {
1006 
1007         public MembersPhase() {
1008             super(CompletionCause.MEMBERS_PHASE, null);
1009         }
1010 
1011         @Override
1012         protected void runPhase(Env<AttrContext> env) {
1013             JCClassDecl tree = env.enclClass;
1014             ClassSymbol sym = tree.sym;
1015             ClassType ct = (ClassType)sym.type;
1016 
1017             JCTree defaultConstructor = null;
1018 
1019             // Add default constructor if needed.
1020             DefaultConstructorHelper helper = getDefaultConstructorHelper(env);
1021             if (helper != null) {
1022                 chk.checkDefaultConstructor(sym, tree.pos());
1023                 defaultConstructor = defaultConstructor(make.at(tree.pos), helper);
1024                 tree.defs = tree.defs.prepend(defaultConstructor);
1025             }
1026             if (!sym.isRecord()) {
1027                 enterThisAndSuper(sym, env);
1028             }
1029 
1030             if (!tree.typarams.isEmpty()) {
1031                 for (JCTypeParameter tvar : tree.typarams) {
1032                     chk.checkNonCyclic(tvar, (TypeVar)tvar.type);
1033                 }
1034             }
1035 
1036             finishClass(tree, defaultConstructor, env);
1037 
1038             if (allowTypeAnnos) {
1039                 typeAnnotations.organizeTypeAnnotationsSignatures(env, (JCClassDecl)env.tree);
1040                 typeAnnotations.validateTypeAnnotationsSignatures(env, (JCClassDecl)env.tree);
1041             }
1042         }
1043 
1044         DefaultConstructorHelper getDefaultConstructorHelper(Env<AttrContext> env) {
1045             JCClassDecl tree = env.enclClass;
1046             ClassSymbol sym = tree.sym;
1047             DefaultConstructorHelper helper = null;
1048             boolean isClassWithoutInit = (sym.flags() & INTERFACE) == 0 && !TreeInfo.hasConstructors(tree.defs);
1049             boolean isRecord = sym.isRecord();
1050             if (isClassWithoutInit && !isRecord) {
1051                 helper = new BasicConstructorHelper(sym);
1052                 if (sym.name.isEmpty()) {
1053                     JCNewClass nc = (JCNewClass)env.next.tree;
1054                     if (nc.constructor != null) {
1055                         if (nc.constructor.kind != ERR) {
1056                             helper = new AnonClassConstructorHelper(sym, (MethodSymbol)nc.constructor, nc.encl);
1057                         } else {
1058                             helper = null;
1059                         }
1060                     }
1061                 }
1062             }
1063             if (isRecord) {
1064                 JCMethodDecl canonicalInit = null;
1065                 if (isClassWithoutInit || (canonicalInit = getCanonicalConstructorDecl(env.enclClass)) == null) {
1066                     helper = new RecordConstructorHelper(sym, TreeInfo.recordFields(tree));
1067                 }
1068                 if (canonicalInit != null) {
1069                     canonicalInit.sym.flags_field |= Flags.RECORD;
1070                 }
1071             }
1072             return helper;
1073         }
1074 
1075         /** Enter members for a class.
1076          */
1077         void finishClass(JCClassDecl tree, JCTree defaultConstructor, Env<AttrContext> env) {
1078             if ((tree.mods.flags & Flags.ENUM) != 0 &&
1079                 !tree.sym.type.hasTag(ERROR) &&
1080                 (types.supertype(tree.sym.type).tsym.flags() & Flags.ENUM) == 0) {
1081                 addEnumMembers(tree, env);
1082             }
1083             boolean isRecord = (tree.sym.flags_field & RECORD) != 0;
1084             List<JCTree> alreadyEntered = null;
1085             if (isRecord) {
1086                 alreadyEntered = List.convert(JCTree.class, TreeInfo.recordFields(tree));
1087                 alreadyEntered = alreadyEntered.prependList(tree.defs.stream()
1088                         .filter(t -> TreeInfo.isConstructor(t) && t != defaultConstructor).collect(List.collector()));
1089             }
1090             List<JCTree> defsToEnter = isRecord ?
1091                     tree.defs.diff(alreadyEntered) : tree.defs;
1092             memberEnter.memberEnter(defsToEnter, env);
1093             if (isRecord) {
1094                 addRecordMembersIfNeeded(tree, env);
1095             }
1096             if (tree.sym.isAnnotationType()) {
1097                 Assert.check(tree.sym.isCompleted());
1098                 tree.sym.setAnnotationTypeMetadata(new AnnotationTypeMetadata(tree.sym, annotate.annotationTypeSourceCompleter()));
1099             }
1100         }
1101 
1102         private void addAccessor(JCVariableDecl tree, Env<AttrContext> env) {
1103             MethodSymbol implSym = lookupMethod(env.enclClass.sym, tree.sym.name, List.nil());
1104             RecordComponent rec = ((ClassSymbol) tree.sym.owner).getRecordComponent(tree.sym);
1105             if (implSym == null || (implSym.flags_field & GENERATED_MEMBER) != 0) {
1106                 /* here we are pushing the annotations present in the corresponding field down to the accessor
1107                  * it could be that some of those annotations are not applicable to the accessor, they will be striped
1108                  * away later at Check::validateAnnotation
1109                  */
1110                 TreeCopier<JCTree> tc = new TreeCopier<JCTree>(make.at(tree.pos));
1111                 List<JCAnnotation> originalAnnos = rec.getOriginalAnnos().isEmpty() ?
1112                         rec.getOriginalAnnos() :
1113                         tc.copy(rec.getOriginalAnnos());
1114                 JCVariableDecl recordField = TreeInfo.recordFields((JCClassDecl) env.tree).stream().filter(rf -> rf.name == tree.name).findAny().get();
1115                 JCMethodDecl getter = make.at(tree.pos).
1116                         MethodDef(
1117                                 make.Modifiers(PUBLIC | Flags.GENERATED_MEMBER, originalAnnos),
1118                           tree.sym.name,
1119                           /* we need to special case for the case when the user declared the type as an ident
1120                            * if we don't do that then we can have issues if type annotations are applied to the
1121                            * return type: javac issues an error if a type annotation is applied to java.lang.String
1122                            * but applying a type annotation to String is kosher
1123                            */
1124                           tc.copy(recordField.vartype),
1125                           List.nil(),
1126                           List.nil(),
1127                           List.nil(), // thrown
1128                           null,
1129                           null);
1130                 memberEnter.memberEnter(getter, env);
1131                 rec.accessor = getter.sym;
1132                 rec.accessorMeth = getter;
1133             } else if (implSym != null) {
1134                 rec.accessor = implSym;
1135             }
1136         }
1137 
1138         /** Add the implicit members for an enum type
1139          *  to the symbol table.
1140          */
1141         private void addEnumMembers(JCClassDecl tree, Env<AttrContext> env) {
1142             JCExpression valuesType = make.Type(new ArrayType(tree.sym.type, syms.arrayClass));
1143 
1144             JCMethodDecl values = make.
1145                 MethodDef(make.Modifiers(Flags.PUBLIC|Flags.STATIC),
1146                           names.values,
1147                           valuesType,
1148                           List.nil(),
1149                           List.nil(),
1150                           List.nil(),
1151                           null,
1152                           null);
1153             memberEnter.memberEnter(values, env);
1154 
1155             JCMethodDecl valueOf = make.
1156                 MethodDef(make.Modifiers(Flags.PUBLIC|Flags.STATIC),
1157                           names.valueOf,
1158                           make.Type(tree.sym.type),
1159                           List.nil(),
1160                           List.of(make.VarDef(make.Modifiers(Flags.PARAMETER |
1161                                                              Flags.MANDATED),
1162                                                 names.fromString("name"),
1163                                                 make.Type(syms.stringType), null)),
1164                           List.nil(),
1165                           null,
1166                           null);
1167             memberEnter.memberEnter(valueOf, env);
1168         }
1169 
1170         JCMethodDecl getCanonicalConstructorDecl(JCClassDecl tree) {
1171             // let's check if there is a constructor with exactly the same arguments as the record components
1172             List<Type> recordComponentErasedTypes = types.erasure(TreeInfo.recordFields(tree).map(vd -> vd.sym.type));
1173             JCMethodDecl canonicalDecl = null;
1174             for (JCTree def : tree.defs) {
1175                 if (TreeInfo.isConstructor(def)) {
1176                     JCMethodDecl mdecl = (JCMethodDecl)def;
1177                     if (types.isSameTypes(types.erasure(mdecl.params.stream().map(v -> v.sym.type).collect(List.collector())), recordComponentErasedTypes)) {
1178                         canonicalDecl = mdecl;
1179                         break;
1180                     }
1181                 }
1182             }
1183             return canonicalDecl;
1184         }
1185 
1186         /** Add the implicit members for a record
1187          *  to the symbol table.
1188          */
1189         private void addRecordMembersIfNeeded(JCClassDecl tree, Env<AttrContext> env) {
1190             if (lookupMethod(tree.sym, names.toString, List.nil()) == null) {
1191                 JCMethodDecl toString = make.
1192                     MethodDef(make.Modifiers(Flags.PUBLIC | Flags.RECORD | Flags.FINAL | Flags.GENERATED_MEMBER),
1193                               names.toString,
1194                               make.Type(syms.stringType),
1195                               List.nil(),
1196                               List.nil(),
1197                               List.nil(),
1198                               null,
1199                               null);
1200                 memberEnter.memberEnter(toString, env);
1201             }
1202 
1203             if (lookupMethod(tree.sym, names.hashCode, List.nil()) == null) {
1204                 JCMethodDecl hashCode = make.
1205                     MethodDef(make.Modifiers(Flags.PUBLIC | Flags.RECORD | Flags.FINAL | Flags.GENERATED_MEMBER),
1206                               names.hashCode,
1207                               make.Type(syms.intType),
1208                               List.nil(),
1209                               List.nil(),
1210                               List.nil(),
1211                               null,
1212                               null);
1213                 memberEnter.memberEnter(hashCode, env);
1214             }
1215 
1216             if (lookupMethod(tree.sym, names.equals, List.of(syms.objectType)) == null) {
1217                 JCMethodDecl equals = make.
1218                     MethodDef(make.Modifiers(Flags.PUBLIC | Flags.RECORD | Flags.FINAL | Flags.GENERATED_MEMBER),
1219                               names.equals,
1220                               make.Type(syms.booleanType),
1221                               List.nil(),
1222                               List.of(make.VarDef(make.Modifiers(Flags.PARAMETER),
1223                                                 names.fromString("o"),
1224                                                 make.Type(syms.objectType), null)),
1225                               List.nil(),
1226                               null,
1227                               null);
1228                 memberEnter.memberEnter(equals, env);
1229             }
1230 
1231             // fields can't be varargs, lets remove the flag
1232             List<JCVariableDecl> recordFields = TreeInfo.recordFields(tree);
1233             for (JCVariableDecl field: recordFields) {
1234                 field.mods.flags &= ~Flags.VARARGS;
1235                 field.sym.flags_field &= ~Flags.VARARGS;
1236             }
1237             // now lets add the accessors
1238             recordFields.stream()
1239                     .filter(vd -> (lookupMethod(syms.objectType.tsym, vd.name, List.nil()) == null))
1240                     .forEach(vd -> addAccessor(vd, env));
1241         }
1242     }
1243 
1244     private MethodSymbol lookupMethod(TypeSymbol tsym, Name name, List<Type> argtypes) {
1245         for (Symbol s : tsym.members().getSymbolsByName(name, s -> s.kind == MTH)) {
1246             if (types.isSameTypes(s.type.getParameterTypes(), argtypes)) {
1247                 return (MethodSymbol) s;
1248             }
1249         }
1250         return null;
1251     }
1252 
1253 /* ***************************************************************************
1254  * tree building
1255  ****************************************************************************/
1256 
1257     interface DefaultConstructorHelper {
1258        Type constructorType();
1259        MethodSymbol constructorSymbol();
1260        Type enclosingType();
1261        TypeSymbol owner();
1262        List<Name> superArgs();
1263        default JCMethodDecl finalAdjustment(JCMethodDecl md) { return md; }
1264     }
1265 
1266     class BasicConstructorHelper implements DefaultConstructorHelper {
1267 
1268         TypeSymbol owner;
1269         Type constructorType;
1270         MethodSymbol constructorSymbol;
1271 
1272         BasicConstructorHelper(TypeSymbol owner) {
1273             this.owner = owner;
1274         }
1275 
1276         @Override
1277         public Type constructorType() {
1278             if (constructorType == null) {
1279                 constructorType = new MethodType(List.nil(), syms.voidType, List.nil(), syms.methodClass);
1280             }
1281             return constructorType;
1282         }
1283 
1284         @Override
1285         public MethodSymbol constructorSymbol() {
1286             if (constructorSymbol == null) {
1287                 long flags;
1288                 if ((owner().flags() & ENUM) != 0 &&
1289                     (types.supertype(owner().type).tsym == syms.enumSym)) {
1290                     // constructors of true enums are private
1291                     flags = PRIVATE | GENERATEDCONSTR;
1292                 } else {
1293                     flags = (owner().flags() & AccessFlags) | GENERATEDCONSTR;
1294                 }
1295                 constructorSymbol = new MethodSymbol(flags, names.init,
1296                     constructorType(), owner());
1297             }
1298             return constructorSymbol;
1299         }
1300 
1301         @Override
1302         public Type enclosingType() {
1303             return Type.noType;
1304     }
1305 
1306         @Override
1307         public TypeSymbol owner() {
1308             return owner;
1309         }
1310 
1311         @Override
1312         public List<Name> superArgs() {
1313             return List.nil();
1314             }
1315     }
1316 
1317     class AnonClassConstructorHelper extends BasicConstructorHelper {
1318 
1319         MethodSymbol constr;
1320         Type encl;
1321         boolean based = false;
1322 
1323         AnonClassConstructorHelper(TypeSymbol owner, MethodSymbol constr, JCExpression encl) {
1324             super(owner);
1325             this.constr = constr;
1326             this.encl = encl != null ? encl.type : Type.noType;
1327         }
1328 
1329         @Override
1330         public Type constructorType() {
1331             if (constructorType == null) {
1332                 Type ctype = types.memberType(owner.type, constr);
1333                 if (!enclosingType().hasTag(NONE)) {
1334                     ctype = types.createMethodTypeWithParameters(ctype, ctype.getParameterTypes().prepend(enclosingType()));
1335                     based = true;
1336                 }
1337                 constructorType = ctype;
1338             }
1339             return constructorType;
1340         }
1341 
1342         @Override
1343         public MethodSymbol constructorSymbol() {
1344             MethodSymbol csym = super.constructorSymbol();
1345             csym.flags_field |= ANONCONSTR | (constr.flags() & VARARGS);
1346             csym.flags_field |= based ? ANONCONSTR_BASED : 0;
1347             ListBuffer<VarSymbol> params = new ListBuffer<>();
1348             List<Type> argtypes = constructorType().getParameterTypes();
1349             if (!enclosingType().hasTag(NONE)) {
1350                 argtypes = argtypes.tail;
1351                 params = params.prepend(new VarSymbol(PARAMETER, make.paramName(0), enclosingType(), csym));
1352             }
1353             if (constr.params != null) {
1354                 for (VarSymbol p : constr.params) {
1355                     params.add(new VarSymbol(PARAMETER | p.flags(), p.name, argtypes.head, csym));
1356                     argtypes = argtypes.tail;
1357                 }
1358             }
1359             csym.params = params.toList();
1360             return csym;
1361         }
1362 
1363         @Override
1364         public Type enclosingType() {
1365             return encl;
1366         }
1367 
1368         @Override
1369         public List<Name> superArgs() {
1370             List<JCVariableDecl> params = make.Params(constructorType().getParameterTypes(), constructorSymbol());
1371             if (!enclosingType().hasTag(NONE)) {
1372                 params = params.tail;
1373             }
1374             return params.map(vd -> vd.name);
1375         }
1376     }
1377 
1378     class RecordConstructorHelper extends BasicConstructorHelper {
1379         boolean lastIsVarargs;
1380         List<JCVariableDecl> recordFieldDecls;
1381 
1382         RecordConstructorHelper(ClassSymbol owner, List<JCVariableDecl> recordFieldDecls) {
1383             super(owner);
1384             this.recordFieldDecls = recordFieldDecls;
1385             this.lastIsVarargs = owner.getRecordComponents().stream().anyMatch(rc -> rc.isVarargs());
1386         }
1387 
1388         @Override
1389         public Type constructorType() {
1390             if (constructorType == null) {
1391                 ListBuffer<Type> argtypes = new ListBuffer<>();
1392                 JCVariableDecl lastField = recordFieldDecls.last();
1393                 for (JCVariableDecl field : recordFieldDecls) {
1394                     argtypes.add(field == lastField && lastIsVarargs ? types.elemtype(field.sym.type) : field.sym.type);
1395                 }
1396 
1397                 constructorType = new MethodType(argtypes.toList(), syms.voidType, List.nil(), syms.methodClass);
1398             }
1399             return constructorType;
1400         }
1401 
1402         @Override
1403         public MethodSymbol constructorSymbol() {
1404             MethodSymbol csym = super.constructorSymbol();
1405             /* if we have to generate a default constructor for records we will treat it as the compact one
1406              * to trigger field initialization later on
1407              */
1408             csym.flags_field |= Flags.COMPACT_RECORD_CONSTRUCTOR | GENERATEDCONSTR;
1409             ListBuffer<VarSymbol> params = new ListBuffer<>();
1410             JCVariableDecl lastField = recordFieldDecls.last();
1411             for (JCVariableDecl field : recordFieldDecls) {
1412                 params.add(new VarSymbol(
1413                         GENERATED_MEMBER | PARAMETER | RECORD | (field == lastField && lastIsVarargs ? Flags.VARARGS : 0),
1414                         field.name, field.sym.type, csym));
1415             }
1416             csym.params = params.toList();
1417             csym.flags_field |= RECORD;
1418             return csym;
1419         }
1420 
1421         @Override
1422         public JCMethodDecl finalAdjustment(JCMethodDecl md) {
1423             List<JCVariableDecl> tmpRecordFieldDecls = recordFieldDecls;
1424             for (JCVariableDecl arg : md.params) {
1425                 /* at this point we are passing all the annotations in the field to the corresponding
1426                  * parameter in the constructor.
1427                  */
1428                 RecordComponent rc = ((ClassSymbol) owner).getRecordComponent(arg.sym);
1429                 TreeCopier<JCTree> tc = new TreeCopier<JCTree>(make.at(arg.pos));
1430                 arg.mods.annotations = rc.getOriginalAnnos().isEmpty() ?
1431                         List.nil() :
1432                         tc.copy(rc.getOriginalAnnos());
1433                 arg.vartype = tc.copy(tmpRecordFieldDecls.head.vartype);
1434                 tmpRecordFieldDecls = tmpRecordFieldDecls.tail;
1435             }
1436             return md;
1437         }
1438     }
1439 
1440     JCTree defaultConstructor(TreeMaker make, DefaultConstructorHelper helper) {
1441         Type initType = helper.constructorType();
1442         MethodSymbol initSym = helper.constructorSymbol();
1443         ListBuffer<JCStatement> stats = new ListBuffer<>();
1444         if (helper.owner().type != syms.objectType) {
1445             JCExpression meth;
1446             if (!helper.enclosingType().hasTag(NONE)) {
1447                 meth = make.Select(make.Ident(initSym.params.head), names._super);
1448             } else {
1449                 meth = make.Ident(names._super);
1450             }
1451             List<JCExpression> typeargs = initType.getTypeArguments().nonEmpty() ?
1452                     make.Types(initType.getTypeArguments()) : null;
1453             JCStatement superCall = make.Exec(make.Apply(typeargs, meth, helper.superArgs().map(make::Ident)));
1454             stats.add(superCall);
1455         }
1456         JCMethodDecl result = make.MethodDef(initSym, make.Block(0, stats.toList()));
1457         return helper.finalAdjustment(result);
1458     }
1459 
1460     /**
1461      * Mark sym deprecated if annotations contain @Deprecated annotation.
1462      */
1463     public void markDeprecated(Symbol sym, List<JCAnnotation> annotations, Env<AttrContext> env) {
1464         // In general, we cannot fully process annotations yet,  but we
1465         // can attribute the annotation types and then check to see if the
1466         // @Deprecated annotation is present.
1467         attr.attribAnnotationTypes(annotations, env);
1468         handleDeprecatedAnnotations(annotations, sym);
1469     }
1470 
1471     /**
1472      * If a list of annotations contains a reference to java.lang.Deprecated,
1473      * set the DEPRECATED flag.
1474      * If the annotation is marked forRemoval=true, also set DEPRECATED_REMOVAL.
1475      **/
1476     private void handleDeprecatedAnnotations(List<JCAnnotation> annotations, Symbol sym) {
1477         for (List<JCAnnotation> al = annotations; !al.isEmpty(); al = al.tail) {
1478             JCAnnotation a = al.head;
1479             if (a.annotationType.type == syms.deprecatedType) {
1480                 sym.flags_field |= (Flags.DEPRECATED | Flags.DEPRECATED_ANNOTATION);
1481                 setFlagIfAttributeTrue(a, sym, names.forRemoval, DEPRECATED_REMOVAL);
1482             } else if (a.annotationType.type == syms.previewFeatureType) {
1483                 sym.flags_field |= Flags.PREVIEW_API;
1484                 setFlagIfAttributeTrue(a, sym, names.reflective, Flags.PREVIEW_REFLECTIVE);
1485             }
1486         }
1487     }
1488     //where:
1489         private void setFlagIfAttributeTrue(JCAnnotation a, Symbol sym, Name attribute, long flag) {
1490             a.args.stream()
1491                     .filter(e -> e.hasTag(ASSIGN))
1492                     .map(e -> (JCAssign) e)
1493                     .filter(assign -> TreeInfo.name(assign.lhs) == attribute)
1494                     .findFirst()
1495                     .ifPresent(assign -> {
1496                         JCExpression rhs = TreeInfo.skipParens(assign.rhs);
1497                         if (rhs.hasTag(LITERAL)
1498                                 && Boolean.TRUE.equals(((JCLiteral) rhs).getValue())) {
1499                             sym.flags_field |= flag;
1500                         }
1501                     });
1502         }
1503 }