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