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