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