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