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