1 /* 2 * Copyright (c) 2003, 2013, 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.HashMap; 29 import java.util.HashSet; 30 import java.util.LinkedHashMap; 31 import java.util.Map; 32 import java.util.Set; 33 34 import javax.lang.model.type.TypeKind; 35 import javax.tools.JavaFileObject; 36 37 import com.sun.tools.javac.code.*; 38 import com.sun.tools.javac.jvm.*; 39 import com.sun.tools.javac.tree.*; 40 import com.sun.tools.javac.util.*; 41 42 import com.sun.tools.javac.code.Type.*; 43 import com.sun.tools.javac.code.Symbol.*; 44 import com.sun.tools.javac.tree.JCTree.*; 45 46 import static com.sun.tools.javac.code.Flags.*; 47 import static com.sun.tools.javac.code.Flags.ANNOTATION; 48 import static com.sun.tools.javac.code.Kinds.*; 49 import static com.sun.tools.javac.code.TypeTag.CLASS; 50 import static com.sun.tools.javac.code.TypeTag.ERROR; 51 import static com.sun.tools.javac.code.TypeTag.TYPEVAR; 52 import static com.sun.tools.javac.tree.JCTree.Tag.*; 53 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticFlag; 54 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; 55 56 /** This is the second phase of Enter, in which classes are completed 57 * by entering their members into the class scope using 58 * MemberEnter.complete(). See Enter for an overview. 59 * 60 * <p><b>This is NOT part of any supported API. 61 * If you write code that depends on this, you do so at your own risk. 62 * This code and its internal interfaces are subject to change or 63 * deletion without notice.</b> 64 */ 65 public class MemberEnter extends JCTree.Visitor implements Completer { 66 protected static final Context.Key<MemberEnter> memberEnterKey = 67 new Context.Key<MemberEnter>(); 68 69 /** A switch to determine whether we check for package/class conflicts 70 */ 71 final static boolean checkClash = true; 72 73 private final Names names; 74 private final Enter enter; 75 private final Log log; 76 private final Check chk; 77 private final Attr attr; 78 private final Symtab syms; 79 private final TreeMaker make; 80 private final ClassReader reader; 81 private final Todo todo; 82 private final Annotate annotate; 83 private final Types types; 84 private final JCDiagnostic.Factory diags; 85 private final Source source; 86 private final Target target; 87 private final DeferredLintHandler deferredLintHandler; 88 89 public static MemberEnter instance(Context context) { 90 MemberEnter instance = context.get(memberEnterKey); 91 if (instance == null) 92 instance = new MemberEnter(context); 93 return instance; 94 } 95 96 protected MemberEnter(Context context) { 97 context.put(memberEnterKey, this); 98 names = Names.instance(context); 99 enter = Enter.instance(context); 100 log = Log.instance(context); 101 chk = Check.instance(context); 102 attr = Attr.instance(context); 103 syms = Symtab.instance(context); 104 make = TreeMaker.instance(context); 105 reader = ClassReader.instance(context); 106 todo = Todo.instance(context); 107 annotate = Annotate.instance(context); 108 types = Types.instance(context); 109 diags = JCDiagnostic.Factory.instance(context); 110 source = Source.instance(context); 111 target = Target.instance(context); 112 deferredLintHandler = DeferredLintHandler.instance(context); 113 } 114 115 /** A queue for classes whose members still need to be entered into the 116 * symbol table. 117 */ 118 ListBuffer<Env<AttrContext>> halfcompleted = new ListBuffer<Env<AttrContext>>(); 119 120 /** Set to true only when the first of a set of classes is 121 * processed from the halfcompleted queue. 122 */ 123 boolean isFirst = true; 124 125 /** A flag to disable completion from time to time during member 126 * enter, as we only need to look up types. This avoids 127 * unnecessarily deep recursion. 128 */ 129 boolean completionEnabled = true; 130 131 /* ---------- Processing import clauses ---------------- 132 */ 133 134 /** Import all classes of a class or package on demand. 135 * @param pos Position to be used for error reporting. 136 * @param tsym The class or package the members of which are imported. 137 * @param env The env in which the imported classes will be entered. 138 */ 139 private void importAll(int pos, 140 final TypeSymbol tsym, 141 Env<AttrContext> env) { 142 // Check that packages imported from exist (JLS ???). 143 if (tsym.kind == PCK && tsym.members().elems == null && !tsym.exists()) { 144 // If we can't find java.lang, exit immediately. 145 if (((PackageSymbol)tsym).fullname.equals(names.java_lang)) { 146 JCDiagnostic msg = diags.fragment("fatal.err.no.java.lang"); 147 throw new FatalError(msg); 148 } else { 149 log.error(DiagnosticFlag.RESOLVE_ERROR, pos, "doesnt.exist", tsym); 150 } 151 } 152 env.toplevel.starImportScope.importAll(tsym.members()); 153 } 154 155 /** Import all static members of a class or package on demand. 156 * @param pos Position to be used for error reporting. 157 * @param tsym The class or package the members of which are imported. 158 * @param env The env in which the imported classes will be 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(DiagnosticFlag.RECOVERABLE, 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 recvparam The method's receiver parameter, 353 * null if none given; TODO: or already set here? 354 * @param thrown The method's thrown exceptions. 355 * @param env The method's (local) environment. 356 */ 357 Type signature(List<JCTypeParameter> typarams, 358 List<JCVariableDecl> params, 359 JCTree res, 360 JCVariableDecl recvparam, 361 List<JCExpression> thrown, 362 Env<AttrContext> env) { 363 364 // Enter and attribute type parameters. 365 List<Type> tvars = enter.classEnter(typarams, env); 366 attr.attribTypeVariables(typarams, env); 367 368 // Enter and attribute value parameters. 369 ListBuffer<Type> argbuf = new ListBuffer<Type>(); 370 for (List<JCVariableDecl> l = params; l.nonEmpty(); l = l.tail) { 371 memberEnter(l.head, env); 372 argbuf.append(l.head.vartype.type); 373 } 374 375 // Attribute result type, if one is given. 376 Type restype = res == null ? syms.voidType : attr.attribType(res, env); 377 378 // Attribute receiver type, if one is given. 379 Type recvtype; 380 if (recvparam!=null) { 381 memberEnter(recvparam, env); 382 recvtype = recvparam.vartype.type; 383 } else { 384 recvtype = null; 385 } 386 387 // Attribute thrown exceptions. 388 ListBuffer<Type> thrownbuf = new ListBuffer<Type>(); 389 for (List<JCExpression> l = thrown; l.nonEmpty(); l = l.tail) { 390 Type exc = attr.attribType(l.head, env); 391 if (!exc.hasTag(TYPEVAR)) 392 exc = chk.checkClassType(l.head.pos(), exc); 393 thrownbuf.append(exc); 394 } 395 MethodType mtype = new MethodType(argbuf.toList(), 396 restype, 397 thrownbuf.toList(), 398 syms.methodClass); 399 mtype.recvtype = recvtype; 400 401 return tvars.isEmpty() ? mtype : new ForAll(tvars, mtype); 402 } 403 404 /* ******************************************************************** 405 * Visitor methods for member enter 406 *********************************************************************/ 407 408 /** Visitor argument: the current environment 409 */ 410 protected Env<AttrContext> env; 411 412 /** Enter field and method definitions and process import 413 * clauses, catching any completion failure exceptions. 414 */ 415 protected void memberEnter(JCTree tree, Env<AttrContext> env) { 416 Env<AttrContext> prevEnv = this.env; 417 try { 418 this.env = env; 419 tree.accept(this); 420 } catch (CompletionFailure ex) { 421 chk.completionError(tree.pos(), ex); 422 } finally { 423 this.env = prevEnv; 424 } 425 } 426 427 /** Enter members from a list of trees. 428 */ 429 void memberEnter(List<? extends JCTree> trees, Env<AttrContext> env) { 430 for (List<? extends JCTree> l = trees; l.nonEmpty(); l = l.tail) 431 memberEnter(l.head, env); 432 } 433 434 /** Enter members for a class. 435 */ 436 void finishClass(JCClassDecl tree, Env<AttrContext> env) { 437 if ((tree.mods.flags & Flags.ENUM) != 0 && 438 (types.supertype(tree.sym.type).tsym.flags() & Flags.ENUM) == 0) { 439 addEnumMembers(tree, env); 440 } 441 memberEnter(tree.defs, env); 442 } 443 444 /** Add the implicit members for an enum type 445 * to the symbol table. 446 */ 447 private void addEnumMembers(JCClassDecl tree, Env<AttrContext> env) { 448 JCExpression valuesType = make.Type(new ArrayType(tree.sym.type, syms.arrayClass)); 449 450 // public static T[] values() { return ???; } 451 JCMethodDecl values = make. 452 MethodDef(make.Modifiers(Flags.PUBLIC|Flags.STATIC), 453 names.values, 454 valuesType, 455 List.<JCTypeParameter>nil(), 456 List.<JCVariableDecl>nil(), 457 List.<JCExpression>nil(), // thrown 458 null, //make.Block(0, Tree.emptyList.prepend(make.Return(make.Ident(names._null)))), 459 null); 460 memberEnter(values, env); 461 462 // public static T valueOf(String name) { return ???; } 463 JCMethodDecl valueOf = make. 464 MethodDef(make.Modifiers(Flags.PUBLIC|Flags.STATIC), 465 names.valueOf, 466 make.Type(tree.sym.type), 467 List.<JCTypeParameter>nil(), 468 List.of(make.VarDef(make.Modifiers(Flags.PARAMETER | 469 Flags.MANDATED), 470 names.fromString("name"), 471 make.Type(syms.stringType), null)), 472 List.<JCExpression>nil(), // thrown 473 null, //make.Block(0, Tree.emptyList.prepend(make.Return(make.Ident(names._null)))), 474 null); 475 memberEnter(valueOf, env); 476 477 // the remaining members are for bootstrapping only 478 if (!target.compilerBootstrap(tree.sym)) return; 479 480 // public final int ordinal() { return ???; } 481 JCMethodDecl ordinal = make.at(tree.pos). 482 MethodDef(make.Modifiers(Flags.PUBLIC|Flags.FINAL), 483 names.ordinal, 484 make.Type(syms.intType), 485 List.<JCTypeParameter>nil(), 486 List.<JCVariableDecl>nil(), 487 List.<JCExpression>nil(), 488 null, 489 null); 490 memberEnter(ordinal, env); 491 492 // public final String name() { return ???; } 493 JCMethodDecl name = make. 494 MethodDef(make.Modifiers(Flags.PUBLIC|Flags.FINAL), 495 names._name, 496 make.Type(syms.stringType), 497 List.<JCTypeParameter>nil(), 498 List.<JCVariableDecl>nil(), 499 List.<JCExpression>nil(), 500 null, 501 null); 502 memberEnter(name, env); 503 504 // public int compareTo(E other) { return ???; } 505 MethodSymbol compareTo = new 506 MethodSymbol(Flags.PUBLIC, 507 names.compareTo, 508 new MethodType(List.of(tree.sym.type), 509 syms.intType, 510 List.<Type>nil(), 511 syms.methodClass), 512 tree.sym); 513 memberEnter(make.MethodDef(compareTo, null), env); 514 } 515 516 public void visitTopLevel(JCCompilationUnit tree) { 517 if (tree.starImportScope.elems != null) { 518 // we must have already processed this toplevel 519 return; 520 } 521 522 // check that no class exists with same fully qualified name as 523 // toplevel package 524 if (checkClash && tree.pid != null) { 525 Symbol p = tree.packge; 526 while (p.owner != syms.rootPackage) { 527 p.owner.complete(); // enter all class members of p 528 if (syms.classes.get(p.getQualifiedName()) != null) { 529 log.error(tree.pos, 530 "pkg.clashes.with.class.of.same.name", 531 p); 532 } 533 p = p.owner; 534 } 535 } 536 537 // process package annotations 538 annotateLater(tree.packageAnnotations, env, tree.packge); 539 540 // Import-on-demand java.lang. 541 importAll(tree.pos, reader.enterPackage(names.java_lang), env); 542 543 // Process all import clauses. 544 memberEnter(tree.defs, env); 545 } 546 547 // process the non-static imports and the static imports of types. 548 public void visitImport(JCImport tree) { 549 JCFieldAccess imp = (JCFieldAccess)tree.qualid; 550 Name name = TreeInfo.name(imp); 551 552 // Create a local environment pointing to this tree to disable 553 // effects of other imports in Resolve.findGlobalType 554 Env<AttrContext> localEnv = env.dup(tree); 555 556 TypeSymbol p = attr.attribImportQualifier(tree, localEnv).tsym; 557 if (name == names.asterisk) { 558 // Import on demand. 559 chk.checkCanonical(imp.selected); 560 if (tree.staticImport) 561 importStaticAll(tree.pos, p, env); 562 else 563 importAll(tree.pos, p, env); 564 } else { 565 // Named type import. 566 if (tree.staticImport) { 567 importNamedStatic(tree.pos(), p, name, localEnv); 568 chk.checkCanonical(imp.selected); 569 } else { 570 TypeSymbol c = attribImportType(imp, localEnv).tsym; 571 chk.checkCanonical(imp); 572 importNamed(tree.pos(), c, env); 573 } 574 } 575 } 576 577 public void visitMethodDef(JCMethodDecl tree) { 578 Scope enclScope = enter.enterScope(env); 579 MethodSymbol m = new MethodSymbol(0, tree.name, null, enclScope.owner); 580 m.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, m, tree); 581 tree.sym = m; 582 583 //if this is a default method, add the DEFAULT flag to the enclosing interface 584 if ((tree.mods.flags & DEFAULT) != 0) { 585 m.enclClass().flags_field |= DEFAULT; 586 } 587 588 Env<AttrContext> localEnv = methodEnv(tree, env); 589 590 DeferredLintHandler prevLintHandler = 591 chk.setDeferredLintHandler(deferredLintHandler.setPos(tree.pos())); 592 try { 593 // Compute the method type 594 m.type = signature(tree.typarams, tree.params, 595 tree.restype, tree.recvparam, 596 tree.thrown, 597 localEnv); 598 } finally { 599 chk.setDeferredLintHandler(prevLintHandler); 600 } 601 602 // Set m.params 603 ListBuffer<VarSymbol> params = new ListBuffer<VarSymbol>(); 604 JCVariableDecl lastParam = null; 605 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) { 606 JCVariableDecl param = lastParam = l.head; 607 params.append(Assert.checkNonNull(param.sym)); 608 } 609 m.params = params.toList(); 610 611 // mark the method varargs, if necessary 612 if (lastParam != null && (lastParam.mods.flags & Flags.VARARGS) != 0) 613 m.flags_field |= Flags.VARARGS; 614 615 localEnv.info.scope.leave(); 616 if (chk.checkUnique(tree.pos(), m, enclScope)) { 617 enclScope.enter(m); 618 } 619 annotateLater(tree.mods.annotations, localEnv, m); 620 // Visit the signature of the method. Note that 621 // TypeAnnotate doesn't descend into the body. 622 typeAnnotate(tree, localEnv, m); 623 624 if (tree.defaultValue != null) 625 annotateDefaultValueLater(tree.defaultValue, localEnv, m); 626 } 627 628 /** Create a fresh environment for method bodies. 629 * @param tree The method definition. 630 * @param env The environment current outside of the method definition. 631 */ 632 Env<AttrContext> methodEnv(JCMethodDecl tree, Env<AttrContext> env) { 633 Env<AttrContext> localEnv = 634 env.dup(tree, env.info.dup(env.info.scope.dupUnshared())); 635 localEnv.enclMethod = tree; 636 localEnv.info.scope.owner = tree.sym; 637 if (tree.sym.type != null) { 638 //when this is called in the enter stage, there's no type to be set 639 localEnv.info.returnResult = attr.new ResultInfo(VAL, tree.sym.type.getReturnType()); 640 } 641 if ((tree.mods.flags & STATIC) != 0) localEnv.info.staticLevel++; 642 return localEnv; 643 } 644 645 public void visitVarDef(JCVariableDecl tree) { 646 Env<AttrContext> localEnv = env; 647 if ((tree.mods.flags & STATIC) != 0 || 648 (env.info.scope.owner.flags() & INTERFACE) != 0) { 649 localEnv = env.dup(tree, env.info.dup()); 650 localEnv.info.staticLevel++; 651 } 652 DeferredLintHandler prevLintHandler = 653 chk.setDeferredLintHandler(deferredLintHandler.setPos(tree.pos())); 654 try { 655 if (TreeInfo.isEnumInit(tree)) { 656 attr.attribIdentAsEnumType(localEnv, (JCIdent)tree.vartype); 657 } else { 658 attr.attribType(tree.vartype, localEnv); 659 } 660 } finally { 661 chk.setDeferredLintHandler(prevLintHandler); 662 } 663 664 if ((tree.mods.flags & VARARGS) != 0) { 665 //if we are entering a varargs parameter, we need to replace its type 666 //(a plain array type) with the more precise VarargsType --- we need 667 //to do it this way because varargs is represented in the tree as a modifier 668 //on the parameter declaration, and not as a distinct type of array node. 669 ArrayType atype = (ArrayType)tree.vartype.type.unannotatedType(); 670 tree.vartype.type = atype.makeVarargs(); 671 } 672 Scope enclScope = enter.enterScope(env); 673 VarSymbol v = 674 new VarSymbol(0, tree.name, tree.vartype.type, enclScope.owner); 675 v.flags_field = chk.checkFlags(tree.pos(), tree.mods.flags, v, tree); 676 tree.sym = v; 677 if (tree.init != null) { 678 v.flags_field |= HASINIT; 679 if ((v.flags_field & FINAL) != 0 && 680 !tree.init.hasTag(NEWCLASS) && 681 !tree.init.hasTag(LAMBDA)) { 682 Env<AttrContext> initEnv = getInitEnv(tree, env); 683 initEnv.info.enclVar = v; 684 v.setLazyConstValue(initEnv(tree, initEnv), attr, tree.init); 685 } 686 } 687 if (chk.checkUnique(tree.pos(), v, enclScope)) { 688 chk.checkTransparentVar(tree.pos(), v, enclScope); 689 enclScope.enter(v); 690 } 691 annotateLater(tree.mods.annotations, localEnv, v); 692 typeAnnotate(tree.vartype, env, tree.sym); 693 annotate.flush(); 694 v.pos = tree.pos; 695 } 696 697 /** Create a fresh environment for a variable's initializer. 698 * If the variable is a field, the owner of the environment's scope 699 * is be the variable itself, otherwise the owner is the method 700 * enclosing the variable definition. 701 * 702 * @param tree The variable definition. 703 * @param env The environment current outside of the variable definition. 704 */ 705 Env<AttrContext> initEnv(JCVariableDecl tree, Env<AttrContext> env) { 706 Env<AttrContext> localEnv = env.dupto(new AttrContextEnv(tree, env.info.dup())); 707 if (tree.sym.owner.kind == TYP) { 708 localEnv.info.scope = env.info.scope.dupUnshared(); 709 localEnv.info.scope.owner = tree.sym; 710 } 711 if ((tree.mods.flags & STATIC) != 0 || 712 ((env.enclClass.sym.flags() & INTERFACE) != 0 && env.enclMethod == null)) 713 localEnv.info.staticLevel++; 714 return localEnv; 715 } 716 717 /** Default member enter visitor method: do nothing 718 */ 719 public void visitTree(JCTree tree) { 720 } 721 722 public void visitErroneous(JCErroneous tree) { 723 if (tree.errs != null) 724 memberEnter(tree.errs, env); 725 } 726 727 public Env<AttrContext> getMethodEnv(JCMethodDecl tree, Env<AttrContext> env) { 728 Env<AttrContext> mEnv = methodEnv(tree, env); 729 mEnv.info.lint = mEnv.info.lint.augment(tree.sym.annotations, tree.sym.flags()); 730 for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail) 731 mEnv.info.scope.enterIfAbsent(l.head.type.tsym); 732 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) 733 mEnv.info.scope.enterIfAbsent(l.head.sym); 734 return mEnv; 735 } 736 737 public Env<AttrContext> getInitEnv(JCVariableDecl tree, Env<AttrContext> env) { 738 Env<AttrContext> iEnv = initEnv(tree, env); 739 return iEnv; 740 } 741 742 /* ******************************************************************** 743 * Type completion 744 *********************************************************************/ 745 746 Type attribImportType(JCTree tree, Env<AttrContext> env) { 747 Assert.check(completionEnabled); 748 try { 749 // To prevent deep recursion, suppress completion of some 750 // types. 751 completionEnabled = false; 752 return attr.attribType(tree, env); 753 } finally { 754 completionEnabled = true; 755 } 756 } 757 758 /* ******************************************************************** 759 * Annotation processing 760 *********************************************************************/ 761 762 /** Queue annotations for later processing. */ 763 void annotateLater(final List<JCAnnotation> annotations, 764 final Env<AttrContext> localEnv, 765 final Symbol s) { 766 if (annotations.isEmpty()) { 767 return; 768 } 769 if (s.kind != PCK) { 770 s.annotations.reset(); // mark Annotations as incomplete for now 771 } 772 annotate.normal(new Annotate.Annotator() { 773 @Override 774 public String toString() { 775 return "annotate " + annotations + " onto " + s + " in " + s.owner; 776 } 777 778 @Override 779 public void enterAnnotation() { 780 Assert.check(s.kind == PCK || s.annotations.pendingCompletion()); 781 JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); 782 try { 783 if (!s.annotations.isEmpty() && 784 annotations.nonEmpty()) 785 log.error(annotations.head.pos, 786 "already.annotated", 787 kindName(s), s); 788 actualEnterAnnotations(annotations, localEnv, s); 789 } finally { 790 log.useSource(prev); 791 } 792 } 793 }); 794 } 795 796 /** 797 * Check if a list of annotations contains a reference to 798 * java.lang.Deprecated. 799 **/ 800 private boolean hasDeprecatedAnnotation(List<JCAnnotation> annotations) { 801 for (List<JCAnnotation> al = annotations; !al.isEmpty(); al = al.tail) { 802 JCAnnotation a = al.head; 803 if (a.annotationType.type == syms.deprecatedType && a.args.isEmpty()) 804 return true; 805 } 806 return false; 807 } 808 809 /** Enter a set of annotations. */ 810 private void actualEnterAnnotations(List<JCAnnotation> annotations, 811 Env<AttrContext> env, 812 Symbol s) { 813 Map<TypeSymbol, ListBuffer<Attribute.Compound>> annotated = 814 new LinkedHashMap<TypeSymbol, ListBuffer<Attribute.Compound>>(); 815 Map<Attribute.Compound, DiagnosticPosition> pos = 816 new HashMap<Attribute.Compound, DiagnosticPosition>(); 817 818 for (List<JCAnnotation> al = annotations; !al.isEmpty(); al = al.tail) { 819 JCAnnotation a = al.head; 820 Attribute.Compound c = annotate.enterAnnotation(a, 821 syms.annotationType, 822 env); 823 if (c == null) { 824 continue; 825 } 826 827 if (annotated.containsKey(a.type.tsym)) { 828 if (source.allowRepeatedAnnotations()) { 829 ListBuffer<Attribute.Compound> l = annotated.get(a.type.tsym); 830 l = l.append(c); 831 annotated.put(a.type.tsym, l); 832 pos.put(c, a.pos()); 833 } else { 834 log.error(a.pos(), "duplicate.annotation"); 835 } 836 } else { 837 annotated.put(a.type.tsym, ListBuffer.of(c)); 838 pos.put(c, a.pos()); 839 } 840 841 // Note: @Deprecated has no effect on local variables and parameters 842 if (!c.type.isErroneous() 843 && s.owner.kind != MTH 844 && types.isSameType(c.type, syms.deprecatedType)) { 845 s.flags_field |= Flags.DEPRECATED; 846 } 847 } 848 849 s.annotations.setDeclarationAttributesWithCompletion( 850 annotate.new AnnotateRepeatedContext<Attribute.Compound>(env, annotated, pos, log, false)); 851 } 852 853 /** Queue processing of an attribute default value. */ 854 void annotateDefaultValueLater(final JCExpression defaultValue, 855 final Env<AttrContext> localEnv, 856 final MethodSymbol m) { 857 annotate.normal(new Annotate.Annotator() { 858 @Override 859 public String toString() { 860 return "annotate " + m.owner + "." + 861 m + " default " + defaultValue; 862 } 863 864 @Override 865 public void enterAnnotation() { 866 JavaFileObject prev = log.useSource(localEnv.toplevel.sourcefile); 867 try { 868 enterDefaultValue(defaultValue, localEnv, m); 869 } finally { 870 log.useSource(prev); 871 } 872 } 873 }); 874 } 875 876 /** Enter a default value for an attribute method. */ 877 private void enterDefaultValue(final JCExpression defaultValue, 878 final Env<AttrContext> localEnv, 879 final MethodSymbol m) { 880 m.defaultValue = annotate.enterAttributeValue(m.type.getReturnType(), 881 defaultValue, 882 localEnv); 883 } 884 885 /* ******************************************************************** 886 * Source completer 887 *********************************************************************/ 888 889 /** Complete entering a class. 890 * @param sym The symbol of the class to be completed. 891 */ 892 public void complete(Symbol sym) throws CompletionFailure { 893 // Suppress some (recursive) MemberEnter invocations 894 if (!completionEnabled) { 895 // Re-install same completer for next time around and return. 896 Assert.check((sym.flags() & Flags.COMPOUND) == 0); 897 sym.completer = this; 898 return; 899 } 900 901 ClassSymbol c = (ClassSymbol)sym; 902 ClassType ct = (ClassType)c.type; 903 Env<AttrContext> env = enter.typeEnvs.get(c); 904 JCClassDecl tree = (JCClassDecl)env.tree; 905 boolean wasFirst = isFirst; 906 isFirst = false; 907 908 JavaFileObject prev = log.useSource(env.toplevel.sourcefile); 909 try { 910 // Save class environment for later member enter (2) processing. 911 halfcompleted.append(env); 912 913 // Mark class as not yet attributed. 914 c.flags_field |= UNATTRIBUTED; 915 916 // If this is a toplevel-class, make sure any preceding import 917 // clauses have been seen. 918 if (c.owner.kind == PCK) { 919 memberEnter(env.toplevel, env.enclosing(TOPLEVEL)); 920 todo.append(env); 921 } 922 923 if (c.owner.kind == TYP) 924 c.owner.complete(); 925 926 // create an environment for evaluating the base clauses 927 Env<AttrContext> baseEnv = baseEnv(tree, env); 928 929 if (tree.extending != null) 930 typeAnnotate(tree.extending, baseEnv, sym); 931 for (JCExpression impl : tree.implementing) 932 typeAnnotate(impl, baseEnv, sym); 933 annotate.flush(); 934 935 // Determine supertype. 936 Type supertype = 937 (tree.extending != null) 938 ? attr.attribBase(tree.extending, baseEnv, true, false, true) 939 : ((tree.mods.flags & Flags.ENUM) != 0 && !target.compilerBootstrap(c)) 940 ? attr.attribBase(enumBase(tree.pos, c), baseEnv, 941 true, false, false) 942 : (c.fullname == names.java_lang_Object) 943 ? Type.noType 944 : syms.objectType; 945 ct.supertype_field = modelMissingTypes(supertype, tree.extending, false); 946 947 // Determine interfaces. 948 ListBuffer<Type> interfaces = new ListBuffer<Type>(); 949 ListBuffer<Type> all_interfaces = null; // lazy init 950 Set<Type> interfaceSet = new HashSet<Type>(); 951 List<JCExpression> interfaceTrees = tree.implementing; 952 if ((tree.mods.flags & Flags.ENUM) != 0 && target.compilerBootstrap(c)) { 953 // add interface Comparable<T> 954 interfaceTrees = 955 interfaceTrees.prepend(make.Type(new ClassType(syms.comparableType.getEnclosingType(), 956 List.of(c.type), 957 syms.comparableType.tsym))); 958 // add interface Serializable 959 interfaceTrees = 960 interfaceTrees.prepend(make.Type(syms.serializableType)); 961 } 962 for (JCExpression iface : interfaceTrees) { 963 Type i = attr.attribBase(iface, baseEnv, false, true, true); 964 if (i.hasTag(CLASS)) { 965 interfaces.append(i); 966 if (all_interfaces != null) all_interfaces.append(i); 967 chk.checkNotRepeated(iface.pos(), types.erasure(i), interfaceSet); 968 } else { 969 if (all_interfaces == null) 970 all_interfaces = new ListBuffer<Type>().appendList(interfaces); 971 all_interfaces.append(modelMissingTypes(i, iface, true)); 972 } 973 } 974 if ((c.flags_field & ANNOTATION) != 0) { 975 ct.interfaces_field = List.of(syms.annotationType); 976 ct.all_interfaces_field = ct.interfaces_field; 977 } else { 978 ct.interfaces_field = interfaces.toList(); 979 ct.all_interfaces_field = (all_interfaces == null) 980 ? ct.interfaces_field : all_interfaces.toList(); 981 } 982 983 if (c.fullname == names.java_lang_Object) { 984 if (tree.extending != null) { 985 chk.checkNonCyclic(tree.extending.pos(), 986 supertype); 987 ct.supertype_field = Type.noType; 988 } 989 else if (tree.implementing.nonEmpty()) { 990 chk.checkNonCyclic(tree.implementing.head.pos(), 991 ct.interfaces_field.head); 992 ct.interfaces_field = List.nil(); 993 } 994 } 995 996 // Annotations. 997 // In general, we cannot fully process annotations yet, but we 998 // can attribute the annotation types and then check to see if the 999 // @Deprecated annotation is present. 1000 attr.attribAnnotationTypes(tree.mods.annotations, baseEnv); 1001 if (hasDeprecatedAnnotation(tree.mods.annotations)) 1002 c.flags_field |= DEPRECATED; 1003 annotateLater(tree.mods.annotations, baseEnv, c); 1004 // class type parameters use baseEnv but everything uses env 1005 1006 chk.checkNonCyclicDecl(tree); 1007 1008 attr.attribTypeVariables(tree.typarams, baseEnv); 1009 // Do this here, where we have the symbol. 1010 for (JCTypeParameter tp : tree.typarams) 1011 typeAnnotate(tp, baseEnv, sym); 1012 annotate.flush(); 1013 1014 // Add default constructor if needed. 1015 if ((c.flags() & INTERFACE) == 0 && 1016 !TreeInfo.hasConstructors(tree.defs)) { 1017 List<Type> argtypes = List.nil(); 1018 List<Type> typarams = List.nil(); 1019 List<Type> thrown = List.nil(); 1020 long ctorFlags = 0; 1021 boolean based = false; 1022 boolean addConstructor = true; 1023 if (c.name.isEmpty()) { 1024 JCNewClass nc = (JCNewClass)env.next.tree; 1025 if (nc.constructor != null) { 1026 addConstructor = nc.constructor.kind != ERR; 1027 Type superConstrType = types.memberType(c.type, 1028 nc.constructor); 1029 argtypes = superConstrType.getParameterTypes(); 1030 typarams = superConstrType.getTypeArguments(); 1031 ctorFlags = nc.constructor.flags() & VARARGS; 1032 if (nc.encl != null) { 1033 argtypes = argtypes.prepend(nc.encl.type); 1034 based = true; 1035 } 1036 thrown = superConstrType.getThrownTypes(); 1037 } 1038 } 1039 if (addConstructor) { 1040 JCTree constrDef = DefaultConstructor(make.at(tree.pos), c, 1041 typarams, argtypes, thrown, 1042 ctorFlags, based); 1043 tree.defs = tree.defs.prepend(constrDef); 1044 } 1045 } 1046 1047 // enter symbols for 'this' into current scope. 1048 VarSymbol thisSym = 1049 new VarSymbol(FINAL | HASINIT, names._this, c.type, c); 1050 thisSym.pos = Position.FIRSTPOS; 1051 env.info.scope.enter(thisSym); 1052 // if this is a class, enter symbol for 'super' into current scope. 1053 if ((c.flags_field & INTERFACE) == 0 && 1054 ct.supertype_field.hasTag(CLASS)) { 1055 VarSymbol superSym = 1056 new VarSymbol(FINAL | HASINIT, names._super, 1057 ct.supertype_field, c); 1058 superSym.pos = Position.FIRSTPOS; 1059 env.info.scope.enter(superSym); 1060 } 1061 1062 // check that no package exists with same fully qualified name, 1063 // but admit classes in the unnamed package which have the same 1064 // name as a top-level package. 1065 if (checkClash && 1066 c.owner.kind == PCK && c.owner != syms.unnamedPackage && 1067 reader.packageExists(c.fullname)) { 1068 log.error(tree.pos, "clash.with.pkg.of.same.name", Kinds.kindName(sym), c); 1069 } 1070 if (c.owner.kind == PCK && (c.flags_field & PUBLIC) == 0 && 1071 !env.toplevel.sourcefile.isNameCompatible(c.name.toString(),JavaFileObject.Kind.SOURCE)) { 1072 c.flags_field |= AUXILIARY; 1073 } 1074 } catch (CompletionFailure ex) { 1075 chk.completionError(tree.pos(), ex); 1076 } finally { 1077 log.useSource(prev); 1078 } 1079 1080 // Enter all member fields and methods of a set of half completed 1081 // classes in a second phase. 1082 if (wasFirst) { 1083 try { 1084 while (halfcompleted.nonEmpty()) { 1085 finish(halfcompleted.next()); 1086 } 1087 } finally { 1088 isFirst = true; 1089 } 1090 } 1091 annotate.afterRepeated(TypeAnnotations.organizeTypeAnnotationsSignatures(syms, names, log, tree)); 1092 } 1093 1094 private void actualEnterTypeAnnotations(final List<JCAnnotation> annotations, 1095 final Env<AttrContext> env, 1096 final Symbol s) { 1097 Map<TypeSymbol, ListBuffer<Attribute.TypeCompound>> annotated = 1098 new LinkedHashMap<TypeSymbol, ListBuffer<Attribute.TypeCompound>>(); 1099 Map<Attribute.TypeCompound, DiagnosticPosition> pos = 1100 new HashMap<Attribute.TypeCompound, DiagnosticPosition>(); 1101 1102 for (List<JCAnnotation> al = annotations; !al.isEmpty(); al = al.tail) { 1103 JCAnnotation a = al.head; 1104 Attribute.TypeCompound tc = annotate.enterTypeAnnotation(a, 1105 syms.annotationType, 1106 env); 1107 if (tc == null) { 1108 continue; 1109 } 1110 1111 if (annotated.containsKey(a.type.tsym)) { 1112 if (source.allowRepeatedAnnotations()) { 1113 ListBuffer<Attribute.TypeCompound> l = annotated.get(a.type.tsym); 1114 l = l.append(tc); 1115 annotated.put(a.type.tsym, l); 1116 pos.put(tc, a.pos()); 1117 } else { 1118 log.error(a.pos(), "duplicate.annotation"); 1119 } 1120 } else { 1121 annotated.put(a.type.tsym, ListBuffer.of(tc)); 1122 pos.put(tc, a.pos()); 1123 } 1124 } 1125 1126 s.annotations.appendTypeAttributesWithCompletion( 1127 annotate.new AnnotateRepeatedContext<Attribute.TypeCompound>(env, annotated, pos, log, true)); 1128 } 1129 1130 public void typeAnnotate(final JCTree tree, final Env<AttrContext> env, final Symbol sym) { 1131 tree.accept(new TypeAnnotate(env, sym)); 1132 } 1133 1134 /** 1135 * We need to use a TreeScanner, because it is not enough to visit the top-level 1136 * annotations. We also need to visit type arguments, etc. 1137 */ 1138 private class TypeAnnotate extends TreeScanner { 1139 private Env<AttrContext> env; 1140 private Symbol sym; 1141 1142 public TypeAnnotate(final Env<AttrContext> env, final Symbol sym) { 1143 this.env = env; 1144 this.sym = sym; 1145 } 1146 1147 void annotateTypeLater(final List<JCAnnotation> annotations) { 1148 if (annotations.isEmpty()) { 1149 return; 1150 } 1151 1152 annotate.normal(new Annotate.Annotator() { 1153 @Override 1154 public String toString() { 1155 return "type annotate " + annotations + " onto " + sym + " in " + sym.owner; 1156 } 1157 @Override 1158 public void enterAnnotation() { 1159 JavaFileObject prev = log.useSource(env.toplevel.sourcefile); 1160 try { 1161 actualEnterTypeAnnotations(annotations, env, sym); 1162 } finally { 1163 log.useSource(prev); 1164 } 1165 } 1166 }); 1167 } 1168 1169 @Override 1170 public void visitAnnotatedType(final JCAnnotatedType tree) { 1171 annotateTypeLater(tree.annotations); 1172 super.visitAnnotatedType(tree); 1173 } 1174 1175 @Override 1176 public void visitTypeParameter(final JCTypeParameter tree) { 1177 annotateTypeLater(tree.annotations); 1178 super.visitTypeParameter(tree); 1179 } 1180 1181 @Override 1182 public void visitNewArray(final JCNewArray tree) { 1183 annotateTypeLater(tree.annotations); 1184 for (List<JCAnnotation> dimAnnos : tree.dimAnnotations) 1185 annotateTypeLater(dimAnnos); 1186 super.visitNewArray(tree); 1187 } 1188 1189 @Override 1190 public void visitMethodDef(final JCMethodDecl tree) { 1191 scan(tree.mods); 1192 scan(tree.restype); 1193 scan(tree.typarams); 1194 scan(tree.recvparam); 1195 scan(tree.params); 1196 scan(tree.thrown); 1197 scan(tree.defaultValue); 1198 // Do not annotate the body, just the signature. 1199 // scan(tree.body); 1200 } 1201 } 1202 1203 1204 private Env<AttrContext> baseEnv(JCClassDecl tree, Env<AttrContext> env) { 1205 Scope baseScope = new Scope(tree.sym); 1206 //import already entered local classes into base scope 1207 for (Scope.Entry e = env.outer.info.scope.elems ; e != null ; e = e.sibling) { 1208 if (e.sym.isLocal()) { 1209 baseScope.enter(e.sym); 1210 } 1211 } 1212 //import current type-parameters into base scope 1213 if (tree.typarams != null) 1214 for (List<JCTypeParameter> typarams = tree.typarams; 1215 typarams.nonEmpty(); 1216 typarams = typarams.tail) 1217 baseScope.enter(typarams.head.type.tsym); 1218 Env<AttrContext> outer = env.outer; // the base clause can't see members of this class 1219 Env<AttrContext> localEnv = outer.dup(tree, outer.info.dup(baseScope)); 1220 localEnv.baseClause = true; 1221 localEnv.outer = outer; 1222 localEnv.info.isSelfCall = false; 1223 return localEnv; 1224 } 1225 1226 /** Enter member fields and methods of a class 1227 * @param env the environment current for the class block. 1228 */ 1229 private void finish(Env<AttrContext> env) { 1230 JavaFileObject prev = log.useSource(env.toplevel.sourcefile); 1231 try { 1232 JCClassDecl tree = (JCClassDecl)env.tree; 1233 finishClass(tree, env); 1234 } finally { 1235 log.useSource(prev); 1236 } 1237 } 1238 1239 /** Generate a base clause for an enum type. 1240 * @param pos The position for trees and diagnostics, if any 1241 * @param c The class symbol of the enum 1242 */ 1243 private JCExpression enumBase(int pos, ClassSymbol c) { 1244 JCExpression result = make.at(pos). 1245 TypeApply(make.QualIdent(syms.enumSym), 1246 List.<JCExpression>of(make.Type(c.type))); 1247 return result; 1248 } 1249 1250 Type modelMissingTypes(Type t, final JCExpression tree, final boolean interfaceExpected) { 1251 if (!t.hasTag(ERROR)) 1252 return t; 1253 1254 return new ErrorType(((ErrorType) t).getOriginalType(), t.tsym) { 1255 private Type modelType; 1256 1257 @Override 1258 public Type getModelType() { 1259 if (modelType == null) 1260 modelType = new Synthesizer(getOriginalType(), interfaceExpected).visit(tree); 1261 return modelType; 1262 } 1263 }; 1264 } 1265 // where 1266 private class Synthesizer extends JCTree.Visitor { 1267 Type originalType; 1268 boolean interfaceExpected; 1269 List<ClassSymbol> synthesizedSymbols = List.nil(); 1270 Type result; 1271 1272 Synthesizer(Type originalType, boolean interfaceExpected) { 1273 this.originalType = originalType; 1274 this.interfaceExpected = interfaceExpected; 1275 } 1276 1277 Type visit(JCTree tree) { 1278 tree.accept(this); 1279 return result; 1280 } 1281 1282 List<Type> visit(List<? extends JCTree> trees) { 1283 ListBuffer<Type> lb = new ListBuffer<Type>(); 1284 for (JCTree t: trees) 1285 lb.append(visit(t)); 1286 return lb.toList(); 1287 } 1288 1289 @Override 1290 public void visitTree(JCTree tree) { 1291 result = syms.errType; 1292 } 1293 1294 @Override 1295 public void visitIdent(JCIdent tree) { 1296 if (!tree.type.hasTag(ERROR)) { 1297 result = tree.type; 1298 } else { 1299 result = synthesizeClass(tree.name, syms.unnamedPackage).type; 1300 } 1301 } 1302 1303 @Override 1304 public void visitSelect(JCFieldAccess tree) { 1305 if (!tree.type.hasTag(ERROR)) { 1306 result = tree.type; 1307 } else { 1308 Type selectedType; 1309 boolean prev = interfaceExpected; 1310 try { 1311 interfaceExpected = false; 1312 selectedType = visit(tree.selected); 1313 } finally { 1314 interfaceExpected = prev; 1315 } 1316 ClassSymbol c = synthesizeClass(tree.name, selectedType.tsym); 1317 result = c.type; 1318 } 1319 } 1320 1321 @Override 1322 public void visitTypeApply(JCTypeApply tree) { 1323 if (!tree.type.hasTag(ERROR)) { 1324 result = tree.type; 1325 } else { 1326 ClassType clazzType = (ClassType) visit(tree.clazz); 1327 if (synthesizedSymbols.contains(clazzType.tsym)) 1328 synthesizeTyparams((ClassSymbol) clazzType.tsym, tree.arguments.size()); 1329 final List<Type> actuals = visit(tree.arguments); 1330 result = new ErrorType(tree.type, clazzType.tsym) { 1331 @Override 1332 public List<Type> getTypeArguments() { 1333 return actuals; 1334 } 1335 }; 1336 } 1337 } 1338 1339 ClassSymbol synthesizeClass(Name name, Symbol owner) { 1340 int flags = interfaceExpected ? INTERFACE : 0; 1341 ClassSymbol c = new ClassSymbol(flags, name, owner); 1342 c.members_field = new Scope.ErrorScope(c); 1343 c.type = new ErrorType(originalType, c) { 1344 @Override 1345 public List<Type> getTypeArguments() { 1346 return typarams_field; 1347 } 1348 }; 1349 synthesizedSymbols = synthesizedSymbols.prepend(c); 1350 return c; 1351 } 1352 1353 void synthesizeTyparams(ClassSymbol sym, int n) { 1354 ClassType ct = (ClassType) sym.type; 1355 Assert.check(ct.typarams_field.isEmpty()); 1356 if (n == 1) { 1357 TypeVar v = new TypeVar(names.fromString("T"), sym, syms.botType); 1358 ct.typarams_field = ct.typarams_field.prepend(v); 1359 } else { 1360 for (int i = n; i > 0; i--) { 1361 TypeVar v = new TypeVar(names.fromString("T" + i), sym, syms.botType); 1362 ct.typarams_field = ct.typarams_field.prepend(v); 1363 } 1364 } 1365 } 1366 } 1367 1368 1369 /* *************************************************************************** 1370 * tree building 1371 ****************************************************************************/ 1372 1373 /** Generate default constructor for given class. For classes different 1374 * from java.lang.Object, this is: 1375 * 1376 * c(argtype_0 x_0, ..., argtype_n x_n) throws thrown { 1377 * super(x_0, ..., x_n) 1378 * } 1379 * 1380 * or, if based == true: 1381 * 1382 * c(argtype_0 x_0, ..., argtype_n x_n) throws thrown { 1383 * x_0.super(x_1, ..., x_n) 1384 * } 1385 * 1386 * @param make The tree factory. 1387 * @param c The class owning the default constructor. 1388 * @param argtypes The parameter types of the constructor. 1389 * @param thrown The thrown exceptions of the constructor. 1390 * @param based Is first parameter a this$n? 1391 */ 1392 JCTree DefaultConstructor(TreeMaker make, 1393 ClassSymbol c, 1394 List<Type> typarams, 1395 List<Type> argtypes, 1396 List<Type> thrown, 1397 long flags, 1398 boolean based) { 1399 List<JCVariableDecl> params = make.Params(argtypes, syms.noSymbol); 1400 List<JCStatement> stats = List.nil(); 1401 if (c.type != syms.objectType) 1402 stats = stats.prepend(SuperCall(make, typarams, params, based)); 1403 if ((c.flags() & ENUM) != 0 && 1404 (types.supertype(c.type).tsym == syms.enumSym || 1405 target.compilerBootstrap(c))) { 1406 // constructors of true enums are private 1407 flags = (flags & ~AccessFlags) | PRIVATE | GENERATEDCONSTR; 1408 } else 1409 flags |= (c.flags() & AccessFlags) | GENERATEDCONSTR; 1410 if (c.name.isEmpty()) flags |= ANONCONSTR; 1411 JCTree result = make.MethodDef( 1412 make.Modifiers(flags), 1413 names.init, 1414 null, 1415 make.TypeParams(typarams), 1416 params, 1417 make.Types(thrown), 1418 make.Block(0, stats), 1419 null); 1420 return result; 1421 } 1422 1423 /** Generate call to superclass constructor. This is: 1424 * 1425 * super(id_0, ..., id_n) 1426 * 1427 * or, if based == true 1428 * 1429 * id_0.super(id_1,...,id_n) 1430 * 1431 * where id_0, ..., id_n are the names of the given parameters. 1432 * 1433 * @param make The tree factory 1434 * @param params The parameters that need to be passed to super 1435 * @param typarams The type parameters that need to be passed to super 1436 * @param based Is first parameter a this$n? 1437 */ 1438 JCExpressionStatement SuperCall(TreeMaker make, 1439 List<Type> typarams, 1440 List<JCVariableDecl> params, 1441 boolean based) { 1442 JCExpression meth; 1443 if (based) { 1444 meth = make.Select(make.Ident(params.head), names._super); 1445 params = params.tail; 1446 } else { 1447 meth = make.Ident(names._super); 1448 } 1449 List<JCExpression> typeargs = typarams.nonEmpty() ? make.Types(typarams) : null; 1450 return make.Exec(make.Apply(typeargs, meth, make.Idents(params))); 1451 } 1452 }