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