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