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