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