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