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