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