1 /* 2 * Copyright (c) 2003, 2011, 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 26 package com.sun.tools.javac.comp; 27 28 import java.util.*; 29 import java.util.Set; 30 import javax.tools.JavaFileObject; 31 32 import com.sun.tools.javac.code.*; 33 import com.sun.tools.javac.jvm.*; 34 import com.sun.tools.javac.tree.*; 35 import com.sun.tools.javac.util.*; 36 import com.sun.tools.javac.util.List; 37 38 import com.sun.tools.javac.code.Type.*; 39 import com.sun.tools.javac.code.Symbol.*; 40 import com.sun.tools.javac.tree.JCTree.*; 41 42 import static com.sun.tools.javac.code.Flags.*; 43 import static com.sun.tools.javac.code.Flags.ANNOTATION; 44 import static com.sun.tools.javac.code.Kinds.*; 45 import static com.sun.tools.javac.code.TypeTags.*; 46 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; 47 48 import static com.sun.tools.javac.tree.JCTree.Tag.*; 49 50 /** This is the second phase of Enter, in which classes are completed 51 * by entering their members into the class scope using 52 * MemberEnter.complete(). See Enter for an overview. 53 * 54 * <p><b>This is NOT part of any supported API. 55 * If you write code that depends on this, you do so at your own risk. 56 * This code and its internal interfaces are subject to change or 57 * deletion without notice.</b> 58 */ 59 public class MemberEnter extends JCTree.Visitor implements Completer { 60 protected static final Context.Key<MemberEnter> memberEnterKey = 61 new Context.Key<MemberEnter>(); 62 63 /** A switch to determine whether we check for package/class conflicts 64 */ 65 final static boolean checkClash = true; 66 67 private final Names names; 68 private final Enter enter; 69 private final Log log; 70 private final Check chk; 71 private final Attr attr; 72 private final Symtab syms; 73 private final TreeMaker make; 74 private final ClassReader reader; 75 private final Todo todo; 76 private final Annotate annotate; 77 private final Types types; 78 private final JCDiagnostic.Factory diags; 79 private final Target target; 80 private final DeferredLintHandler deferredLintHandler; 81 82 private final boolean skipAnnotations; 83 84 public static MemberEnter instance(Context context) { 85 MemberEnter instance = context.get(memberEnterKey); 86 if (instance == null) 87 instance = new MemberEnter(context); 88 return instance; 89 } 90 91 protected MemberEnter(Context context) { 92 context.put(memberEnterKey, this); 93 names = Names.instance(context); 94 enter = Enter.instance(context); 95 log = Log.instance(context); 96 chk = Check.instance(context); 97 attr = Attr.instance(context); 98 syms = Symtab.instance(context); 99 make = TreeMaker.instance(context); 100 reader = ClassReader.instance(context); 101 todo = Todo.instance(context); 102 annotate = Annotate.instance(context); 103 types = Types.instance(context); 104 diags = JCDiagnostic.Factory.instance(context); 105 target = Target.instance(context); 106 deferredLintHandler = DeferredLintHandler.instance(context); 107 Options options = Options.instance(context); 108 skipAnnotations = options.isSet("skipAnnotations"); 109 } 110 111 /** A queue for classes whose members still need to be entered into the 112 * symbol table. 113 */ 114 ListBuffer<Env<AttrContext>> halfcompleted = new ListBuffer<Env<AttrContext>>(); 115 116 /** Set to true only when the first of a set of classes is 117 * processed from the halfcompleted queue. 118 */ 119 boolean isFirst = true; 120 121 /** A flag to disable completion from time to time during member 122 * enter, as we only need to look up types. This avoids 123 * unnecessarily deep recursion. 124 */ 125 boolean completionEnabled = true; 126 127 /* ---------- Processing import clauses ---------------- 128 */ 129 130 /** Import all classes of a class or package on demand. 131 * @param pos Position to be used for error reporting. 132 * @param tsym The class or package the members of which are imported. 133 * @param toScope The (import) scope in which imported classes 134 * are entered. 135 */ 136 private void importAll(int pos, 137 final TypeSymbol tsym, 138 Env<AttrContext> env) { 139 // Check that packages imported from exist (JLS ???). 140 if (tsym.kind == PCK && tsym.members().elems == null && !tsym.exists()) { 141 // If we can't find java.lang, exit immediately. 142 if (((PackageSymbol)tsym).fullname.equals(names.java_lang)) { 143 JCDiagnostic msg = diags.fragment("fatal.err.no.java.lang"); 144 throw new FatalError(msg); 145 } else { 146 log.error(pos, "doesnt.exist", tsym); 147 } 148 } 149 env.toplevel.starImportScope.importAll(tsym.members()); 150 } 151 152 /** Import all static members of a class or package on demand. 153 * @param pos Position to be used for error reporting. 154 * @param tsym The class or package the members of which are imported. 155 * @param toScope The (import) scope in which imported classes 156 * are entered. 157 */ 158 private void importStaticAll(int pos, 159 final TypeSymbol tsym, 160 Env<AttrContext> env) { 161 final JavaFileObject sourcefile = env.toplevel.sourcefile; 162 final Scope toScope = env.toplevel.starImportScope; 163 final PackageSymbol packge = env.toplevel.packge; 164 final TypeSymbol origin = tsym; 165 166 // enter imported types immediately 167 new Object() { 168 Set<Symbol> processed = new HashSet<Symbol>(); 169 void importFrom(TypeSymbol tsym) { 170 if (tsym == null || !processed.add(tsym)) 171 return; 172 173 // also import inherited names 174 importFrom(types.supertype(tsym.type).tsym); 175 for (Type t : types.interfaces(tsym.type)) 176 importFrom(t.tsym); 177 178 final Scope fromScope = tsym.members(); 179 for (Scope.Entry e = fromScope.elems; e != null; e = e.sibling) { 180 Symbol sym = e.sym; 181 if (sym.kind == TYP && 182 (sym.flags() & STATIC) != 0 && 183 staticImportAccessible(sym, packge) && 184 sym.isMemberOf(origin, types) && 185 !toScope.includes(sym)) 186 toScope.enter(sym, fromScope, origin.members()); 187 } 188 } 189 }.importFrom(tsym); 190 191 // enter non-types before annotations that might use them 192 annotate.earlier(new Annotate.Annotator() { 193 Set<Symbol> processed = new HashSet<Symbol>(); 194 195 public String toString() { 196 return "import static " + tsym + ".*" + " in " + sourcefile; 197 } 198 void importFrom(TypeSymbol tsym) { 199 if (tsym == null || !processed.add(tsym)) 200 return; 201 202 // also import inherited names 203 importFrom(types.supertype(tsym.type).tsym); 204 for (Type t : types.interfaces(tsym.type)) 205 importFrom(t.tsym); 206 207 final Scope fromScope = tsym.members(); 208 for (Scope.Entry e = fromScope.elems; e != null; e = e.sibling) { 209 Symbol sym = e.sym; 210 if (sym.isStatic() && sym.kind != TYP && 211 staticImportAccessible(sym, packge) && 212 !toScope.includes(sym) && 213 sym.isMemberOf(origin, types)) { 214 toScope.enter(sym, fromScope, origin.members()); 215 } 216 } 217 } 218 public void enterAnnotation() { 219 importFrom(tsym); 220 } 221 }); 222 } 223 224 // is the sym accessible everywhere in packge? 225 boolean staticImportAccessible(Symbol sym, PackageSymbol packge) { 226 int flags = (int)(sym.flags() & AccessFlags); 227 switch (flags) { 228 default: 229 case PUBLIC: 230 return true; 231 case PRIVATE: 232 return false; 233 case 0: 234 case PROTECTED: 235 return sym.packge() == packge; 236 } 237 } 238 239 /** Import statics types of a given name. Non-types are handled in Attr. 240 * @param pos Position to be used for error reporting. 241 * @param tsym The class from which the name is imported. 242 * @param name The (simple) name being imported. 243 * @param env The environment containing the named import 244 * scope to add to. 245 */ 246 private void importNamedStatic(final DiagnosticPosition pos, 247 final TypeSymbol tsym, 248 final Name name, 249 final Env<AttrContext> env) { 250 if (tsym.kind != TYP) { 251 log.error(pos, "static.imp.only.classes.and.interfaces"); 252 return; 253 } 254 255 final Scope toScope = env.toplevel.namedImportScope; 256 final PackageSymbol packge = env.toplevel.packge; 257 final TypeSymbol origin = tsym; 258 259 // enter imported types immediately 260 new Object() { 261 Set<Symbol> processed = new HashSet<Symbol>(); 262 void importFrom(TypeSymbol tsym) { 263 if (tsym == null || !processed.add(tsym)) 264 return; 265 266 // also import inherited names 267 importFrom(types.supertype(tsym.type).tsym); 268 for (Type t : types.interfaces(tsym.type)) 269 importFrom(t.tsym); 270 271 for (Scope.Entry e = tsym.members().lookup(name); 272 e.scope != null; 273 e = e.next()) { 274 Symbol sym = e.sym; 275 if (sym.isStatic() && 276 sym.kind == TYP && 277 staticImportAccessible(sym, packge) && 278 sym.isMemberOf(origin, types) && 279 chk.checkUniqueStaticImport(pos, sym, toScope)) 280 toScope.enter(sym, sym.owner.members(), origin.members()); 281 } 282 } 283 }.importFrom(tsym); 284 285 // enter non-types before annotations that might use them 286 annotate.earlier(new Annotate.Annotator() { 287 Set<Symbol> processed = new HashSet<Symbol>(); 288 boolean found = false; 289 290 public String toString() { 291 return "import static " + tsym + "." + name; 292 } 293 void importFrom(TypeSymbol tsym) { 294 if (tsym == null || !processed.add(tsym)) 295 return; 296 297 // also import inherited names 298 importFrom(types.supertype(tsym.type).tsym); 299 for (Type t : types.interfaces(tsym.type)) 300 importFrom(t.tsym); 301 302 for (Scope.Entry e = tsym.members().lookup(name); 303 e.scope != null; 304 e = e.next()) { 305 Symbol sym = e.sym; 306 if (sym.isStatic() && 307 staticImportAccessible(sym, packge) && 308 sym.isMemberOf(origin, types)) { 309 found = true; 310 if (sym.kind == MTH || 311 sym.kind != TYP && chk.checkUniqueStaticImport(pos, sym, toScope)) 312 toScope.enter(sym, sym.owner.members(), origin.members()); 313 } 314 } 315 } 316 public void enterAnnotation() { 317 JavaFileObject prev = log.useSource(env.toplevel.sourcefile); 318 try { 319 importFrom(tsym); 320 if (!found) { 321 log.error(pos, "cant.resolve.location", 322 KindName.STATIC, 323 name, List.<Type>nil(), List.<Type>nil(), 324 Kinds.typeKindName(tsym.type), 325 tsym.type); 326 } 327 } finally { 328 log.useSource(prev); 329 } 330 } 331 }); 332 } 333 /** Import given class. 334 * @param pos Position to be used for error reporting. 335 * @param tsym The class to be imported. 336 * @param env The environment containing the named import 337 * scope to add to. 338 */ 339 private void importNamed(DiagnosticPosition pos, Symbol tsym, Env<AttrContext> env) { 340 if (tsym.kind == TYP && 341 chk.checkUniqueImport(pos, tsym, env.toplevel.namedImportScope)) 342 env.toplevel.namedImportScope.enter(tsym, tsym.owner.members()); 343 } 344 345 /** Construct method type from method signature. 346 * @param typarams The method's type parameters. 347 * @param params The method's value parameters. 348 * @param res The method's result type, 349 * null if it is a constructor. 350 * @param thrown The method's thrown exceptions. 351 * @param env The method's (local) environment. 352 */ 353 Type signature(List<JCTypeParameter> typarams, 354 List<JCVariableDecl> params, 355 JCTree res, 356 List<JCExpression> thrown, 357 Env<AttrContext> env) { 358 359 // Enter and attribute type parameters. 360 List<Type> tvars = enter.classEnter(typarams, env); 361 attr.attribTypeVariables(typarams, env); 362 363 // Enter and attribute value parameters. 364 ListBuffer<Type> argbuf = new ListBuffer<Type>(); 365 for (List<JCVariableDecl> l = params; l.nonEmpty(); l = l.tail) { 366 memberEnter(l.head, env); 367 argbuf.append(l.head.vartype.type); 368 } 369 370 // Attribute result type, if one is given. 371 Type restype = res == null ? syms.voidType : attr.attribType(res, env); 372 373 // Attribute thrown exceptions. 374 ListBuffer<Type> thrownbuf = new ListBuffer<Type>(); 375 for (List<JCExpression> l = thrown; l.nonEmpty(); l = l.tail) { 376 Type exc = attr.attribType(l.head, env); 377 if (exc.tag != TYPEVAR) 378 exc = chk.checkClassType(l.head.pos(), exc); 379 thrownbuf.append(exc); 380 } 381 Type mtype = new MethodType(argbuf.toList(), 382 restype, 383 thrownbuf.toList(), 384 syms.methodClass); 385 return tvars.isEmpty() ? mtype : new ForAll(tvars, mtype); 386 } 387 388 /* ******************************************************************** 389 * Visitor methods for member enter 390 *********************************************************************/ 391 392 /** Visitor argument: the current environment 393 */ 394 protected Env<AttrContext> env; 395 396 /** Enter field and method definitions and process import 397 * clauses, catching any completion failure exceptions. 398 */ 399 protected void memberEnter(JCTree tree, Env<AttrContext> env) { 400 Env<AttrContext> prevEnv = this.env; 401 try { 402 this.env = env; 403 tree.accept(this); 404 } catch (CompletionFailure ex) { 405 chk.completionError(tree.pos(), ex); 406 } finally { 407 this.env = prevEnv; 408 } 409 } 410 411 /** Enter members from a list of trees. 412 */ 413 void memberEnter(List<? extends JCTree> trees, Env<AttrContext> env) { 414 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail) 415 memberEnter(l.head, env); 416 } 417 418 /** Enter members for a class. 419 */ 420 void finishClass(JCClassDecl tree, Env<AttrContext> env) { 421 if ((tree.mods.flags & Flags.ENUM) != 0 && 422 (types.supertype(tree.sym.type).tsym.flags() & Flags.ENUM) == 0) { 423 addEnumMembers(tree, env); 424 } 425 memberEnter(tree.defs, env); 426 } 427 428 /** Add the implicit members for an enum type 429 * to the symbol table. 430 */ 431 private void addEnumMembers(JCClassDecl tree, Env<AttrContext> env) { 432 JCExpression valuesType = make.Type(new ArrayType(tree.sym.type, syms.arrayClass)); 433 434 // public static T[] values() { return ???; } 435 JCMethodDecl values = make. 436 MethodDef(make.Modifiers(Flags.PUBLIC|Flags.STATIC), 437 names.values, 438 valuesType, 439 List.<JCTypeParameter>nil(), 440 List.<JCVariableDecl>nil(), 441 List.<JCExpression>nil(), // thrown 442 null, //make.Block(0, Tree.emptyList.prepend(make.Return(make.Ident(names._null)))), 443 null); 444 memberEnter(values, env); 445 446 // public static T valueOf(String name) { return ???; } 447 JCMethodDecl valueOf = make. 448 MethodDef(make.Modifiers(Flags.PUBLIC|Flags.STATIC), 449 names.valueOf, 450 make.Type(tree.sym.type), 451 List.<JCTypeParameter>nil(), 452 List.of(make.VarDef(make.Modifiers(Flags.PARAMETER), 453 names.fromString("name"), 454 make.Type(syms.stringType), null)), 455 List.<JCExpression>nil(), // thrown 456 null, //make.Block(0, Tree.emptyList.prepend(make.Return(make.Ident(names._null)))), 457 null); 458 memberEnter(valueOf, env); 459 460 // the remaining members are for bootstrapping only 461 if (!target.compilerBootstrap(tree.sym)) return; 462 463 // public final int ordinal() { return ???; } 464 JCMethodDecl ordinal = make.at(tree.pos). 465 MethodDef(make.Modifiers(Flags.PUBLIC|Flags.FINAL), 466 names.ordinal, 467 make.Type(syms.intType), 468 List.<JCTypeParameter>nil(), 469 List.<JCVariableDecl>nil(), 470 List.<JCExpression>nil(), 471 null, 472 null); 473 memberEnter(ordinal, env); 474 475 // public final String name() { return ???; } 476 JCMethodDecl name = make. 477 MethodDef(make.Modifiers(Flags.PUBLIC|Flags.FINAL), 478 names._name, 479 make.Type(syms.stringType), 480 List.<JCTypeParameter>nil(), 481 List.<JCVariableDecl>nil(), 482 List.<JCExpression>nil(), 483 null, 484 null); 485 memberEnter(name, env); 486 487 // public int compareTo(E other) { return ???; } 488 MethodSymbol compareTo = new 489 MethodSymbol(Flags.PUBLIC, 490 names.compareTo, 491 new MethodType(List.of(tree.sym.type), 492 syms.intType, 493 List.<Type>nil(), 494 syms.methodClass), 495 tree.sym); 496 memberEnter(make.MethodDef(compareTo, null), env); 497 } 498 499 public void visitTopLevel(JCCompilationUnit tree) { 500 if (tree.starImportScope.elems != null) { 501 // we must have already processed this toplevel 502 return; 503 } 504 505 // check that no class exists with same fully qualified name as 506 // toplevel package 507 if (checkClash && tree.pid != null) { 508 Symbol p = tree.packge; 509 while (p.owner != syms.rootPackage) { 510 p.owner.complete(); // enter all class members of p 511 if (syms.classes.get(p.getQualifiedName()) != null) { 512 log.error(tree.pos, 513 "pkg.clashes.with.class.of.same.name", 514 p); 515 } 516 p = p.owner; 517 } 518 } 519 520 // process package annotations 521 annotateLater(tree.packageAnnotations, env, tree.packge); 522 523 // Import-on-demand java.lang. 524 importAll(tree.pos, reader.enterPackage(names.java_lang), env); 525 526 // Process all import clauses. 527 memberEnter(tree.defs, env); 528 } 529 530 // process the non-static imports and the static imports of types. 531 public void visitImport(JCImport tree) { 532 JCTree imp = tree.qualid; 533 Name name = TreeInfo.name(imp); 534 TypeSymbol p; 535 536 // Create a local environment pointing to this tree to disable 537 // effects of other imports in Resolve.findGlobalType 538 Env<AttrContext> localEnv = env.dup(tree); 539 540 // Attribute qualifying package or class. 541 JCFieldAccess s = (JCFieldAccess) imp; 542 p = attr. 543 attribTree(s.selected, 544 localEnv, 545 tree.staticImport ? TYP : (TYP | PCK), 546 Type.noType).tsym; 547 if (name == names.asterisk) { 548 // Import on demand. 549 chk.checkCanonical(s.selected); 550 if (tree.staticImport) 551 importStaticAll(tree.pos, p, env); 552 else 553 importAll(tree.pos, p, env); 554 } else { 555 // Named type import. 556 if (tree.staticImport) { 557 importNamedStatic(tree.pos(), p, name, localEnv); 558 chk.checkCanonical(s.selected); 559 } else { 560 TypeSymbol c = attribImportType(imp, localEnv).tsym; 561 chk.checkCanonical(imp); 562 importNamed(tree.pos(), c, env); 563 } 564 } 565 } 566 567 public void visitMethodDef(JCMethodDecl tree) { 568 Scope enclScope = enter.enterScope(env); 569 MethodSymbol m = new MethodSymbol(0, tree.name, null, enclScope.owner); 570 m.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, m, tree); 571 tree.sym = m; 572 Env<AttrContext> localEnv = methodEnv(tree, env); 573 574 DeferredLintHandler prevLintHandler = 575 chk.setDeferredLintHandler(deferredLintHandler.setPos(tree.pos())); 576 try { 577 // Compute the method type 578 m.type = signature(tree.typarams, tree.params, 579 tree.restype, tree.thrown, 580 localEnv); 581 } finally { 582 chk.setDeferredLintHandler(prevLintHandler); 583 } 584 585 // Set m.params 586 ListBuffer<VarSymbol> params = new ListBuffer<VarSymbol>(); 587 JCVariableDecl lastParam = null; 588 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) { 589 JCVariableDecl param = lastParam = l.head; 590 params.append(Assert.checkNonNull(param.sym)); 591 } 592 m.params = params.toList(); 593 594 // mark the method varargs, if necessary 595 if (lastParam != null && (lastParam.mods.flags & Flags.VARARGS) != 0) 596 m.flags_field |= Flags.VARARGS; 597 598 localEnv.info.scope.leave(); 599 if (chk.checkUnique(tree.pos(), m, enclScope)) { 600 enclScope.enter(m); 601 } 602 annotateLater(tree.mods.annotations, localEnv, m); 603 if (tree.defaultValue != null) 604 annotateDefaultValueLater(tree.defaultValue, localEnv, m); 605 } 606 607 /** Create a fresh environment for method bodies. 608 * @param tree The method definition. 609 * @param env The environment current outside of the method definition. 610 */ 611 Env<AttrContext> methodEnv(JCMethodDecl tree, Env<AttrContext> env) { 612 Env<AttrContext> localEnv = 613 env.dup(tree, env.info.dup(env.info.scope.dupUnshared())); 614 localEnv.enclMethod = tree; 615 localEnv.info.scope.owner = tree.sym; 616 if ((tree.mods.flags & STATIC) != 0) localEnv.info.staticLevel++; 617 return localEnv; 618 } 619 620 public void visitVarDef(JCVariableDecl tree) { 621 Env<AttrContext> localEnv = env; 622 if ((tree.mods.flags & STATIC) != 0 || 623 (env.info.scope.owner.flags() & INTERFACE) != 0) { 624 localEnv = env.dup(tree, env.info.dup()); 625 localEnv.info.staticLevel++; 626 } 627 DeferredLintHandler prevLintHandler = 628 chk.setDeferredLintHandler(deferredLintHandler.setPos(tree.pos())); 629 try { 630 attr.attribType(tree.vartype, localEnv); 631 } finally { 632 chk.setDeferredLintHandler(prevLintHandler); 633 } 634 635 if ((tree.mods.flags & VARARGS) != 0) { 636 //if we are entering a varargs parameter, we need to replace its type 637 //(a plain array type) with the more precise VarargsType --- we need 638 //to do it this way because varargs is represented in the tree as a modifier 639 //on the parameter declaration, and not as a distinct type of array node. 640 ArrayType atype = (ArrayType)tree.vartype.type; 641 tree.vartype.type = atype.makeVarargs(); 642 } 643 Scope enclScope = enter.enterScope(env); 644 VarSymbol v = 645 new VarSymbol(0, tree.name, tree.vartype.type, enclScope.owner); 646 v.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, v, tree); 647 tree.sym = v; 648 if (tree.init != null) { 649 v.flags_field |= HASINIT; 650 if ((v.flags_field & FINAL) != 0 && !tree.init.hasTag(NEWCLASS)) { 651 Env<AttrContext> initEnv = getInitEnv(tree, env); 652 initEnv.info.enclVar = v; 653 v.setLazyConstValue(initEnv(tree, initEnv), attr, tree.init); 654 } 655 } 656 if (chk.checkUnique(tree.pos(), v, enclScope)) { 657 chk.checkTransparentVar(tree.pos(), v, enclScope); 658 enclScope.enter(v); 659 } 660 annotateLater(tree.mods.annotations, localEnv, v); 661 v.pos = tree.pos; 662 } 663 664 /** Create a fresh environment for a variable's initializer. 665 * If the variable is a field, the owner of the environment's scope 666 * is be the variable itself, otherwise the owner is the method 667 * enclosing the variable definition. 668 * 669 * @param tree The variable definition. 670 * @param env The environment current outside of the variable definition. 671 */ 672 Env<AttrContext> initEnv(JCVariableDecl tree, Env<AttrContext> env) { 673 Env<AttrContext> localEnv = env.dupto(new AttrContextEnv(tree, env.info.dup())); 674 if (tree.sym.owner.kind == TYP) { 675 localEnv.info.scope = new Scope.DelegatedScope(env.info.scope); 676 localEnv.info.scope.owner = tree.sym; 677 } 678 if ((tree.mods.flags & STATIC) != 0 || 679 (env.enclClass.sym.flags() & INTERFACE) != 0) 680 localEnv.info.staticLevel++; 681 return localEnv; 682 } 683 684 /** Default member enter visitor method: do nothing 685 */ 686 public void visitTree(JCTree tree) { 687 } 688 689 public void visitErroneous(JCErroneous tree) { 690 if (tree.errs != null) 691 memberEnter(tree.errs, env); 692 } 693 694 public Env<AttrContext> getMethodEnv(JCMethodDecl tree, Env<AttrContext> env) { 695 Env<AttrContext> mEnv = methodEnv(tree, env); 696 mEnv.info.lint = mEnv.info.lint.augment(tree.sym.attributes_field, tree.sym.flags()); 697 for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail) 698 mEnv.info.scope.enterIfAbsent(l.head.type.tsym); 699 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) 700 mEnv.info.scope.enterIfAbsent(l.head.sym); 701 return mEnv; 702 } 703 704 public Env<AttrContext> getInitEnv(JCVariableDecl tree, Env<AttrContext> env) { 705 Env<AttrContext> iEnv = initEnv(tree, env); 706 return iEnv; 707 } 708 709 /* ******************************************************************** 710 * Type completion 711 *********************************************************************/ 712 713 Type attribImportType(JCTree tree, Env<AttrContext> env) { 714 Assert.check(completionEnabled); 715 try { 716 // To prevent deep recursion, suppress completion of some 717 // types. 718 completionEnabled = false; 719 return attr.attribType(tree, env); 720 } finally { 721 completionEnabled = true; 722 } 723 } 724 725 /* ******************************************************************** 726 * Annotation processing 727 *********************************************************************/ 728 729 /** Queue annotations for later processing. */ 730 void annotateLater(final List<JCAnnotation> annotations, 731 final Env<AttrContext> localEnv, 732 final Symbol s) { 733 if (annotations.isEmpty()) return; 734 if (s.kind != PCK) s.attributes_field = null; // mark it incomplete for now 735 annotate.later(new Annotate.Annotator() { 736 public String toString() { 737 return "annotate " + annotations + " onto " + s + " in " + s.owner; 738 } 739 public void enterAnnotation() { 740 Assert.check(s.kind == PCK || s.attributes_field == null); 741 JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); 742 try { 743 if (s.attributes_field != null && 744 s.attributes_field.nonEmpty() && 745 annotations.nonEmpty()) 746 log.error(annotations.head.pos, 747 "already.annotated", 748 kindName(s), s); 749 enterAnnotations(annotations, localEnv, s); 750 } finally { 751 log.useSource(prev); 752 } 753 } 754 }); 755 } 756 757 /** 758 * Check if a list of annotations contains a reference to 759 * java.lang.Deprecated. 760 **/ 761 private boolean hasDeprecatedAnnotation(List<JCAnnotation> annotations) { 762 for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) { 763 JCAnnotation a = al.head; 764 if (a.annotationType.type == syms.deprecatedType && a.args.isEmpty()) 765 return true; 766 } 767 return false; 768 } 769 770 771 /** Enter a set of annotations. */ 772 private void enterAnnotations(List<JCAnnotation> annotations, 773 Env<AttrContext> env, 774 Symbol s) { 775 ListBuffer<Attribute.Compound> buf = 776 new ListBuffer<Attribute.Compound>(); 777 Set<TypeSymbol> annotated = new HashSet<TypeSymbol>(); 778 if (!skipAnnotations) 779 for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) { 780 JCAnnotation a = al.head; 781 Attribute.Compound c = annotate.enterAnnotation(a, 782 syms.annotationType, 783 env); 784 if (c == null) continue; 785 buf.append(c); 786 // Note: @Deprecated has no effect on local variables and parameters 787 if (!c.type.isErroneous() 788 && s.owner.kind != MTH 789 && types.isSameType(c.type, syms.deprecatedType)) 790 s.flags_field |= Flags.DEPRECATED; 791 // Internally to java.lang.invoke, a @PolymorphicSignature annotation 792 // acts like a classfile attribute. 793 if (!c.type.isErroneous() && 794 types.isSameType(c.type, syms.polymorphicSignatureType)) { 795 if (!target.hasMethodHandles()) { 796 // Somebody is compiling JDK7 source code to a JDK6 target. 797 // Make it an error, since it is unlikely but important. 798 log.error(env.tree.pos(), 799 "wrong.target.for.polymorphic.signature.definition", 800 target.name); 801 } 802 // Pull the flag through for better diagnostics, even on a bad target. 803 s.flags_field |= Flags.POLYMORPHIC_SIGNATURE; 804 } 805 if (!annotated.add(a.type.tsym)) 806 log.error(a.pos, "duplicate.annotation"); 807 } 808 s.attributes_field = buf.toList(); 809 } 810 811 /** Queue processing of an attribute default value. */ 812 void annotateDefaultValueLater(final JCExpression defaultValue, 813 final Env<AttrContext> localEnv, 814 final MethodSymbol m) { 815 annotate.later(new Annotate.Annotator() { 816 public String toString() { 817 return "annotate " + m.owner + "." + 818 m + " default " + defaultValue; 819 } 820 public void enterAnnotation() { 821 JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); 822 try { 823 enterDefaultValue(defaultValue, localEnv, m); 824 } finally { 825 log.useSource(prev); 826 } 827 } 828 }); 829 } 830 831 /** Enter a default value for an attribute method. */ 832 private void enterDefaultValue(final JCExpression defaultValue, 833 final Env<AttrContext> localEnv, 834 final MethodSymbol m) { 835 m.defaultValue = annotate.enterAttributeValue(m.type.getReturnType(), 836 defaultValue, 837 localEnv); 838 } 839 840 /* ******************************************************************** 841 * Source completer 842 *********************************************************************/ 843 844 /** Complete entering a class. 845 * @param sym The symbol of the class to be completed. 846 */ 847 public void complete(Symbol sym) throws CompletionFailure { 848 // Suppress some (recursive) MemberEnter invocations 849 if (!completionEnabled) { 850 // Re-install same completer for next time around and return. 851 Assert.check((sym.flags() & Flags.COMPOUND) == 0); 852 sym.completer = this; 853 return; 854 } 855 856 ClassSymbol c = (ClassSymbol)sym; 857 ClassType ct = (ClassType)c.type; 858 Env<AttrContext> env = enter.typeEnvs.get(c); 859 JCClassDecl tree = (JCClassDecl)env.tree; 860 boolean wasFirst = isFirst; 861 isFirst = false; 862 863 JavaFileObject prev = log.useSource(env.toplevel.sourcefile); 864 try { 865 // Save class environment for later member enter (2) processing. 866 halfcompleted.append(env); 867 868 // Mark class as not yet attributed. 869 c.flags_field |= UNATTRIBUTED; 870 871 // If this is a toplevel-class, make sure any preceding import 872 // clauses have been seen. 873 if (c.owner.kind == PCK) { 874 memberEnter(env.toplevel, env.enclosing(TOPLEVEL)); 875 todo.append(env); 876 } 877 878 if (c.owner.kind == TYP) 879 c.owner.complete(); 880 881 // create an environment for evaluating the base clauses 882 Env<AttrContext> baseEnv = baseEnv(tree, env); 883 884 // Determine supertype. 885 Type supertype = 886 (tree.extending != null) 887 ? attr.attribBase(tree.extending, baseEnv, true, false, true) 888 : ((tree.mods.flags & Flags.ENUM) != 0 && !target.compilerBootstrap(c)) 889 ? attr.attribBase(enumBase(tree.pos, c), baseEnv, 890 true, false, false) 891 : (c.fullname == names.java_lang_Object) 892 ? Type.noType 893 : syms.objectType; 894 ct.supertype_field = modelMissingTypes(supertype, tree.extending, false); 895 896 // Determine interfaces. 897 ListBuffer<Type> interfaces = new ListBuffer<Type>(); 898 ListBuffer<Type> all_interfaces = null; // lazy init 899 Set<Type> interfaceSet = new HashSet<Type>(); 900 List<JCExpression> interfaceTrees = tree.implementing; 901 if ((tree.mods.flags & Flags.ENUM) != 0 && target.compilerBootstrap(c)) { 902 // add interface Comparable<T> 903 interfaceTrees = 904 interfaceTrees.prepend(make.Type(new ClassType(syms.comparableType.getEnclosingType(), 905 List.of(c.type), 906 syms.comparableType.tsym))); 907 // add interface Serializable 908 interfaceTrees = 909 interfaceTrees.prepend(make.Type(syms.serializableType)); 910 } 911 for (JCExpression iface : interfaceTrees) { 912 Type i = attr.attribBase(iface, baseEnv, false, true, true); 913 if (i.tag == CLASS) { 914 interfaces.append(i); 915 if (all_interfaces != null) all_interfaces.append(i); 916 chk.checkNotRepeated(iface.pos(), types.erasure(i), interfaceSet); 917 } else { 918 if (all_interfaces == null) 919 all_interfaces = new ListBuffer<Type>().appendList(interfaces); 920 all_interfaces.append(modelMissingTypes(i, iface, true)); 921 } 922 } 923 if ((c.flags_field & ANNOTATION) != 0) { 924 ct.interfaces_field = List.of(syms.annotationType); 925 ct.all_interfaces_field = ct.interfaces_field; 926 } else { 927 ct.interfaces_field = interfaces.toList(); 928 ct.all_interfaces_field = (all_interfaces == null) 929 ? ct.interfaces_field : all_interfaces.toList(); 930 } 931 932 if (c.fullname == names.java_lang_Object) { 933 if (tree.extending != null) { 934 chk.checkNonCyclic(tree.extending.pos(), 935 supertype); 936 ct.supertype_field = Type.noType; 937 } 938 else if (tree.implementing.nonEmpty()) { 939 chk.checkNonCyclic(tree.implementing.head.pos(), 940 ct.interfaces_field.head); 941 ct.interfaces_field = List.nil(); 942 } 943 } 944 945 // Annotations. 946 // In general, we cannot fully process annotations yet, but we 947 // can attribute the annotation types and then check to see if the 948 // @Deprecated annotation is present. 949 attr.attribAnnotationTypes(tree.mods.annotations, baseEnv); 950 if (hasDeprecatedAnnotation(tree.mods.annotations)) 951 c.flags_field |= DEPRECATED; 952 annotateLater(tree.mods.annotations, baseEnv, c); 953 954 chk.checkNonCyclicDecl(tree); 955 956 attr.attribTypeVariables(tree.typarams, baseEnv); 957 958 // Add default constructor if needed. 959 if ((c.flags() & INTERFACE) == 0 && 960 !TreeInfo.hasConstructors(tree.defs)) { 961 List<Type> argtypes = List.nil(); 962 List<Type> typarams = List.nil(); 963 List<Type> thrown = List.nil(); 964 long ctorFlags = 0; 965 boolean based = false; 966 if (c.name.isEmpty()) { 967 JCNewClass nc = (JCNewClass)env.next.tree; 968 if (nc.constructor != null) { 969 Type superConstrType = types.memberType(c.type, 970 nc.constructor); 971 argtypes = superConstrType.getParameterTypes(); 972 typarams = superConstrType.getTypeArguments(); 973 ctorFlags = nc.constructor.flags() & VARARGS; 974 if (nc.encl != null) { 975 argtypes = argtypes.prepend(nc.encl.type); 976 based = true; 977 } 978 thrown = superConstrType.getThrownTypes(); 979 } 980 } 981 JCTree constrDef = DefaultConstructor(make.at(tree.pos), c, 982 typarams, argtypes, thrown, 983 ctorFlags, based); 984 tree.defs = tree.defs.prepend(constrDef); 985 } 986 987 // If this is a class, enter symbols for this and super into 988 // current scope. 989 if ((c.flags_field & INTERFACE) == 0) { 990 VarSymbol thisSym = 991 new VarSymbol(FINAL | HASINIT, names._this, c.type, c); 992 thisSym.pos = Position.FIRSTPOS; 993 env.info.scope.enter(thisSym); 994 if (ct.supertype_field.tag == CLASS) { 995 VarSymbol superSym = 996 new VarSymbol(FINAL | HASINIT, names._super, 997 ct.supertype_field, c); 998 superSym.pos = Position.FIRSTPOS; 999 env.info.scope.enter(superSym); 1000 } 1001 } 1002 1003 // check that no package exists with same fully qualified name, 1004 // but admit classes in the unnamed package which have the same 1005 // name as a top-level package. 1006 if (checkClash && 1007 c.owner.kind == PCK && c.owner != syms.unnamedPackage && 1008 reader.packageExists(c.fullname)) 1009 { 1010 log.error(tree.pos, "clash.with.pkg.of.same.name", Kinds.kindName(sym), c); 1011 } 1012 1013 } catch (CompletionFailure ex) { 1014 chk.completionError(tree.pos(), ex); 1015 } finally { 1016 log.useSource(prev); 1017 } 1018 1019 // Enter all member fields and methods of a set of half completed 1020 // classes in a second phase. 1021 if (wasFirst) { 1022 try { 1023 while (halfcompleted.nonEmpty()) { 1024 finish(halfcompleted.next()); 1025 } 1026 } finally { 1027 isFirst = true; 1028 } 1029 1030 // commit pending annotations 1031 annotate.flush(); 1032 } 1033 } 1034 1035 private Env<AttrContext> baseEnv(JCClassDecl tree, Env<AttrContext> env) { 1036 Scope baseScope = new Scope(tree.sym); 1037 //import already entered local classes into base scope 1038 for (Scope.Entry e = env.outer.info.scope.elems ; e != null ; e = e.sibling) { 1039 if (e.sym.isLocal()) { 1040 baseScope.enter(e.sym); 1041 } 1042 } 1043 //import current type-parameters into base scope 1044 if (tree.typarams != null) 1045 for (List<JCTypeParameter> typarams = tree.typarams; 1046 typarams.nonEmpty(); 1047 typarams = typarams.tail) 1048 baseScope.enter(typarams.head.type.tsym); 1049 Env<AttrContext> outer = env.outer; // the base clause can't see members of this class 1050 Env<AttrContext> localEnv = outer.dup(tree, outer.info.dup(baseScope)); 1051 localEnv.baseClause = true; 1052 localEnv.outer = outer; 1053 localEnv.info.isSelfCall = false; 1054 return localEnv; 1055 } 1056 1057 /** Enter member fields and methods of a class 1058 * @param env the environment current for the class block. 1059 */ 1060 private void finish(Env<AttrContext> env) { 1061 JavaFileObject prev = log.useSource(env.toplevel.sourcefile); 1062 try { 1063 JCClassDecl tree = (JCClassDecl)env.tree; 1064 finishClass(tree, env); 1065 } finally { 1066 log.useSource(prev); 1067 } 1068 } 1069 1070 /** Generate a base clause for an enum type. 1071 * @param pos The position for trees and diagnostics, if any 1072 * @param c The class symbol of the enum 1073 */ 1074 private JCExpression enumBase(int pos, ClassSymbol c) { 1075 JCExpression result = make.at(pos). 1076 TypeApply(make.QualIdent(syms.enumSym), 1077 List.<JCExpression>of(make.Type(c.type))); 1078 return result; 1079 } 1080 1081 Type modelMissingTypes(Type t, final JCExpression tree, final boolean interfaceExpected) { 1082 if (t.tag != ERROR) 1083 return t; 1084 1085 return new ErrorType(((ErrorType) t).getOriginalType(), t.tsym) { 1086 private Type modelType; 1087 1088 @Override 1089 public Type getModelType() { 1090 if (modelType == null) 1091 modelType = new Synthesizer(getOriginalType(), interfaceExpected).visit(tree); 1092 return modelType; 1093 } 1094 }; 1095 } 1096 // where 1097 private class Synthesizer extends JCTree.Visitor { 1098 Type originalType; 1099 boolean interfaceExpected; 1100 List<ClassSymbol> synthesizedSymbols = List.nil(); 1101 Type result; 1102 1103 Synthesizer(Type originalType, boolean interfaceExpected) { 1104 this.originalType = originalType; 1105 this.interfaceExpected = interfaceExpected; 1106 } 1107 1108 Type visit(JCTree tree) { 1109 tree.accept(this); 1110 return result; 1111 } 1112 1113 List<Type> visit(List<? extends JCTree> trees) { 1114 ListBuffer<Type> lb = new ListBuffer<Type>(); 1115 for (JCTree t: trees) 1116 lb.append(visit(t)); 1117 return lb.toList(); 1118 } 1119 1120 @Override 1121 public void visitTree(JCTree tree) { 1122 result = syms.errType; 1123 } 1124 1125 @Override 1126 public void visitIdent(JCIdent tree) { 1127 if (tree.type.tag != ERROR) { 1128 result = tree.type; 1129 } else { 1130 result = synthesizeClass(tree.name, syms.unnamedPackage).type; 1131 } 1132 } 1133 1134 @Override 1135 public void visitSelect(JCFieldAccess tree) { 1136 if (tree.type.tag != ERROR) { 1137 result = tree.type; 1138 } else { 1139 Type selectedType; 1140 boolean prev = interfaceExpected; 1141 try { 1142 interfaceExpected = false; 1143 selectedType = visit(tree.selected); 1144 } finally { 1145 interfaceExpected = prev; 1146 } 1147 ClassSymbol c = synthesizeClass(tree.name, selectedType.tsym); 1148 result = c.type; 1149 } 1150 } 1151 1152 @Override 1153 public void visitTypeApply(JCTypeApply tree) { 1154 if (tree.type.tag != ERROR) { 1155 result = tree.type; 1156 } else { 1157 ClassType clazzType = (ClassType) visit(tree.clazz); 1158 if (synthesizedSymbols.contains(clazzType.tsym)) 1159 synthesizeTyparams((ClassSymbol) clazzType.tsym, tree.arguments.size()); 1160 final List<Type> actuals = visit(tree.arguments); 1161 result = new ErrorType(tree.type, clazzType.tsym) { 1162 @Override 1163 public List<Type> getTypeArguments() { 1164 return actuals; 1165 } 1166 }; 1167 } 1168 } 1169 1170 ClassSymbol synthesizeClass(Name name, Symbol owner) { 1171 int flags = interfaceExpected ? INTERFACE : 0; 1172 ClassSymbol c = new ClassSymbol(flags, name, owner); 1173 c.members_field = new Scope.ErrorScope(c); 1174 c.type = new ErrorType(originalType, c) { 1175 @Override 1176 public List<Type> getTypeArguments() { 1177 return typarams_field; 1178 } 1179 }; 1180 synthesizedSymbols = synthesizedSymbols.prepend(c); 1181 return c; 1182 } 1183 1184 void synthesizeTyparams(ClassSymbol sym, int n) { 1185 ClassType ct = (ClassType) sym.type; 1186 Assert.check(ct.typarams_field.isEmpty()); 1187 if (n == 1) { 1188 TypeVar v = new TypeVar(names.fromString("T"), sym, syms.botType); 1189 ct.typarams_field = ct.typarams_field.prepend(v); 1190 } else { 1191 for (int i = n; i > 0; i--) { 1192 TypeVar v = new TypeVar(names.fromString("T" + i), sym, syms.botType); 1193 ct.typarams_field = ct.typarams_field.prepend(v); 1194 } 1195 } 1196 } 1197 } 1198 1199 1200 /* *************************************************************************** 1201 * tree building 1202 ****************************************************************************/ 1203 1204 /** Generate default constructor for given class. For classes different 1205 * from java.lang.Object, this is: 1206 * 1207 * c(argtype_0 x_0, ..., argtype_n x_n) throws thrown { 1208 * super(x_0, ..., x_n) 1209 * } 1210 * 1211 * or, if based == true: 1212 * 1213 * c(argtype_0 x_0, ..., argtype_n x_n) throws thrown { 1214 * x_0.super(x_1, ..., x_n) 1215 * } 1216 * 1217 * @param make The tree factory. 1218 * @param c The class owning the default constructor. 1219 * @param argtypes The parameter types of the constructor. 1220 * @param thrown The thrown exceptions of the constructor. 1221 * @param based Is first parameter a this$n? 1222 */ 1223 JCTree DefaultConstructor(TreeMaker make, 1224 ClassSymbol c, 1225 List<Type> typarams, 1226 List<Type> argtypes, 1227 List<Type> thrown, 1228 long flags, 1229 boolean based) { 1230 List<JCVariableDecl> params = make.Params(argtypes, syms.noSymbol); 1231 List<JCStatement> stats = List.nil(); 1232 if (c.type != syms.objectType) 1233 stats = stats.prepend(SuperCall(make, typarams, params, based)); 1234 if ((c.flags() & ENUM) != 0 && 1235 (types.supertype(c.type).tsym == syms.enumSym || 1236 target.compilerBootstrap(c))) { 1237 // constructors of true enums are private 1238 flags = (flags & ~AccessFlags) | PRIVATE | GENERATEDCONSTR; 1239 } else 1240 flags |= (c.flags() & AccessFlags) | GENERATEDCONSTR; 1241 if (c.name.isEmpty()) flags |= ANONCONSTR; 1242 JCTree result = make.MethodDef( 1243 make.Modifiers(flags), 1244 names.init, 1245 null, 1246 make.TypeParams(typarams), 1247 params, 1248 make.Types(thrown), 1249 make.Block(0, stats), 1250 null); 1251 return result; 1252 } 1253 1254 /** Generate call to superclass constructor. This is: 1255 * 1256 * super(id_0, ..., id_n) 1257 * 1258 * or, if based == true 1259 * 1260 * id_0.super(id_1,...,id_n) 1261 * 1262 * where id_0, ..., id_n are the names of the given parameters. 1263 * 1264 * @param make The tree factory 1265 * @param params The parameters that need to be passed to super 1266 * @param typarams The type parameters that need to be passed to super 1267 * @param based Is first parameter a this$n? 1268 */ 1269 JCExpressionStatement SuperCall(TreeMaker make, 1270 List<Type> typarams, 1271 List<JCVariableDecl> params, 1272 boolean based) { 1273 JCExpression meth; 1274 if (based) { 1275 meth = make.Select(make.Ident(params.head), names._super); 1276 params = params.tail; 1277 } else { 1278 meth = make.Ident(names._super); 1279 } 1280 List<JCExpression> typeargs = typarams.nonEmpty() ? make.Types(typarams) : null; 1281 return make.Exec(make.Apply(typeargs, meth, make.Idents(params))); 1282 } 1283 }