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