TypeEnter.java revision 3878:cfa0d9053907
1/* 2 * Copyright (c) 2003, 2017, 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 26package com.sun.tools.javac.comp; 27 28import java.util.HashSet; 29import java.util.Set; 30import java.util.function.BiConsumer; 31 32import javax.tools.JavaFileObject; 33 34import com.sun.tools.javac.code.*; 35import com.sun.tools.javac.code.Lint.LintCategory; 36import com.sun.tools.javac.code.Scope.ImportFilter; 37import com.sun.tools.javac.code.Scope.NamedImportScope; 38import com.sun.tools.javac.code.Scope.StarImportScope; 39import com.sun.tools.javac.code.Scope.WriteableScope; 40import com.sun.tools.javac.comp.Annotate.AnnotationTypeMetadata; 41import com.sun.tools.javac.tree.*; 42import com.sun.tools.javac.util.*; 43import com.sun.tools.javac.util.DefinedBy.Api; 44 45import com.sun.tools.javac.code.Symbol.*; 46import com.sun.tools.javac.code.Type.*; 47import com.sun.tools.javac.tree.JCTree.*; 48 49import static com.sun.tools.javac.code.Flags.*; 50import static com.sun.tools.javac.code.Flags.ANNOTATION; 51import static com.sun.tools.javac.code.Scope.LookupKind.NON_RECURSIVE; 52import static com.sun.tools.javac.code.Kinds.Kind.*; 53import static com.sun.tools.javac.code.TypeTag.CLASS; 54import static com.sun.tools.javac.code.TypeTag.ERROR; 55import static com.sun.tools.javac.tree.JCTree.Tag.*; 56 57import com.sun.tools.javac.util.Dependencies.CompletionCause; 58import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag; 59import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; 60 61/** This is the second phase of Enter, in which classes are completed 62 * by resolving their headers and entering their members in the into 63 * the class scope. See Enter for an overall overview. 64 * 65 * This class uses internal phases to process the classes. When a phase 66 * processes classes, the lower phases are not invoked until all classes 67 * pass through the current phase. Note that it is possible that upper phases 68 * are run due to recursive completion. The internal phases are: 69 * - ImportPhase: shallow pass through imports, adds information about imports 70 * the NamedImportScope and StarImportScope, but avoids queries 71 * about class hierarchy. 72 * - HierarchyPhase: resolves the supertypes of the given class. Does not handle 73 * type parameters of the class or type argument of the supertypes. 74 * - HeaderPhase: finishes analysis of the header of the given class by resolving 75 * type parameters, attributing supertypes including type arguments 76 * and scheduling full annotation attribution. This phase also adds 77 * a synthetic default constructor if needed and synthetic "this" field. 78 * - MembersPhase: resolves headers for fields, methods and constructors in the given class. 79 * Also generates synthetic enum members. 80 * 81 * <p><b>This is NOT part of any supported API. 82 * If you write code that depends on this, you do so at your own risk. 83 * This code and its internal interfaces are subject to change or 84 * deletion without notice.</b> 85 */ 86public class TypeEnter implements Completer { 87 protected static final Context.Key<TypeEnter> typeEnterKey = new Context.Key<>(); 88 89 /** A switch to determine whether we check for package/class conflicts 90 */ 91 final static boolean checkClash = true; 92 93 private final Names names; 94 private final Enter enter; 95 private final MemberEnter memberEnter; 96 private final Log log; 97 private final Check chk; 98 private final Attr attr; 99 private final Symtab syms; 100 private final TreeMaker make; 101 private final Todo todo; 102 private final Annotate annotate; 103 private final TypeAnnotations typeAnnotations; 104 private final Types types; 105 private final JCDiagnostic.Factory diags; 106 private final DeferredLintHandler deferredLintHandler; 107 private final Lint lint; 108 private final TypeEnvs typeEnvs; 109 private final Dependencies dependencies; 110 111 public static TypeEnter instance(Context context) { 112 TypeEnter instance = context.get(typeEnterKey); 113 if (instance == null) 114 instance = new TypeEnter(context); 115 return instance; 116 } 117 118 protected TypeEnter(Context context) { 119 context.put(typeEnterKey, this); 120 names = Names.instance(context); 121 enter = Enter.instance(context); 122 memberEnter = MemberEnter.instance(context); 123 log = Log.instance(context); 124 chk = Check.instance(context); 125 attr = Attr.instance(context); 126 syms = Symtab.instance(context); 127 make = TreeMaker.instance(context); 128 todo = Todo.instance(context); 129 annotate = Annotate.instance(context); 130 typeAnnotations = TypeAnnotations.instance(context); 131 types = Types.instance(context); 132 diags = JCDiagnostic.Factory.instance(context); 133 deferredLintHandler = DeferredLintHandler.instance(context); 134 lint = Lint.instance(context); 135 typeEnvs = TypeEnvs.instance(context); 136 dependencies = Dependencies.instance(context); 137 Source source = Source.instance(context); 138 allowTypeAnnos = source.allowTypeAnnotations(); 139 allowDeprecationOnImport = source.allowDeprecationOnImport(); 140 } 141 142 /** Switch: support type annotations. 143 */ 144 boolean allowTypeAnnos; 145 146 /** 147 * Switch: should deprecation warnings be issued on import 148 */ 149 boolean allowDeprecationOnImport; 150 151 /** A flag to disable completion from time to time during member 152 * enter, as we only need to look up types. This avoids 153 * unnecessarily deep recursion. 154 */ 155 boolean completionEnabled = true; 156 157 /* Verify Imports: 158 */ 159 protected void ensureImportsChecked(List<JCCompilationUnit> trees) { 160 // if there remain any unimported toplevels (these must have 161 // no classes at all), process their import statements as well. 162 for (JCCompilationUnit tree : trees) { 163 if (!tree.starImportScope.isFilled()) { 164 Env<AttrContext> topEnv = enter.topLevelEnv(tree); 165 finishImports(tree, () -> { completeClass.resolveImports(tree, topEnv); }); 166 } 167 } 168 } 169 170/* ******************************************************************** 171 * Source completer 172 *********************************************************************/ 173 174 /** Complete entering a class. 175 * @param sym The symbol of the class to be completed. 176 */ 177 @Override 178 public void complete(Symbol sym) throws CompletionFailure { 179 // Suppress some (recursive) MemberEnter invocations 180 if (!completionEnabled) { 181 // Re-install same completer for next time around and return. 182 Assert.check((sym.flags() & Flags.COMPOUND) == 0); 183 sym.completer = this; 184 return; 185 } 186 187 try { 188 annotate.blockAnnotations(); 189 sym.flags_field |= UNATTRIBUTED; 190 191 List<Env<AttrContext>> queue; 192 193 dependencies.push((ClassSymbol) sym, CompletionCause.MEMBER_ENTER); 194 try { 195 queue = completeClass.completeEnvs(List.of(typeEnvs.get((ClassSymbol) sym))); 196 } finally { 197 dependencies.pop(); 198 } 199 200 if (!queue.isEmpty()) { 201 Set<JCCompilationUnit> seen = new HashSet<>(); 202 203 for (Env<AttrContext> env : queue) { 204 if (env.toplevel.defs.contains(env.enclClass) && seen.add(env.toplevel)) { 205 finishImports(env.toplevel, () -> {}); 206 } 207 } 208 } 209 } finally { 210 annotate.unblockAnnotations(); 211 } 212 } 213 214 void finishImports(JCCompilationUnit toplevel, Runnable resolve) { 215 JavaFileObject prev = log.useSource(toplevel.sourcefile); 216 try { 217 resolve.run(); 218 chk.checkImportsUnique(toplevel); 219 chk.checkImportsResolvable(toplevel); 220 chk.checkImportedPackagesObservable(toplevel); 221 toplevel.namedImportScope.finalizeScope(); 222 toplevel.starImportScope.finalizeScope(); 223 } finally { 224 log.useSource(prev); 225 } 226 } 227 228 abstract class Phase { 229 private final ListBuffer<Env<AttrContext>> queue = new ListBuffer<>(); 230 private final Phase next; 231 private final CompletionCause phaseName; 232 233 Phase(CompletionCause phaseName, Phase next) { 234 this.phaseName = phaseName; 235 this.next = next; 236 } 237 238 public final List<Env<AttrContext>> completeEnvs(List<Env<AttrContext>> envs) { 239 boolean firstToComplete = queue.isEmpty(); 240 241 Phase prevTopLevelPhase = topLevelPhase; 242 243 try { 244 topLevelPhase = this; 245 doCompleteEnvs(envs); 246 } finally { 247 topLevelPhase = prevTopLevelPhase; 248 } 249 250 if (firstToComplete) { 251 List<Env<AttrContext>> out = queue.toList(); 252 253 queue.clear(); 254 return next != null ? next.completeEnvs(out) : out; 255 } else { 256 return List.nil(); 257 } 258 } 259 260 protected void doCompleteEnvs(List<Env<AttrContext>> envs) { 261 for (Env<AttrContext> env : envs) { 262 JCClassDecl tree = (JCClassDecl)env.tree; 263 264 queue.add(env); 265 266 JavaFileObject prev = log.useSource(env.toplevel.sourcefile); 267 DiagnosticPosition prevLintPos = deferredLintHandler.setPos(tree.pos()); 268 try { 269 dependencies.push(env.enclClass.sym, phaseName); 270 runPhase(env); 271 } catch (CompletionFailure ex) { 272 chk.completionError(tree.pos(), ex); 273 } finally { 274 dependencies.pop(); 275 deferredLintHandler.setPos(prevLintPos); 276 log.useSource(prev); 277 } 278 } 279 } 280 281 protected abstract void runPhase(Env<AttrContext> env); 282 } 283 284 private final ImportsPhase completeClass = new ImportsPhase(); 285 private Phase topLevelPhase; 286 287 /**Analyze import clauses. 288 */ 289 private final class ImportsPhase extends Phase { 290 291 public ImportsPhase() { 292 super(CompletionCause.IMPORTS_PHASE, new HierarchyPhase()); 293 } 294 295 Env<AttrContext> env; 296 ImportFilter staticImportFilter; 297 ImportFilter typeImportFilter; 298 BiConsumer<JCImport, CompletionFailure> cfHandler = 299 (imp, cf) -> chk.completionError(imp.pos(), cf); 300 301 @Override 302 protected void runPhase(Env<AttrContext> env) { 303 JCClassDecl tree = env.enclClass; 304 ClassSymbol sym = tree.sym; 305 306 // If sym is a toplevel-class, make sure any import 307 // clauses in its source file have been seen. 308 if (sym.owner.kind == PCK) { 309 resolveImports(env.toplevel, env.enclosing(TOPLEVEL)); 310 todo.append(env); 311 } 312 313 if (sym.owner.kind == TYP) 314 sym.owner.complete(); 315 } 316 317 private void resolveImports(JCCompilationUnit tree, Env<AttrContext> env) { 318 if (tree.starImportScope.isFilled()) { 319 // we must have already processed this toplevel 320 return; 321 } 322 323 ImportFilter prevStaticImportFilter = staticImportFilter; 324 ImportFilter prevTypeImportFilter = typeImportFilter; 325 DiagnosticPosition prevLintPos = deferredLintHandler.immediate(); 326 Lint prevLint = chk.setLint(lint); 327 Env<AttrContext> prevEnv = this.env; 328 try { 329 this.env = env; 330 final PackageSymbol packge = env.toplevel.packge; 331 this.staticImportFilter = 332 (origin, sym) -> sym.isStatic() && 333 chk.importAccessible(sym, packge) && 334 sym.isMemberOf((TypeSymbol) origin.owner, types); 335 this.typeImportFilter = 336 (origin, sym) -> sym.kind == TYP && 337 chk.importAccessible(sym, packge); 338 339 // Import-on-demand java.lang. 340 PackageSymbol javaLang = syms.enterPackage(syms.java_base, names.java_lang); 341 if (javaLang.members().isEmpty() && !javaLang.exists()) 342 throw new FatalError(diags.fragment("fatal.err.no.java.lang")); 343 importAll(make.at(tree.pos()).Import(make.QualIdent(javaLang), false), javaLang, env); 344 345 JCModuleDecl decl = tree.getModuleDecl(); 346 347 // Process the package def and all import clauses. 348 if (tree.getPackage() != null && decl == null) 349 checkClassPackageClash(tree.getPackage()); 350 351 for (JCImport imp : tree.getImports()) { 352 doImport(imp); 353 } 354 355 if (decl != null) { 356 //check @Deprecated: 357 markDeprecated(decl.sym, decl.mods.annotations, env); 358 // process module annotations 359 annotate.annotateLater(decl.mods.annotations, env, env.toplevel.modle, null); 360 } 361 } finally { 362 this.env = prevEnv; 363 chk.setLint(prevLint); 364 deferredLintHandler.setPos(prevLintPos); 365 this.staticImportFilter = prevStaticImportFilter; 366 this.typeImportFilter = prevTypeImportFilter; 367 } 368 } 369 370 private void checkClassPackageClash(JCPackageDecl tree) { 371 // check that no class exists with same fully qualified name as 372 // toplevel package 373 if (checkClash && tree.pid != null) { 374 Symbol p = env.toplevel.packge; 375 while (p.owner != syms.rootPackage) { 376 p.owner.complete(); // enter all class members of p 377 //need to lookup the owning module/package: 378 PackageSymbol pack = syms.lookupPackage(env.toplevel.modle, p.owner.getQualifiedName()); 379 if (syms.getClass(pack.modle, p.getQualifiedName()) != null) { 380 log.error(tree.pos, 381 "pkg.clashes.with.class.of.same.name", 382 p); 383 } 384 p = p.owner; 385 } 386 } 387 // process package annotations 388 annotate.annotateLater(tree.annotations, env, env.toplevel.packge, null); 389 } 390 391 private void doImport(JCImport tree) { 392 JCFieldAccess imp = (JCFieldAccess)tree.qualid; 393 Name name = TreeInfo.name(imp); 394 395 // Create a local environment pointing to this tree to disable 396 // effects of other imports in Resolve.findGlobalType 397 Env<AttrContext> localEnv = env.dup(tree); 398 399 TypeSymbol p = attr.attribImportQualifier(tree, localEnv).tsym; 400 if (name == names.asterisk) { 401 // Import on demand. 402 chk.checkCanonical(imp.selected); 403 if (tree.staticImport) 404 importStaticAll(tree, p, env); 405 else 406 importAll(tree, p, env); 407 } else { 408 // Named type import. 409 if (tree.staticImport) { 410 importNamedStatic(tree, p, name, localEnv); 411 chk.checkCanonical(imp.selected); 412 } else { 413 Type importedType = attribImportType(imp, localEnv); 414 Type originalType = importedType.getOriginalType(); 415 TypeSymbol c = originalType.hasTag(CLASS) ? originalType.tsym : importedType.tsym; 416 chk.checkCanonical(imp); 417 importNamed(tree.pos(), c, env, tree); 418 } 419 } 420 } 421 422 Type attribImportType(JCTree tree, Env<AttrContext> env) { 423 Assert.check(completionEnabled); 424 Lint prevLint = chk.setLint(allowDeprecationOnImport ? 425 lint : lint.suppress(LintCategory.DEPRECATION, LintCategory.REMOVAL)); 426 try { 427 // To prevent deep recursion, suppress completion of some 428 // types. 429 completionEnabled = false; 430 return attr.attribType(tree, env); 431 } finally { 432 completionEnabled = true; 433 chk.setLint(prevLint); 434 } 435 } 436 437 /** Import all classes of a class or package on demand. 438 * @param imp The import that is being handled. 439 * @param tsym The class or package the members of which are imported. 440 * @param env The env in which the imported classes will be entered. 441 */ 442 private void importAll(JCImport imp, 443 final TypeSymbol tsym, 444 Env<AttrContext> env) { 445 env.toplevel.starImportScope.importAll(types, tsym.members(), typeImportFilter, imp, cfHandler); 446 } 447 448 /** Import all static members of a class or package on demand. 449 * @param imp The import that is being handled. 450 * @param tsym The class or package the members of which are imported. 451 * @param env The env in which the imported classes will be entered. 452 */ 453 private void importStaticAll(JCImport imp, 454 final TypeSymbol tsym, 455 Env<AttrContext> env) { 456 final StarImportScope toScope = env.toplevel.starImportScope; 457 final TypeSymbol origin = tsym; 458 459 toScope.importAll(types, origin.members(), staticImportFilter, imp, cfHandler); 460 } 461 462 /** Import statics types of a given name. Non-types are handled in Attr. 463 * @param imp The import that is being handled. 464 * @param tsym The class from which the name is imported. 465 * @param name The (simple) name being imported. 466 * @param env The environment containing the named import 467 * scope to add to. 468 */ 469 private void importNamedStatic(final JCImport imp, 470 final TypeSymbol tsym, 471 final Name name, 472 final Env<AttrContext> env) { 473 if (tsym.kind != TYP) { 474 log.error(DiagnosticFlag.RECOVERABLE, imp.pos(), "static.imp.only.classes.and.interfaces"); 475 return; 476 } 477 478 final NamedImportScope toScope = env.toplevel.namedImportScope; 479 final Scope originMembers = tsym.members(); 480 481 imp.importScope = toScope.importByName(types, originMembers, name, staticImportFilter, imp, cfHandler); 482 } 483 484 /** Import given class. 485 * @param pos Position to be used for error reporting. 486 * @param tsym The class to be imported. 487 * @param env The environment containing the named import 488 * scope to add to. 489 */ 490 private void importNamed(DiagnosticPosition pos, final Symbol tsym, Env<AttrContext> env, JCImport imp) { 491 if (tsym.kind == TYP) 492 imp.importScope = env.toplevel.namedImportScope.importType(tsym.owner.members(), tsym.owner.members(), tsym); 493 } 494 495 } 496 497 /**Defines common utility methods used by the HierarchyPhase and HeaderPhase. 498 */ 499 private abstract class AbstractHeaderPhase extends Phase { 500 501 public AbstractHeaderPhase(CompletionCause phaseName, Phase next) { 502 super(phaseName, next); 503 } 504 505 protected Env<AttrContext> baseEnv(JCClassDecl tree, Env<AttrContext> env) { 506 WriteableScope baseScope = WriteableScope.create(tree.sym); 507 //import already entered local classes into base scope 508 for (Symbol sym : env.outer.info.scope.getSymbols(NON_RECURSIVE)) { 509 if (sym.isLocal()) { 510 baseScope.enter(sym); 511 } 512 } 513 //import current type-parameters into base scope 514 if (tree.typarams != null) 515 for (List<JCTypeParameter> typarams = tree.typarams; 516 typarams.nonEmpty(); 517 typarams = typarams.tail) 518 baseScope.enter(typarams.head.type.tsym); 519 Env<AttrContext> outer = env.outer; // the base clause can't see members of this class 520 Env<AttrContext> localEnv = outer.dup(tree, outer.info.dup(baseScope)); 521 localEnv.baseClause = true; 522 localEnv.outer = outer; 523 localEnv.info.isSelfCall = false; 524 return localEnv; 525 } 526 527 /** Generate a base clause for an enum type. 528 * @param pos The position for trees and diagnostics, if any 529 * @param c The class symbol of the enum 530 */ 531 protected JCExpression enumBase(int pos, ClassSymbol c) { 532 JCExpression result = make.at(pos). 533 TypeApply(make.QualIdent(syms.enumSym), 534 List.of(make.Type(c.type))); 535 return result; 536 } 537 538 protected Type modelMissingTypes(Env<AttrContext> env, Type t, final JCExpression tree, final boolean interfaceExpected) { 539 if (!t.hasTag(ERROR)) 540 return t; 541 542 return new ErrorType(t.getOriginalType(), t.tsym) { 543 private Type modelType; 544 545 @Override 546 public Type getModelType() { 547 if (modelType == null) 548 modelType = new Synthesizer(env.toplevel.modle, getOriginalType(), interfaceExpected).visit(tree); 549 return modelType; 550 } 551 }; 552 } 553 // where: 554 private class Synthesizer extends JCTree.Visitor { 555 ModuleSymbol msym; 556 Type originalType; 557 boolean interfaceExpected; 558 List<ClassSymbol> synthesizedSymbols = List.nil(); 559 Type result; 560 561 Synthesizer(ModuleSymbol msym, Type originalType, boolean interfaceExpected) { 562 this.msym = msym; 563 this.originalType = originalType; 564 this.interfaceExpected = interfaceExpected; 565 } 566 567 Type visit(JCTree tree) { 568 tree.accept(this); 569 return result; 570 } 571 572 List<Type> visit(List<? extends JCTree> trees) { 573 ListBuffer<Type> lb = new ListBuffer<>(); 574 for (JCTree t: trees) 575 lb.append(visit(t)); 576 return lb.toList(); 577 } 578 579 @Override 580 public void visitTree(JCTree tree) { 581 result = syms.errType; 582 } 583 584 @Override 585 public void visitIdent(JCIdent tree) { 586 if (!tree.type.hasTag(ERROR)) { 587 result = tree.type; 588 } else { 589 result = synthesizeClass(tree.name, msym.unnamedPackage).type; 590 } 591 } 592 593 @Override 594 public void visitSelect(JCFieldAccess tree) { 595 if (!tree.type.hasTag(ERROR)) { 596 result = tree.type; 597 } else { 598 Type selectedType; 599 boolean prev = interfaceExpected; 600 try { 601 interfaceExpected = false; 602 selectedType = visit(tree.selected); 603 } finally { 604 interfaceExpected = prev; 605 } 606 ClassSymbol c = synthesizeClass(tree.name, selectedType.tsym); 607 result = c.type; 608 } 609 } 610 611 @Override 612 public void visitTypeApply(JCTypeApply tree) { 613 if (!tree.type.hasTag(ERROR)) { 614 result = tree.type; 615 } else { 616 ClassType clazzType = (ClassType) visit(tree.clazz); 617 if (synthesizedSymbols.contains(clazzType.tsym)) 618 synthesizeTyparams((ClassSymbol) clazzType.tsym, tree.arguments.size()); 619 final List<Type> actuals = visit(tree.arguments); 620 result = new ErrorType(tree.type, clazzType.tsym) { 621 @Override @DefinedBy(Api.LANGUAGE_MODEL) 622 public List<Type> getTypeArguments() { 623 return actuals; 624 } 625 }; 626 } 627 } 628 629 ClassSymbol synthesizeClass(Name name, Symbol owner) { 630 int flags = interfaceExpected ? INTERFACE : 0; 631 ClassSymbol c = new ClassSymbol(flags, name, owner); 632 c.members_field = new Scope.ErrorScope(c); 633 c.type = new ErrorType(originalType, c) { 634 @Override @DefinedBy(Api.LANGUAGE_MODEL) 635 public List<Type> getTypeArguments() { 636 return typarams_field; 637 } 638 }; 639 synthesizedSymbols = synthesizedSymbols.prepend(c); 640 return c; 641 } 642 643 void synthesizeTyparams(ClassSymbol sym, int n) { 644 ClassType ct = (ClassType) sym.type; 645 Assert.check(ct.typarams_field.isEmpty()); 646 if (n == 1) { 647 TypeVar v = new TypeVar(names.fromString("T"), sym, syms.botType); 648 ct.typarams_field = ct.typarams_field.prepend(v); 649 } else { 650 for (int i = n; i > 0; i--) { 651 TypeVar v = new TypeVar(names.fromString("T" + i), sym, 652 syms.botType); 653 ct.typarams_field = ct.typarams_field.prepend(v); 654 } 655 } 656 } 657 } 658 659 protected void attribSuperTypes(Env<AttrContext> env, Env<AttrContext> baseEnv) { 660 JCClassDecl tree = env.enclClass; 661 ClassSymbol sym = tree.sym; 662 ClassType ct = (ClassType)sym.type; 663 // Determine supertype. 664 Type supertype; 665 JCExpression extending; 666 667 if (tree.extending != null) { 668 extending = clearTypeParams(tree.extending); 669 supertype = attr.attribBase(extending, baseEnv, true, false, true); 670 } else { 671 extending = null; 672 supertype = ((tree.mods.flags & Flags.ENUM) != 0) 673 ? attr.attribBase(enumBase(tree.pos, sym), baseEnv, 674 true, false, false) 675 : (sym.fullname == names.java_lang_Object) 676 ? Type.noType 677 : syms.objectType; 678 } 679 ct.supertype_field = modelMissingTypes(baseEnv, supertype, extending, false); 680 681 // Determine interfaces. 682 ListBuffer<Type> interfaces = new ListBuffer<>(); 683 ListBuffer<Type> all_interfaces = null; // lazy init 684 List<JCExpression> interfaceTrees = tree.implementing; 685 for (JCExpression iface : interfaceTrees) { 686 iface = clearTypeParams(iface); 687 Type it = attr.attribBase(iface, baseEnv, false, true, true); 688 if (it.hasTag(CLASS)) { 689 interfaces.append(it); 690 if (all_interfaces != null) all_interfaces.append(it); 691 } else { 692 if (all_interfaces == null) 693 all_interfaces = new ListBuffer<Type>().appendList(interfaces); 694 all_interfaces.append(modelMissingTypes(baseEnv, it, iface, true)); 695 } 696 } 697 698 if ((sym.flags_field & ANNOTATION) != 0) { 699 ct.interfaces_field = List.of(syms.annotationType); 700 ct.all_interfaces_field = ct.interfaces_field; 701 } else { 702 ct.interfaces_field = interfaces.toList(); 703 ct.all_interfaces_field = (all_interfaces == null) 704 ? ct.interfaces_field : all_interfaces.toList(); 705 } 706 } 707 //where: 708 protected JCExpression clearTypeParams(JCExpression superType) { 709 return superType; 710 } 711 } 712 713 private final class HierarchyPhase extends AbstractHeaderPhase implements Completer { 714 715 public HierarchyPhase() { 716 super(CompletionCause.HIERARCHY_PHASE, new HeaderPhase()); 717 } 718 719 @Override 720 protected void doCompleteEnvs(List<Env<AttrContext>> envs) { 721 //The ClassSymbols in the envs list may not be in the dependency order. 722 //To get proper results, for every class or interface C, the supertypes of 723 //C must be processed by the HierarchyPhase phase before C. 724 //To achieve that, the HierarchyPhase is registered as the Completer for 725 //all the classes first, and then all the classes are completed. 726 for (Env<AttrContext> env : envs) { 727 env.enclClass.sym.completer = this; 728 } 729 for (Env<AttrContext> env : envs) { 730 env.enclClass.sym.complete(); 731 } 732 } 733 734 @Override 735 protected void runPhase(Env<AttrContext> env) { 736 JCClassDecl tree = env.enclClass; 737 ClassSymbol sym = tree.sym; 738 ClassType ct = (ClassType)sym.type; 739 740 Env<AttrContext> baseEnv = baseEnv(tree, env); 741 742 attribSuperTypes(env, baseEnv); 743 744 if (sym.fullname == names.java_lang_Object) { 745 if (tree.extending != null) { 746 chk.checkNonCyclic(tree.extending.pos(), 747 ct.supertype_field); 748 ct.supertype_field = Type.noType; 749 } 750 else if (tree.implementing.nonEmpty()) { 751 chk.checkNonCyclic(tree.implementing.head.pos(), 752 ct.interfaces_field.head); 753 ct.interfaces_field = List.nil(); 754 } 755 } 756 757 markDeprecated(sym, tree.mods.annotations, baseEnv); 758 759 chk.checkNonCyclicDecl(tree); 760 } 761 //where: 762 @Override 763 protected JCExpression clearTypeParams(JCExpression superType) { 764 switch (superType.getTag()) { 765 case TYPEAPPLY: 766 return ((JCTypeApply) superType).clazz; 767 } 768 769 return superType; 770 } 771 772 @Override 773 public void complete(Symbol sym) throws CompletionFailure { 774 Assert.check((topLevelPhase instanceof ImportsPhase) || 775 (topLevelPhase == this)); 776 777 if (topLevelPhase != this) { 778 //only do the processing based on dependencies in the HierarchyPhase: 779 sym.completer = this; 780 return ; 781 } 782 783 Env<AttrContext> env = typeEnvs.get((ClassSymbol) sym); 784 785 super.doCompleteEnvs(List.of(env)); 786 } 787 788 } 789 790 private final class HeaderPhase extends AbstractHeaderPhase { 791 792 public HeaderPhase() { 793 super(CompletionCause.HEADER_PHASE, new MembersPhase()); 794 } 795 796 @Override 797 protected void runPhase(Env<AttrContext> env) { 798 JCClassDecl tree = env.enclClass; 799 ClassSymbol sym = tree.sym; 800 ClassType ct = (ClassType)sym.type; 801 802 // create an environment for evaluating the base clauses 803 Env<AttrContext> baseEnv = baseEnv(tree, env); 804 805 if (tree.extending != null) 806 annotate.queueScanTreeAndTypeAnnotate(tree.extending, baseEnv, sym, tree.pos()); 807 for (JCExpression impl : tree.implementing) 808 annotate.queueScanTreeAndTypeAnnotate(impl, baseEnv, sym, tree.pos()); 809 annotate.flush(); 810 811 attribSuperTypes(env, baseEnv); 812 813 Set<Type> interfaceSet = new HashSet<>(); 814 815 for (JCExpression iface : tree.implementing) { 816 Type it = iface.type; 817 if (it.hasTag(CLASS)) 818 chk.checkNotRepeated(iface.pos(), types.erasure(it), interfaceSet); 819 } 820 821 annotate.annotateLater(tree.mods.annotations, baseEnv, 822 sym, tree.pos()); 823 824 attr.attribTypeVariables(tree.typarams, baseEnv); 825 for (JCTypeParameter tp : tree.typarams) 826 annotate.queueScanTreeAndTypeAnnotate(tp, baseEnv, sym, tree.pos()); 827 828 // check that no package exists with same fully qualified name, 829 // but admit classes in the unnamed package which have the same 830 // name as a top-level package. 831 if (checkClash && 832 sym.owner.kind == PCK && sym.owner != env.toplevel.modle.unnamedPackage && 833 syms.packageExists(env.toplevel.modle, sym.fullname)) { 834 log.error(tree.pos, "clash.with.pkg.of.same.name", Kinds.kindName(sym), sym); 835 } 836 if (sym.owner.kind == PCK && (sym.flags_field & PUBLIC) == 0 && 837 !env.toplevel.sourcefile.isNameCompatible(sym.name.toString(),JavaFileObject.Kind.SOURCE)) { 838 sym.flags_field |= AUXILIARY; 839 } 840 } 841 } 842 843 /** Enter member fields and methods of a class 844 */ 845 private final class MembersPhase extends Phase { 846 847 public MembersPhase() { 848 super(CompletionCause.MEMBERS_PHASE, null); 849 } 850 851 private boolean completing; 852 private List<Env<AttrContext>> todo = List.nil(); 853 854 @Override 855 protected void doCompleteEnvs(List<Env<AttrContext>> envs) { 856 todo = todo.prependList(envs); 857 if (completing) { 858 return ; //the top-level invocation will handle all envs 859 } 860 boolean prevCompleting = completing; 861 completing = true; 862 try { 863 while (todo.nonEmpty()) { 864 Env<AttrContext> head = todo.head; 865 todo = todo.tail; 866 super.doCompleteEnvs(List.of(head)); 867 } 868 } finally { 869 completing = prevCompleting; 870 } 871 } 872 873 @Override 874 protected void runPhase(Env<AttrContext> env) { 875 JCClassDecl tree = env.enclClass; 876 ClassSymbol sym = tree.sym; 877 ClassType ct = (ClassType)sym.type; 878 879 // Add default constructor if needed. 880 if ((sym.flags() & INTERFACE) == 0 && 881 !TreeInfo.hasConstructors(tree.defs)) { 882 List<Type> argtypes = List.nil(); 883 List<Type> typarams = List.nil(); 884 List<Type> thrown = List.nil(); 885 long ctorFlags = 0; 886 boolean based = false; 887 boolean addConstructor = true; 888 JCNewClass nc = null; 889 if (sym.name.isEmpty()) { 890 nc = (JCNewClass)env.next.tree; 891 if (nc.constructor != null) { 892 addConstructor = nc.constructor.kind != ERR; 893 Type superConstrType = types.memberType(sym.type, 894 nc.constructor); 895 argtypes = superConstrType.getParameterTypes(); 896 typarams = superConstrType.getTypeArguments(); 897 ctorFlags = nc.constructor.flags() & VARARGS; 898 if (nc.encl != null) { 899 argtypes = argtypes.prepend(nc.encl.type); 900 based = true; 901 } 902 thrown = superConstrType.getThrownTypes(); 903 } 904 } 905 if (addConstructor) { 906 MethodSymbol basedConstructor = nc != null ? 907 (MethodSymbol)nc.constructor : null; 908 JCTree constrDef = DefaultConstructor(make.at(tree.pos), sym, 909 basedConstructor, 910 typarams, argtypes, thrown, 911 ctorFlags, based); 912 tree.defs = tree.defs.prepend(constrDef); 913 } 914 } 915 916 // enter symbols for 'this' into current scope. 917 VarSymbol thisSym = 918 new VarSymbol(FINAL | HASINIT, names._this, sym.type, sym); 919 thisSym.pos = Position.FIRSTPOS; 920 env.info.scope.enter(thisSym); 921 // if this is a class, enter symbol for 'super' into current scope. 922 if ((sym.flags_field & INTERFACE) == 0 && 923 ct.supertype_field.hasTag(CLASS)) { 924 VarSymbol superSym = 925 new VarSymbol(FINAL | HASINIT, names._super, 926 ct.supertype_field, sym); 927 superSym.pos = Position.FIRSTPOS; 928 env.info.scope.enter(superSym); 929 } 930 931 finishClass(tree, env); 932 933 if (allowTypeAnnos) { 934 typeAnnotations.organizeTypeAnnotationsSignatures(env, (JCClassDecl)env.tree); 935 typeAnnotations.validateTypeAnnotationsSignatures(env, (JCClassDecl)env.tree); 936 } 937 } 938 939 /** Enter members for a class. 940 */ 941 void finishClass(JCClassDecl tree, Env<AttrContext> env) { 942 if ((tree.mods.flags & Flags.ENUM) != 0 && 943 !tree.sym.type.hasTag(ERROR) && 944 (types.supertype(tree.sym.type).tsym.flags() & Flags.ENUM) == 0) { 945 addEnumMembers(tree, env); 946 } 947 memberEnter.memberEnter(tree.defs, env); 948 949 if (tree.sym.isAnnotationType()) { 950 Assert.check(tree.sym.isCompleted()); 951 tree.sym.setAnnotationTypeMetadata(new AnnotationTypeMetadata(tree.sym, annotate.annotationTypeSourceCompleter())); 952 } 953 } 954 955 /** Add the implicit members for an enum type 956 * to the symbol table. 957 */ 958 private void addEnumMembers(JCClassDecl tree, Env<AttrContext> env) { 959 JCExpression valuesType = make.Type(new ArrayType(tree.sym.type, syms.arrayClass)); 960 961 // public static T[] values() { return ???; } 962 JCMethodDecl values = make. 963 MethodDef(make.Modifiers(Flags.PUBLIC|Flags.STATIC), 964 names.values, 965 valuesType, 966 List.nil(), 967 List.nil(), 968 List.nil(), // thrown 969 null, //make.Block(0, Tree.emptyList.prepend(make.Return(make.Ident(names._null)))), 970 null); 971 memberEnter.memberEnter(values, env); 972 973 // public static T valueOf(String name) { return ???; } 974 JCMethodDecl valueOf = make. 975 MethodDef(make.Modifiers(Flags.PUBLIC|Flags.STATIC), 976 names.valueOf, 977 make.Type(tree.sym.type), 978 List.nil(), 979 List.of(make.VarDef(make.Modifiers(Flags.PARAMETER | 980 Flags.MANDATED), 981 names.fromString("name"), 982 make.Type(syms.stringType), null)), 983 List.nil(), // thrown 984 null, //make.Block(0, Tree.emptyList.prepend(make.Return(make.Ident(names._null)))), 985 null); 986 memberEnter.memberEnter(valueOf, env); 987 } 988 989 } 990 991/* *************************************************************************** 992 * tree building 993 ****************************************************************************/ 994 995 /** Generate default constructor for given class. For classes different 996 * from java.lang.Object, this is: 997 * 998 * c(argtype_0 x_0, ..., argtype_n x_n) throws thrown { 999 * super(x_0, ..., x_n) 1000 * } 1001 * 1002 * or, if based == true: 1003 * 1004 * c(argtype_0 x_0, ..., argtype_n x_n) throws thrown { 1005 * x_0.super(x_1, ..., x_n) 1006 * } 1007 * 1008 * @param make The tree factory. 1009 * @param c The class owning the default constructor. 1010 * @param argtypes The parameter types of the constructor. 1011 * @param thrown The thrown exceptions of the constructor. 1012 * @param based Is first parameter a this$n? 1013 */ 1014 JCTree DefaultConstructor(TreeMaker make, 1015 ClassSymbol c, 1016 MethodSymbol baseInit, 1017 List<Type> typarams, 1018 List<Type> argtypes, 1019 List<Type> thrown, 1020 long flags, 1021 boolean based) { 1022 JCTree result; 1023 if ((c.flags() & ENUM) != 0 && 1024 (types.supertype(c.type).tsym == syms.enumSym)) { 1025 // constructors of true enums are private 1026 flags = (flags & ~AccessFlags) | PRIVATE | GENERATEDCONSTR; 1027 } else 1028 flags |= (c.flags() & AccessFlags) | GENERATEDCONSTR; 1029 if (c.name.isEmpty()) { 1030 flags |= ANONCONSTR; 1031 } 1032 Type mType = new MethodType(argtypes, null, thrown, c); 1033 Type initType = typarams.nonEmpty() ? 1034 new ForAll(typarams, mType) : 1035 mType; 1036 MethodSymbol init = new MethodSymbol(flags, names.init, 1037 initType, c); 1038 init.params = createDefaultConstructorParams(make, baseInit, init, 1039 argtypes, based); 1040 List<JCVariableDecl> params = make.Params(argtypes, init); 1041 List<JCStatement> stats = List.nil(); 1042 if (c.type != syms.objectType) { 1043 stats = stats.prepend(SuperCall(make, typarams, params, based)); 1044 } 1045 result = make.MethodDef(init, make.Block(0, stats)); 1046 return result; 1047 } 1048 1049 private List<VarSymbol> createDefaultConstructorParams( 1050 TreeMaker make, 1051 MethodSymbol baseInit, 1052 MethodSymbol init, 1053 List<Type> argtypes, 1054 boolean based) { 1055 List<VarSymbol> initParams = null; 1056 List<Type> argTypesList = argtypes; 1057 if (based) { 1058 /* In this case argtypes will have an extra type, compared to baseInit, 1059 * corresponding to the type of the enclosing instance i.e.: 1060 * 1061 * Inner i = outer.new Inner(1){} 1062 * 1063 * in the above example argtypes will be (Outer, int) and baseInit 1064 * will have parameter's types (int). So in this case we have to add 1065 * first the extra type in argtypes and then get the names of the 1066 * parameters from baseInit. 1067 */ 1068 initParams = List.nil(); 1069 VarSymbol param = new VarSymbol(PARAMETER, make.paramName(0), argtypes.head, init); 1070 initParams = initParams.append(param); 1071 argTypesList = argTypesList.tail; 1072 } 1073 if (baseInit != null && baseInit.params != null && 1074 baseInit.params.nonEmpty() && argTypesList.nonEmpty()) { 1075 initParams = (initParams == null) ? List.nil() : initParams; 1076 List<VarSymbol> baseInitParams = baseInit.params; 1077 while (baseInitParams.nonEmpty() && argTypesList.nonEmpty()) { 1078 VarSymbol param = new VarSymbol(baseInitParams.head.flags() | PARAMETER, 1079 baseInitParams.head.name, argTypesList.head, init); 1080 initParams = initParams.append(param); 1081 baseInitParams = baseInitParams.tail; 1082 argTypesList = argTypesList.tail; 1083 } 1084 } 1085 return initParams; 1086 } 1087 1088 /** Generate call to superclass constructor. This is: 1089 * 1090 * super(id_0, ..., id_n) 1091 * 1092 * or, if based == true 1093 * 1094 * id_0.super(id_1,...,id_n) 1095 * 1096 * where id_0, ..., id_n are the names of the given parameters. 1097 * 1098 * @param make The tree factory 1099 * @param params The parameters that need to be passed to super 1100 * @param typarams The type parameters that need to be passed to super 1101 * @param based Is first parameter a this$n? 1102 */ 1103 JCExpressionStatement SuperCall(TreeMaker make, 1104 List<Type> typarams, 1105 List<JCVariableDecl> params, 1106 boolean based) { 1107 JCExpression meth; 1108 if (based) { 1109 meth = make.Select(make.Ident(params.head), names._super); 1110 params = params.tail; 1111 } else { 1112 meth = make.Ident(names._super); 1113 } 1114 List<JCExpression> typeargs = typarams.nonEmpty() ? make.Types(typarams) : null; 1115 return make.Exec(make.Apply(typeargs, meth, make.Idents(params))); 1116 } 1117 1118 /** 1119 * Mark sym deprecated if annotations contain @Deprecated annotation. 1120 */ 1121 public void markDeprecated(Symbol sym, List<JCAnnotation> annotations, Env<AttrContext> env) { 1122 // In general, we cannot fully process annotations yet, but we 1123 // can attribute the annotation types and then check to see if the 1124 // @Deprecated annotation is present. 1125 attr.attribAnnotationTypes(annotations, env); 1126 handleDeprecatedAnnotations(annotations, sym); 1127 } 1128 1129 /** 1130 * If a list of annotations contains a reference to java.lang.Deprecated, 1131 * set the DEPRECATED flag. 1132 * If the annotation is marked forRemoval=true, also set DEPRECATED_REMOVAL. 1133 **/ 1134 private void handleDeprecatedAnnotations(List<JCAnnotation> annotations, Symbol sym) { 1135 for (List<JCAnnotation> al = annotations; !al.isEmpty(); al = al.tail) { 1136 JCAnnotation a = al.head; 1137 if (a.annotationType.type == syms.deprecatedType) { 1138 sym.flags_field |= (Flags.DEPRECATED | Flags.DEPRECATED_ANNOTATION); 1139 a.args.stream() 1140 .filter(e -> e.hasTag(ASSIGN)) 1141 .map(e -> (JCAssign) e) 1142 .filter(assign -> TreeInfo.name(assign.lhs) == names.forRemoval) 1143 .findFirst() 1144 .ifPresent(assign -> { 1145 JCExpression rhs = TreeInfo.skipParens(assign.rhs); 1146 if (rhs.hasTag(LITERAL) 1147 && Boolean.TRUE.equals(((JCLiteral) rhs).getValue())) { 1148 sym.flags_field |= DEPRECATED_REMOVAL; 1149 } 1150 }); 1151 } 1152 } 1153 } 1154} 1155