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