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