1 /* 2 * Copyright 1999-2009 Sun Microsystems, Inc. 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. Sun designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, 22 * CA 95054 USA or visit www.sun.com if you need additional information or 23 * have any questions. 24 */ 25 26 package com.sun.tools.javac.comp; 27 28 import java.util.*; 29 import java.util.Set; 30 import javax.lang.model.element.ElementKind; 31 import javax.tools.JavaFileObject; 32 33 import com.sun.tools.javac.code.*; 34 import com.sun.tools.javac.jvm.*; 35 import com.sun.tools.javac.tree.*; 36 import com.sun.tools.javac.util.*; 37 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; 38 import com.sun.tools.javac.util.List; 39 40 import com.sun.tools.javac.jvm.Target; 41 import com.sun.tools.javac.code.Symbol.*; 42 import com.sun.tools.javac.tree.JCTree.*; 43 import com.sun.tools.javac.code.Type.*; 44 45 import com.sun.source.tree.IdentifierTree; 46 import com.sun.source.tree.MemberSelectTree; 47 import com.sun.source.tree.TreeVisitor; 48 import com.sun.source.util.SimpleTreeVisitor; 49 50 import static com.sun.tools.javac.code.Flags.*; 51 import static com.sun.tools.javac.code.Kinds.*; 52 import static com.sun.tools.javac.code.TypeTags.*; 53 54 /** This is the main context-dependent analysis phase in GJC. It 55 * encompasses name resolution, type checking and constant folding as 56 * subtasks. Some subtasks involve auxiliary classes. 57 * @see Check 58 * @see Resolve 59 * @see ConstFold 60 * @see Infer 61 * 62 * <p><b>This is NOT part of any API supported by Sun Microsystems. If 63 * you write code that depends on this, you do so at your own risk. 64 * This code and its internal interfaces are subject to change or 65 * deletion without notice.</b> 66 */ 67 public class Attr extends JCTree.Visitor { 68 protected static final Context.Key<Attr> attrKey = 69 new Context.Key<Attr>(); 70 71 final Names names; 72 final Log log; 73 final Symtab syms; 74 final Resolve rs; 75 final Check chk; 76 final MemberEnter memberEnter; 77 final TreeMaker make; 78 final ConstFold cfolder; 79 final Enter enter; 80 final Target target; 81 final Types types; 82 final JCDiagnostic.Factory diags; 83 final Annotate annotate; 84 85 public static Attr instance(Context context) { 86 Attr instance = context.get(attrKey); 87 if (instance == null) 88 instance = new Attr(context); 89 return instance; 90 } 91 92 protected Attr(Context context) { 93 context.put(attrKey, this); 94 95 names = Names.instance(context); 96 log = Log.instance(context); 97 syms = Symtab.instance(context); 98 rs = Resolve.instance(context); 99 chk = Check.instance(context); 100 memberEnter = MemberEnter.instance(context); 101 make = TreeMaker.instance(context); 102 enter = Enter.instance(context); 103 cfolder = ConstFold.instance(context); 104 target = Target.instance(context); 105 types = Types.instance(context); 106 diags = JCDiagnostic.Factory.instance(context); 107 annotate = Annotate.instance(context); 108 109 Options options = Options.instance(context); 110 111 Source source = Source.instance(context); 112 allowGenerics = source.allowGenerics(); 113 allowVarargs = source.allowVarargs(); 114 allowEnums = source.allowEnums(); 115 allowBoxing = source.allowBoxing(); 116 allowCovariantReturns = source.allowCovariantReturns(); 117 allowAnonOuterThis = source.allowAnonOuterThis(); 118 allowStringsInSwitch = source.allowStringsInSwitch(); 119 sourceName = source.name; 120 relax = (options.get("-retrofit") != null || 121 options.get("-relax") != null); 122 useBeforeDeclarationWarning = options.get("useBeforeDeclarationWarning") != null; 123 allowInvokedynamic = options.get("invokedynamic") != null; 124 enableSunApiLintControl = options.get("enableSunApiLintControl") != null; 125 } 126 127 /** Switch: relax some constraints for retrofit mode. 128 */ 129 boolean relax; 130 131 /** Switch: support generics? 132 */ 133 boolean allowGenerics; 134 135 /** Switch: allow variable-arity methods. 136 */ 137 boolean allowVarargs; 138 139 /** Switch: support enums? 140 */ 141 boolean allowEnums; 142 143 /** Switch: support boxing and unboxing? 144 */ 145 boolean allowBoxing; 146 147 /** Switch: support covariant result types? 148 */ 149 boolean allowCovariantReturns; 150 151 /** Switch: allow references to surrounding object from anonymous 152 * objects during constructor call? 153 */ 154 boolean allowAnonOuterThis; 155 156 /** Switch: allow invokedynamic syntax 157 */ 158 boolean allowInvokedynamic; 159 160 /** 161 * Switch: warn about use of variable before declaration? 162 * RFE: 6425594 163 */ 164 boolean useBeforeDeclarationWarning; 165 166 /** 167 * Switch: allow lint infrastructure to control Sun proprietary 168 * API warnings. 169 */ 170 boolean enableSunApiLintControl; 171 172 /** 173 * Switch: allow strings in switch? 174 */ 175 boolean allowStringsInSwitch; 176 177 /** 178 * Switch: name of source level; used for error reporting. 179 */ 180 String sourceName; 181 182 /** Check kind and type of given tree against protokind and prototype. 183 * If check succeeds, store type in tree and return it. 184 * If check fails, store errType in tree and return it. 185 * No checks are performed if the prototype is a method type. 186 * It is not necessary in this case since we know that kind and type 187 * are correct. 188 * 189 * @param tree The tree whose kind and type is checked 190 * @param owntype The computed type of the tree 191 * @param ownkind The computed kind of the tree 192 * @param pkind The expected kind (or: protokind) of the tree 193 * @param pt The expected type (or: prototype) of the tree 194 */ 195 Type check(JCTree tree, Type owntype, int ownkind, int pkind, Type pt) { 196 if (owntype.tag != ERROR && pt.tag != METHOD && pt.tag != FORALL) { 197 if ((ownkind & ~pkind) == 0) { 198 owntype = chk.checkType(tree.pos(), owntype, pt); 199 } else { 200 log.error(tree.pos(), "unexpected.type", 201 kindNames(pkind), 202 kindName(ownkind)); 203 owntype = types.createErrorType(owntype); 204 } 205 } 206 tree.type = owntype; 207 return owntype; 208 } 209 210 Type checkReturn(JCTree tree, Type owntype, int ownkind, int pkind, Type pt) { 211 if (owntype.tag != ERROR && pt.tag != METHOD && pt.tag != FORALL) { 212 if ((ownkind & ~pkind) == 0) { 213 owntype = chk.checkReturnType(tree.pos(), owntype, pt); 214 } else { 215 log.error(tree.pos(), "unexpected.type", 216 kindNames(pkind), 217 kindName(ownkind)); 218 owntype = types.createErrorType(owntype); 219 } 220 } 221 tree.type = owntype; 222 return owntype; 223 } 224 225 /** Is given blank final variable assignable, i.e. in a scope where it 226 * may be assigned to even though it is final? 227 * @param v The blank final variable. 228 * @param env The current environment. 229 */ 230 boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) { 231 Symbol owner = env.info.scope.owner; 232 // owner refers to the innermost variable, method or 233 // initializer block declaration at this point. 234 return 235 v.owner == owner 236 || 237 ((owner.name == names.init || // i.e. we are in a constructor 238 owner.kind == VAR || // i.e. we are in a variable initializer 239 (owner.flags() & BLOCK) != 0) // i.e. we are in an initializer block 240 && 241 v.owner == owner.owner 242 && 243 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env)); 244 } 245 246 /** Check that variable can be assigned to. 247 * @param pos The current source code position. 248 * @param v The assigned varaible 249 * @param base If the variable is referred to in a Select, the part 250 * to the left of the `.', null otherwise. 251 * @param env The current environment. 252 */ 253 void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) { 254 if ((v.flags() & FINAL) != 0 && 255 ((v.flags() & HASINIT) != 0 256 || 257 !((base == null || 258 (base.getTag() == JCTree.IDENT && TreeInfo.name(base) == names._this)) && 259 isAssignableAsBlankFinal(v, env)))) { 260 log.error(pos, "cant.assign.val.to.final.var", v); 261 } 262 } 263 264 /** Does tree represent a static reference to an identifier? 265 * It is assumed that tree is either a SELECT or an IDENT. 266 * We have to weed out selects from non-type names here. 267 * @param tree The candidate tree. 268 */ 269 boolean isStaticReference(JCTree tree) { 270 if (tree.getTag() == JCTree.SELECT) { 271 Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected); 272 if (lsym == null || lsym.kind != TYP) { 273 return false; 274 } 275 } 276 return true; 277 } 278 279 /** Is this symbol a type? 280 */ 281 static boolean isType(Symbol sym) { 282 return sym != null && sym.kind == TYP; 283 } 284 285 /** The current `this' symbol. 286 * @param env The current environment. 287 */ 288 Symbol thisSym(DiagnosticPosition pos, Env<AttrContext> env) { 289 return rs.resolveSelf(pos, env, env.enclClass.sym, names._this); 290 } 291 292 /** Attribute a parsed identifier. 293 * @param tree Parsed identifier name 294 * @param topLevel The toplevel to use 295 */ 296 public Symbol attribIdent(JCTree tree, JCCompilationUnit topLevel) { 297 Env<AttrContext> localEnv = enter.topLevelEnv(topLevel); 298 localEnv.enclClass = make.ClassDef(make.Modifiers(0), 299 syms.errSymbol.name, 300 null, null, null, null); 301 localEnv.enclClass.sym = syms.errSymbol; 302 return tree.accept(identAttributer, localEnv); 303 } 304 // where 305 private TreeVisitor<Symbol,Env<AttrContext>> identAttributer = new IdentAttributer(); 306 private class IdentAttributer extends SimpleTreeVisitor<Symbol,Env<AttrContext>> { 307 @Override 308 public Symbol visitMemberSelect(MemberSelectTree node, Env<AttrContext> env) { 309 Symbol site = visit(node.getExpression(), env); 310 if (site.kind == ERR) 311 return site; 312 Name name = (Name)node.getIdentifier(); 313 if (site.kind == PCK) { 314 env.toplevel.packge = (PackageSymbol)site; 315 return rs.findIdentInPackage(env, (TypeSymbol)site, name, TYP | PCK); 316 } else { 317 env.enclClass.sym = (ClassSymbol)site; 318 return rs.findMemberType(env, site.asType(), name, (TypeSymbol)site); 319 } 320 } 321 322 @Override 323 public Symbol visitIdentifier(IdentifierTree node, Env<AttrContext> env) { 324 return rs.findIdent(env, (Name)node.getName(), TYP | PCK); 325 } 326 } 327 328 public Type coerce(Type etype, Type ttype) { 329 return cfolder.coerce(etype, ttype); 330 } 331 332 public Type attribType(JCTree node, TypeSymbol sym) { 333 Env<AttrContext> env = enter.typeEnvs.get(sym); 334 Env<AttrContext> localEnv = env.dup(node, env.info.dup()); 335 return attribTree(node, localEnv, Kinds.TYP, Type.noType); 336 } 337 338 public Env<AttrContext> attribExprToTree(JCTree expr, Env<AttrContext> env, JCTree tree) { 339 breakTree = tree; 340 JavaFileObject prev = log.useSource(env.toplevel.sourcefile); 341 try { 342 attribExpr(expr, env); 343 } catch (BreakAttr b) { 344 return b.env; 345 } finally { 346 breakTree = null; 347 log.useSource(prev); 348 } 349 return env; 350 } 351 352 public Env<AttrContext> attribStatToTree(JCTree stmt, Env<AttrContext> env, JCTree tree) { 353 breakTree = tree; 354 JavaFileObject prev = log.useSource(env.toplevel.sourcefile); 355 try { 356 attribStat(stmt, env); 357 } catch (BreakAttr b) { 358 return b.env; 359 } finally { 360 breakTree = null; 361 log.useSource(prev); 362 } 363 return env; 364 } 365 366 private JCTree breakTree = null; 367 368 private static class BreakAttr extends RuntimeException { 369 static final long serialVersionUID = -6924771130405446405L; 370 private Env<AttrContext> env; 371 private BreakAttr(Env<AttrContext> env) { 372 this.env = env; 373 } 374 } 375 376 377 /* ************************************************************************ 378 * Visitor methods 379 *************************************************************************/ 380 381 /** Visitor argument: the current environment. 382 */ 383 Env<AttrContext> env; 384 385 /** Visitor argument: the currently expected proto-kind. 386 */ 387 int pkind; 388 389 /** Visitor argument: the currently expected proto-type. 390 */ 391 Type pt; 392 393 /** Visitor result: the computed type. 394 */ 395 Type result; 396 397 /** Visitor method: attribute a tree, catching any completion failure 398 * exceptions. Return the tree's type. 399 * 400 * @param tree The tree to be visited. 401 * @param env The environment visitor argument. 402 * @param pkind The protokind visitor argument. 403 * @param pt The prototype visitor argument. 404 */ 405 Type attribTree(JCTree tree, Env<AttrContext> env, int pkind, Type pt) { 406 Env<AttrContext> prevEnv = this.env; 407 int prevPkind = this.pkind; 408 Type prevPt = this.pt; 409 try { 410 this.env = env; 411 this.pkind = pkind; 412 this.pt = pt; 413 tree.accept(this); 414 if (tree == breakTree) 415 throw new BreakAttr(env); 416 return result; 417 } catch (CompletionFailure ex) { 418 tree.type = syms.errType; 419 return chk.completionError(tree.pos(), ex); 420 } finally { 421 this.env = prevEnv; 422 this.pkind = prevPkind; 423 this.pt = prevPt; 424 } 425 } 426 427 /** Derived visitor method: attribute an expression tree. 428 */ 429 public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) { 430 return attribTree(tree, env, VAL, pt.tag != ERROR ? pt : Type.noType); 431 } 432 433 /** Derived visitor method: attribute an expression tree with 434 * no constraints on the computed type. 435 */ 436 Type attribExpr(JCTree tree, Env<AttrContext> env) { 437 return attribTree(tree, env, VAL, Type.noType); 438 } 439 440 /** Derived visitor method: attribute a type tree. 441 */ 442 Type attribType(JCTree tree, Env<AttrContext> env) { 443 Type result = attribType(tree, env, Type.noType); 444 return result; 445 } 446 447 /** Derived visitor method: attribute a type tree. 448 */ 449 Type attribType(JCTree tree, Env<AttrContext> env, Type pt) { 450 Type result = attribTree(tree, env, TYP, pt); 451 return result; 452 } 453 454 /** Derived visitor method: attribute a statement or definition tree. 455 */ 456 public Type attribStat(JCTree tree, Env<AttrContext> env) { 457 return attribTree(tree, env, NIL, Type.noType); 458 } 459 460 /** Attribute a list of expressions, returning a list of types. 461 */ 462 List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) { 463 ListBuffer<Type> ts = new ListBuffer<Type>(); 464 for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail) 465 ts.append(attribExpr(l.head, env, pt)); 466 return ts.toList(); 467 } 468 469 /** Attribute a list of statements, returning nothing. 470 */ 471 <T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) { 472 for (List<T> l = trees; l.nonEmpty(); l = l.tail) 473 attribStat(l.head, env); 474 } 475 476 /** Attribute the arguments in a method call, returning a list of types. 477 */ 478 List<Type> attribArgs(List<JCExpression> trees, Env<AttrContext> env) { 479 ListBuffer<Type> argtypes = new ListBuffer<Type>(); 480 for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail) 481 argtypes.append(chk.checkNonVoid( 482 l.head.pos(), types.upperBound(attribTree(l.head, env, VAL, Infer.anyPoly)))); 483 return argtypes.toList(); 484 } 485 486 /** Attribute a type argument list, returning a list of types. 487 * Caller is responsible for calling checkRefTypes. 488 */ 489 List<Type> attribAnyTypes(List<JCExpression> trees, Env<AttrContext> env) { 490 ListBuffer<Type> argtypes = new ListBuffer<Type>(); 491 for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail) 492 argtypes.append(attribType(l.head, env)); 493 return argtypes.toList(); 494 } 495 496 /** Attribute a type argument list, returning a list of types. 497 * Check that all the types are references. 498 */ 499 List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) { 500 List<Type> types = attribAnyTypes(trees, env); 501 return chk.checkRefTypes(trees, types); 502 } 503 504 /** 505 * Attribute type variables (of generic classes or methods). 506 * Compound types are attributed later in attribBounds. 507 * @param typarams the type variables to enter 508 * @param env the current environment 509 */ 510 void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env) { 511 for (JCTypeParameter tvar : typarams) { 512 TypeVar a = (TypeVar)tvar.type; 513 a.tsym.flags_field |= UNATTRIBUTED; 514 a.bound = Type.noType; 515 if (!tvar.bounds.isEmpty()) { 516 List<Type> bounds = List.of(attribType(tvar.bounds.head, env)); 517 for (JCExpression bound : tvar.bounds.tail) 518 bounds = bounds.prepend(attribType(bound, env)); 519 types.setBounds(a, bounds.reverse()); 520 } else { 521 // if no bounds are given, assume a single bound of 522 // java.lang.Object. 523 types.setBounds(a, List.of(syms.objectType)); 524 } 525 a.tsym.flags_field &= ~UNATTRIBUTED; 526 } 527 for (JCTypeParameter tvar : typarams) 528 chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type); 529 attribStats(typarams, env); 530 } 531 532 void attribBounds(List<JCTypeParameter> typarams) { 533 for (JCTypeParameter typaram : typarams) { 534 Type bound = typaram.type.getUpperBound(); 535 if (bound != null && bound.tsym instanceof ClassSymbol) { 536 ClassSymbol c = (ClassSymbol)bound.tsym; 537 if ((c.flags_field & COMPOUND) != 0) { 538 assert (c.flags_field & UNATTRIBUTED) != 0 : c; 539 attribClass(typaram.pos(), c); 540 } 541 } 542 } 543 } 544 545 /** 546 * Attribute the type references in a list of annotations. 547 */ 548 void attribAnnotationTypes(List<JCAnnotation> annotations, 549 Env<AttrContext> env) { 550 for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) { 551 JCAnnotation a = al.head; 552 attribType(a.annotationType, env); 553 } 554 } 555 556 /** Attribute type reference in an `extends' or `implements' clause. 557 * 558 * @param tree The tree making up the type reference. 559 * @param env The environment current at the reference. 560 * @param classExpected true if only a class is expected here. 561 * @param interfaceExpected true if only an interface is expected here. 562 */ 563 Type attribBase(JCTree tree, 564 Env<AttrContext> env, 565 boolean classExpected, 566 boolean interfaceExpected, 567 boolean checkExtensible) { 568 Type t = attribType(tree, env); 569 return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible); 570 } 571 Type checkBase(Type t, 572 JCTree tree, 573 Env<AttrContext> env, 574 boolean classExpected, 575 boolean interfaceExpected, 576 boolean checkExtensible) { 577 if (t.tag == TYPEVAR && !classExpected && !interfaceExpected) { 578 // check that type variable is already visible 579 if (t.getUpperBound() == null) { 580 log.error(tree.pos(), "illegal.forward.ref"); 581 return types.createErrorType(t); 582 } 583 } else { 584 t = chk.checkClassType(tree.pos(), t, checkExtensible|!allowGenerics); 585 } 586 if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) { 587 log.error(tree.pos(), "intf.expected.here"); 588 // return errType is necessary since otherwise there might 589 // be undetected cycles which cause attribution to loop 590 return types.createErrorType(t); 591 } else if (checkExtensible && 592 classExpected && 593 (t.tsym.flags() & INTERFACE) != 0) { 594 log.error(tree.pos(), "no.intf.expected.here"); 595 return types.createErrorType(t); 596 } 597 if (checkExtensible && 598 ((t.tsym.flags() & FINAL) != 0)) { 599 log.error(tree.pos(), 600 "cant.inherit.from.final", t.tsym); 601 } 602 chk.checkNonCyclic(tree.pos(), t); 603 return t; 604 } 605 606 public void visitClassDef(JCClassDecl tree) { 607 // Local classes have not been entered yet, so we need to do it now: 608 if ((env.info.scope.owner.kind & (VAR | MTH)) != 0) 609 enter.classEnter(tree, env); 610 611 ClassSymbol c = tree.sym; 612 if (c == null) { 613 // exit in case something drastic went wrong during enter. 614 result = null; 615 } else { 616 // make sure class has been completed: 617 c.complete(); 618 619 // If this class appears as an anonymous class 620 // in a superclass constructor call where 621 // no explicit outer instance is given, 622 // disable implicit outer instance from being passed. 623 // (This would be an illegal access to "this before super"). 624 if (env.info.isSelfCall && 625 env.tree.getTag() == JCTree.NEWCLASS && 626 ((JCNewClass) env.tree).encl == null) 627 { 628 c.flags_field |= NOOUTERTHIS; 629 } 630 attribClass(tree.pos(), c); 631 result = tree.type = c.type; 632 } 633 } 634 635 public void visitMethodDef(JCMethodDecl tree) { 636 MethodSymbol m = tree.sym; 637 638 Lint lint = env.info.lint.augment(m.attributes_field, m.flags()); 639 Lint prevLint = chk.setLint(lint); 640 try { 641 chk.checkDeprecatedAnnotation(tree.pos(), m); 642 643 attribBounds(tree.typarams); 644 645 // If we override any other methods, check that we do so properly. 646 // JLS ??? 647 chk.checkOverride(tree, m); 648 649 // Create a new environment with local scope 650 // for attributing the method. 651 Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env); 652 653 localEnv.info.lint = lint; 654 655 // Enter all type parameters into the local method scope. 656 for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail) 657 localEnv.info.scope.enterIfAbsent(l.head.type.tsym); 658 659 ClassSymbol owner = env.enclClass.sym; 660 if ((owner.flags() & ANNOTATION) != 0 && 661 tree.params.nonEmpty()) 662 log.error(tree.params.head.pos(), 663 "intf.annotation.members.cant.have.params"); 664 665 // Attribute all value parameters. 666 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) { 667 attribStat(l.head, localEnv); 668 } 669 670 // Check that type parameters are well-formed. 671 chk.validate(tree.typarams, localEnv); 672 if ((owner.flags() & ANNOTATION) != 0 && 673 tree.typarams.nonEmpty()) 674 log.error(tree.typarams.head.pos(), 675 "intf.annotation.members.cant.have.type.params"); 676 677 // Check that result type is well-formed. 678 chk.validate(tree.restype, localEnv); 679 if ((owner.flags() & ANNOTATION) != 0) 680 chk.validateAnnotationType(tree.restype); 681 682 if ((owner.flags() & ANNOTATION) != 0) 683 chk.validateAnnotationMethod(tree.pos(), m); 684 685 // Check that all exceptions mentioned in the throws clause extend 686 // java.lang.Throwable. 687 if ((owner.flags() & ANNOTATION) != 0 && tree.thrown.nonEmpty()) 688 log.error(tree.thrown.head.pos(), 689 "throws.not.allowed.in.intf.annotation"); 690 for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail) 691 chk.checkType(l.head.pos(), l.head.type, syms.throwableType); 692 693 if (tree.body == null) { 694 // Empty bodies are only allowed for 695 // abstract, native, or interface methods, or for methods 696 // in a retrofit signature class. 697 if ((owner.flags() & INTERFACE) == 0 && 698 (tree.mods.flags & (ABSTRACT | NATIVE)) == 0 && 699 !relax) 700 log.error(tree.pos(), "missing.meth.body.or.decl.abstract"); 701 if (tree.defaultValue != null) { 702 if ((owner.flags() & ANNOTATION) == 0) 703 log.error(tree.pos(), 704 "default.allowed.in.intf.annotation.member"); 705 } 706 } else if ((owner.flags() & INTERFACE) != 0) { 707 log.error(tree.body.pos(), "intf.meth.cant.have.body"); 708 } else if ((tree.mods.flags & ABSTRACT) != 0) { 709 log.error(tree.pos(), "abstract.meth.cant.have.body"); 710 } else if ((tree.mods.flags & NATIVE) != 0) { 711 log.error(tree.pos(), "native.meth.cant.have.body"); 712 } else { 713 // Add an implicit super() call unless an explicit call to 714 // super(...) or this(...) is given 715 // or we are compiling class java.lang.Object. 716 if (tree.name == names.init && owner.type != syms.objectType) { 717 JCBlock body = tree.body; 718 if (body.stats.isEmpty() || 719 !TreeInfo.isSelfCall(body.stats.head)) { 720 body.stats = body.stats. 721 prepend(memberEnter.SuperCall(make.at(body.pos), 722 List.<Type>nil(), 723 List.<JCVariableDecl>nil(), 724 false)); 725 } else if ((env.enclClass.sym.flags() & ENUM) != 0 && 726 (tree.mods.flags & GENERATEDCONSTR) == 0 && 727 TreeInfo.isSuperCall(body.stats.head)) { 728 // enum constructors are not allowed to call super 729 // directly, so make sure there aren't any super calls 730 // in enum constructors, except in the compiler 731 // generated one. 732 log.error(tree.body.stats.head.pos(), 733 "call.to.super.not.allowed.in.enum.ctor", 734 env.enclClass.sym); 735 } 736 } 737 738 // Attribute method body. 739 attribStat(tree.body, localEnv); 740 } 741 localEnv.info.scope.leave(); 742 result = tree.type = m.type; 743 chk.validateAnnotations(tree.mods.annotations, m); 744 } 745 finally { 746 chk.setLint(prevLint); 747 } 748 } 749 750 public void visitVarDef(JCVariableDecl tree) { 751 // Local variables have not been entered yet, so we need to do it now: 752 if (env.info.scope.owner.kind == MTH) { 753 if (tree.sym != null) { 754 // parameters have already been entered 755 env.info.scope.enter(tree.sym); 756 } else { 757 memberEnter.memberEnter(tree, env); 758 annotate.flush(); 759 } 760 } 761 762 VarSymbol v = tree.sym; 763 Lint lint = env.info.lint.augment(v.attributes_field, v.flags()); 764 Lint prevLint = chk.setLint(lint); 765 766 // Check that the variable's declared type is well-formed. 767 chk.validate(tree.vartype, env); 768 769 try { 770 chk.checkDeprecatedAnnotation(tree.pos(), v); 771 772 if (tree.init != null) { 773 if ((v.flags_field & FINAL) != 0 && tree.init.getTag() != JCTree.NEWCLASS) { 774 // In this case, `v' is final. Ensure that it's initializer is 775 // evaluated. 776 v.getConstValue(); // ensure initializer is evaluated 777 } else { 778 // Attribute initializer in a new environment 779 // with the declared variable as owner. 780 // Check that initializer conforms to variable's declared type. 781 Env<AttrContext> initEnv = memberEnter.initEnv(tree, env); 782 initEnv.info.lint = lint; 783 // In order to catch self-references, we set the variable's 784 // declaration position to maximal possible value, effectively 785 // marking the variable as undefined. 786 initEnv.info.enclVar = v; 787 attribExpr(tree.init, initEnv, v.type); 788 } 789 } 790 result = tree.type = v.type; 791 chk.validateAnnotations(tree.mods.annotations, v); 792 } 793 finally { 794 chk.setLint(prevLint); 795 } 796 } 797 798 public void visitSkip(JCSkip tree) { 799 result = null; 800 } 801 802 public void visitBlock(JCBlock tree) { 803 if (env.info.scope.owner.kind == TYP) { 804 // Block is a static or instance initializer; 805 // let the owner of the environment be a freshly 806 // created BLOCK-method. 807 Env<AttrContext> localEnv = 808 env.dup(tree, env.info.dup(env.info.scope.dupUnshared())); 809 localEnv.info.scope.owner = 810 new MethodSymbol(tree.flags | BLOCK, names.empty, null, 811 env.info.scope.owner); 812 if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++; 813 attribStats(tree.stats, localEnv); 814 } else { 815 // Create a new local environment with a local scope. 816 Env<AttrContext> localEnv = 817 env.dup(tree, env.info.dup(env.info.scope.dup())); 818 attribStats(tree.stats, localEnv); 819 localEnv.info.scope.leave(); 820 } 821 result = null; 822 } 823 824 public void visitDoLoop(JCDoWhileLoop tree) { 825 attribStat(tree.body, env.dup(tree)); 826 attribExpr(tree.cond, env, syms.booleanType); 827 result = null; 828 } 829 830 public void visitWhileLoop(JCWhileLoop tree) { 831 attribExpr(tree.cond, env, syms.booleanType); 832 attribStat(tree.body, env.dup(tree)); 833 result = null; 834 } 835 836 public void visitForLoop(JCForLoop tree) { 837 Env<AttrContext> loopEnv = 838 env.dup(env.tree, env.info.dup(env.info.scope.dup())); 839 attribStats(tree.init, loopEnv); 840 if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType); 841 loopEnv.tree = tree; // before, we were not in loop! 842 attribStats(tree.step, loopEnv); 843 attribStat(tree.body, loopEnv); 844 loopEnv.info.scope.leave(); 845 result = null; 846 } 847 848 public void visitForeachLoop(JCEnhancedForLoop tree) { 849 Env<AttrContext> loopEnv = 850 env.dup(env.tree, env.info.dup(env.info.scope.dup())); 851 attribStat(tree.var, loopEnv); 852 Type exprType = types.upperBound(attribExpr(tree.expr, loopEnv)); 853 chk.checkNonVoid(tree.pos(), exprType); 854 Type elemtype = types.elemtype(exprType); // perhaps expr is an array? 855 if (elemtype == null) { 856 // or perhaps expr implements Iterable<T>? 857 Type base = types.asSuper(exprType, syms.iterableType.tsym); 858 if (base == null) { 859 log.error(tree.expr.pos(), "foreach.not.applicable.to.type"); 860 elemtype = types.createErrorType(exprType); 861 } else { 862 List<Type> iterableParams = base.allparams(); 863 elemtype = iterableParams.isEmpty() 864 ? syms.objectType 865 : types.upperBound(iterableParams.head); 866 } 867 } 868 chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type); 869 loopEnv.tree = tree; // before, we were not in loop! 870 attribStat(tree.body, loopEnv); 871 loopEnv.info.scope.leave(); 872 result = null; 873 } 874 875 public void visitLabelled(JCLabeledStatement tree) { 876 // Check that label is not used in an enclosing statement 877 Env<AttrContext> env1 = env; 878 while (env1 != null && env1.tree.getTag() != JCTree.CLASSDEF) { 879 if (env1.tree.getTag() == JCTree.LABELLED && 880 ((JCLabeledStatement) env1.tree).label == tree.label) { 881 log.error(tree.pos(), "label.already.in.use", 882 tree.label); 883 break; 884 } 885 env1 = env1.next; 886 } 887 888 attribStat(tree.body, env.dup(tree)); 889 result = null; 890 } 891 892 public void visitSwitch(JCSwitch tree) { 893 Type seltype = attribExpr(tree.selector, env); 894 895 Env<AttrContext> switchEnv = 896 env.dup(tree, env.info.dup(env.info.scope.dup())); 897 898 boolean enumSwitch = 899 allowEnums && 900 (seltype.tsym.flags() & Flags.ENUM) != 0; 901 boolean stringSwitch = false; 902 if (types.isSameType(seltype, syms.stringType)) { 903 if (allowStringsInSwitch) { 904 stringSwitch = true; 905 } else { 906 log.error(tree.selector.pos(), "string.switch.not.supported.in.source", sourceName); 907 } 908 } 909 if (!enumSwitch && !stringSwitch) 910 seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType); 911 912 // Attribute all cases and 913 // check that there are no duplicate case labels or default clauses. 914 Set<Object> labels = new HashSet<Object>(); // The set of case labels. 915 boolean hasDefault = false; // Is there a default label? 916 for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) { 917 JCCase c = l.head; 918 Env<AttrContext> caseEnv = 919 switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup())); 920 if (c.pat != null) { 921 if (enumSwitch) { 922 Symbol sym = enumConstant(c.pat, seltype); 923 if (sym == null) { 924 log.error(c.pat.pos(), "enum.const.req"); 925 } else if (!labels.add(sym)) { 926 log.error(c.pos(), "duplicate.case.label"); 927 } 928 } else { 929 Type pattype = attribExpr(c.pat, switchEnv, seltype); 930 if (pattype.tag != ERROR) { 931 if (pattype.constValue() == null) { 932 log.error(c.pat.pos(), 933 (stringSwitch ? "string.const.req" : "const.expr.req")); 934 } else if (labels.contains(pattype.constValue())) { 935 log.error(c.pos(), "duplicate.case.label"); 936 } else { 937 labels.add(pattype.constValue()); 938 } 939 } 940 } 941 } else if (hasDefault) { 942 log.error(c.pos(), "duplicate.default.label"); 943 } else { 944 hasDefault = true; 945 } 946 attribStats(c.stats, caseEnv); 947 caseEnv.info.scope.leave(); 948 addVars(c.stats, switchEnv.info.scope); 949 } 950 951 switchEnv.info.scope.leave(); 952 result = null; 953 } 954 // where 955 /** Add any variables defined in stats to the switch scope. */ 956 private static void addVars(List<JCStatement> stats, Scope switchScope) { 957 for (;stats.nonEmpty(); stats = stats.tail) { 958 JCTree stat = stats.head; 959 if (stat.getTag() == JCTree.VARDEF) 960 switchScope.enter(((JCVariableDecl) stat).sym); 961 } 962 } 963 // where 964 /** Return the selected enumeration constant symbol, or null. */ 965 private Symbol enumConstant(JCTree tree, Type enumType) { 966 if (tree.getTag() != JCTree.IDENT) { 967 log.error(tree.pos(), "enum.label.must.be.unqualified.enum"); 968 return syms.errSymbol; 969 } 970 JCIdent ident = (JCIdent)tree; 971 Name name = ident.name; 972 for (Scope.Entry e = enumType.tsym.members().lookup(name); 973 e.scope != null; e = e.next()) { 974 if (e.sym.kind == VAR) { 975 Symbol s = ident.sym = e.sym; 976 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated 977 ident.type = s.type; 978 return ((s.flags_field & Flags.ENUM) == 0) 979 ? null : s; 980 } 981 } 982 return null; 983 } 984 985 public void visitSynchronized(JCSynchronized tree) { 986 chk.checkRefType(tree.pos(), attribExpr(tree.lock, env)); 987 attribStat(tree.body, env); 988 result = null; 989 } 990 991 public void visitTry(JCTry tree) { 992 // Attribute body 993 attribStat(tree.body, env.dup(tree, env.info.dup())); 994 995 // Attribute catch clauses 996 for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) { 997 JCCatch c = l.head; 998 Env<AttrContext> catchEnv = 999 env.dup(c, env.info.dup(env.info.scope.dup())); 1000 Type ctype = attribStat(c.param, catchEnv); 1001 if (c.param.type.tsym.kind == Kinds.VAR) { 1002 c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER); 1003 } 1004 chk.checkType(c.param.vartype.pos(), 1005 chk.checkClassType(c.param.vartype.pos(), ctype), 1006 syms.throwableType); 1007 attribStat(c.body, catchEnv); 1008 catchEnv.info.scope.leave(); 1009 } 1010 1011 // Attribute finalizer 1012 if (tree.finalizer != null) attribStat(tree.finalizer, env); 1013 result = null; 1014 } 1015 1016 public void visitConditional(JCConditional tree) { 1017 attribExpr(tree.cond, env, syms.booleanType); 1018 attribExpr(tree.truepart, env); 1019 attribExpr(tree.falsepart, env); 1020 result = check(tree, 1021 capture(condType(tree.pos(), tree.cond.type, 1022 tree.truepart.type, tree.falsepart.type)), 1023 VAL, pkind, pt); 1024 } 1025 //where 1026 /** Compute the type of a conditional expression, after 1027 * checking that it exists. See Spec 15.25. 1028 * 1029 * @param pos The source position to be used for 1030 * error diagnostics. 1031 * @param condtype The type of the expression's condition. 1032 * @param thentype The type of the expression's then-part. 1033 * @param elsetype The type of the expression's else-part. 1034 */ 1035 private Type condType(DiagnosticPosition pos, 1036 Type condtype, 1037 Type thentype, 1038 Type elsetype) { 1039 Type ctype = condType1(pos, condtype, thentype, elsetype); 1040 1041 // If condition and both arms are numeric constants, 1042 // evaluate at compile-time. 1043 return ((condtype.constValue() != null) && 1044 (thentype.constValue() != null) && 1045 (elsetype.constValue() != null)) 1046 ? cfolder.coerce(condtype.isTrue()?thentype:elsetype, ctype) 1047 : ctype; 1048 } 1049 /** Compute the type of a conditional expression, after 1050 * checking that it exists. Does not take into 1051 * account the special case where condition and both arms 1052 * are constants. 1053 * 1054 * @param pos The source position to be used for error 1055 * diagnostics. 1056 * @param condtype The type of the expression's condition. 1057 * @param thentype The type of the expression's then-part. 1058 * @param elsetype The type of the expression's else-part. 1059 */ 1060 private Type condType1(DiagnosticPosition pos, Type condtype, 1061 Type thentype, Type elsetype) { 1062 // If same type, that is the result 1063 if (types.isSameType(thentype, elsetype)) 1064 return thentype.baseType(); 1065 1066 Type thenUnboxed = (!allowBoxing || thentype.isPrimitive()) 1067 ? thentype : types.unboxedType(thentype); 1068 Type elseUnboxed = (!allowBoxing || elsetype.isPrimitive()) 1069 ? elsetype : types.unboxedType(elsetype); 1070 1071 // Otherwise, if both arms can be converted to a numeric 1072 // type, return the least numeric type that fits both arms 1073 // (i.e. return larger of the two, or return int if one 1074 // arm is short, the other is char). 1075 if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) { 1076 // If one arm has an integer subrange type (i.e., byte, 1077 // short, or char), and the other is an integer constant 1078 // that fits into the subrange, return the subrange type. 1079 if (thenUnboxed.tag < INT && elseUnboxed.tag == INT && 1080 types.isAssignable(elseUnboxed, thenUnboxed)) 1081 return thenUnboxed.baseType(); 1082 if (elseUnboxed.tag < INT && thenUnboxed.tag == INT && 1083 types.isAssignable(thenUnboxed, elseUnboxed)) 1084 return elseUnboxed.baseType(); 1085 1086 for (int i = BYTE; i < VOID; i++) { 1087 Type candidate = syms.typeOfTag[i]; 1088 if (types.isSubtype(thenUnboxed, candidate) && 1089 types.isSubtype(elseUnboxed, candidate)) 1090 return candidate; 1091 } 1092 } 1093 1094 // Those were all the cases that could result in a primitive 1095 if (allowBoxing) { 1096 if (thentype.isPrimitive()) 1097 thentype = types.boxedClass(thentype).type; 1098 if (elsetype.isPrimitive()) 1099 elsetype = types.boxedClass(elsetype).type; 1100 } 1101 1102 if (types.isSubtype(thentype, elsetype)) 1103 return elsetype.baseType(); 1104 if (types.isSubtype(elsetype, thentype)) 1105 return thentype.baseType(); 1106 1107 if (!allowBoxing || thentype.tag == VOID || elsetype.tag == VOID) { 1108 log.error(pos, "neither.conditional.subtype", 1109 thentype, elsetype); 1110 return thentype.baseType(); 1111 } 1112 1113 // both are known to be reference types. The result is 1114 // lub(thentype,elsetype). This cannot fail, as it will 1115 // always be possible to infer "Object" if nothing better. 1116 return types.lub(thentype.baseType(), elsetype.baseType()); 1117 } 1118 1119 public void visitIf(JCIf tree) { 1120 attribExpr(tree.cond, env, syms.booleanType); 1121 attribStat(tree.thenpart, env); 1122 if (tree.elsepart != null) 1123 attribStat(tree.elsepart, env); 1124 chk.checkEmptyIf(tree); 1125 result = null; 1126 } 1127 1128 public void visitExec(JCExpressionStatement tree) { 1129 attribExpr(tree.expr, env); 1130 result = null; 1131 } 1132 1133 public void visitBreak(JCBreak tree) { 1134 tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env); 1135 result = null; 1136 } 1137 1138 public void visitContinue(JCContinue tree) { 1139 tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env); 1140 result = null; 1141 } 1142 //where 1143 /** Return the target of a break or continue statement, if it exists, 1144 * report an error if not. 1145 * Note: The target of a labelled break or continue is the 1146 * (non-labelled) statement tree referred to by the label, 1147 * not the tree representing the labelled statement itself. 1148 * 1149 * @param pos The position to be used for error diagnostics 1150 * @param tag The tag of the jump statement. This is either 1151 * Tree.BREAK or Tree.CONTINUE. 1152 * @param label The label of the jump statement, or null if no 1153 * label is given. 1154 * @param env The environment current at the jump statement. 1155 */ 1156 private JCTree findJumpTarget(DiagnosticPosition pos, 1157 int tag, 1158 Name label, 1159 Env<AttrContext> env) { 1160 // Search environments outwards from the point of jump. 1161 Env<AttrContext> env1 = env; 1162 LOOP: 1163 while (env1 != null) { 1164 switch (env1.tree.getTag()) { 1165 case JCTree.LABELLED: 1166 JCLabeledStatement labelled = (JCLabeledStatement)env1.tree; 1167 if (label == labelled.label) { 1168 // If jump is a continue, check that target is a loop. 1169 if (tag == JCTree.CONTINUE) { 1170 if (labelled.body.getTag() != JCTree.DOLOOP && 1171 labelled.body.getTag() != JCTree.WHILELOOP && 1172 labelled.body.getTag() != JCTree.FORLOOP && 1173 labelled.body.getTag() != JCTree.FOREACHLOOP) 1174 log.error(pos, "not.loop.label", label); 1175 // Found labelled statement target, now go inwards 1176 // to next non-labelled tree. 1177 return TreeInfo.referencedStatement(labelled); 1178 } else { 1179 return labelled; 1180 } 1181 } 1182 break; 1183 case JCTree.DOLOOP: 1184 case JCTree.WHILELOOP: 1185 case JCTree.FORLOOP: 1186 case JCTree.FOREACHLOOP: 1187 if (label == null) return env1.tree; 1188 break; 1189 case JCTree.SWITCH: 1190 if (label == null && tag == JCTree.BREAK) return env1.tree; 1191 break; 1192 case JCTree.METHODDEF: 1193 case JCTree.CLASSDEF: 1194 break LOOP; 1195 default: 1196 } 1197 env1 = env1.next; 1198 } 1199 if (label != null) 1200 log.error(pos, "undef.label", label); 1201 else if (tag == JCTree.CONTINUE) 1202 log.error(pos, "cont.outside.loop"); 1203 else 1204 log.error(pos, "break.outside.switch.loop"); 1205 return null; 1206 } 1207 1208 public void visitReturn(JCReturn tree) { 1209 // Check that there is an enclosing method which is 1210 // nested within than the enclosing class. 1211 if (env.enclMethod == null || 1212 env.enclMethod.sym.owner != env.enclClass.sym) { 1213 log.error(tree.pos(), "ret.outside.meth"); 1214 1215 } else { 1216 // Attribute return expression, if it exists, and check that 1217 // it conforms to result type of enclosing method. 1218 Symbol m = env.enclMethod.sym; 1219 if (m.type.getReturnType().tag == VOID) { 1220 if (tree.expr != null) 1221 log.error(tree.expr.pos(), 1222 "cant.ret.val.from.meth.decl.void"); 1223 } else if (tree.expr == null) { 1224 log.error(tree.pos(), "missing.ret.val"); 1225 } else { 1226 attribExpr(tree.expr, env, m.type.getReturnType()); 1227 } 1228 } 1229 result = null; 1230 } 1231 1232 public void visitThrow(JCThrow tree) { 1233 attribExpr(tree.expr, env, syms.throwableType); 1234 result = null; 1235 } 1236 1237 public void visitAssert(JCAssert tree) { 1238 attribExpr(tree.cond, env, syms.booleanType); 1239 if (tree.detail != null) { 1240 chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env)); 1241 } 1242 result = null; 1243 } 1244 1245 /** Visitor method for method invocations. 1246 * NOTE: The method part of an application will have in its type field 1247 * the return type of the method, not the method's type itself! 1248 */ 1249 public void visitApply(JCMethodInvocation tree) { 1250 // The local environment of a method application is 1251 // a new environment nested in the current one. 1252 Env<AttrContext> localEnv = env.dup(tree, env.info.dup()); 1253 1254 // The types of the actual method arguments. 1255 List<Type> argtypes; 1256 1257 // The types of the actual method type arguments. 1258 List<Type> typeargtypes = null; 1259 boolean typeargtypesNonRefOK = false; 1260 1261 Name methName = TreeInfo.name(tree.meth); 1262 1263 boolean isConstructorCall = 1264 methName == names._this || methName == names._super; 1265 1266 if (isConstructorCall) { 1267 // We are seeing a ...this(...) or ...super(...) call. 1268 // Check that this is the first statement in a constructor. 1269 if (checkFirstConstructorStat(tree, env)) { 1270 1271 // Record the fact 1272 // that this is a constructor call (using isSelfCall). 1273 localEnv.info.isSelfCall = true; 1274 1275 // Attribute arguments, yielding list of argument types. 1276 argtypes = attribArgs(tree.args, localEnv); 1277 typeargtypes = attribTypes(tree.typeargs, localEnv); 1278 1279 // Variable `site' points to the class in which the called 1280 // constructor is defined. 1281 Type site = env.enclClass.sym.type; 1282 if (methName == names._super) { 1283 if (site == syms.objectType) { 1284 log.error(tree.meth.pos(), "no.superclass", site); 1285 site = types.createErrorType(syms.objectType); 1286 } else { 1287 site = types.supertype(site); 1288 } 1289 } 1290 1291 if (site.tag == CLASS) { 1292 Type encl = site.getEnclosingType(); 1293 while (encl != null && encl.tag == TYPEVAR) 1294 encl = encl.getUpperBound(); 1295 if (encl.tag == CLASS) { 1296 // we are calling a nested class 1297 1298 if (tree.meth.getTag() == JCTree.SELECT) { 1299 JCTree qualifier = ((JCFieldAccess) tree.meth).selected; 1300 1301 // We are seeing a prefixed call, of the form 1302 // <expr>.super(...). 1303 // Check that the prefix expression conforms 1304 // to the outer instance type of the class. 1305 chk.checkRefType(qualifier.pos(), 1306 attribExpr(qualifier, localEnv, 1307 encl)); 1308 } else if (methName == names._super) { 1309 // qualifier omitted; check for existence 1310 // of an appropriate implicit qualifier. 1311 rs.resolveImplicitThis(tree.meth.pos(), 1312 localEnv, site); 1313 } 1314 } else if (tree.meth.getTag() == JCTree.SELECT) { 1315 log.error(tree.meth.pos(), "illegal.qual.not.icls", 1316 site.tsym); 1317 } 1318 1319 // if we're calling a java.lang.Enum constructor, 1320 // prefix the implicit String and int parameters 1321 if (site.tsym == syms.enumSym && allowEnums) 1322 argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType); 1323 1324 // Resolve the called constructor under the assumption 1325 // that we are referring to a superclass instance of the 1326 // current instance (JLS ???). 1327 boolean selectSuperPrev = localEnv.info.selectSuper; 1328 localEnv.info.selectSuper = true; 1329 localEnv.info.varArgs = false; 1330 Symbol sym = rs.resolveConstructor( 1331 tree.meth.pos(), localEnv, site, argtypes, typeargtypes); 1332 localEnv.info.selectSuper = selectSuperPrev; 1333 1334 // Set method symbol to resolved constructor... 1335 TreeInfo.setSymbol(tree.meth, sym); 1336 1337 // ...and check that it is legal in the current context. 1338 // (this will also set the tree's type) 1339 Type mpt = newMethTemplate(argtypes, typeargtypes); 1340 checkId(tree.meth, site, sym, localEnv, MTH, 1341 mpt, tree.varargsElement != null); 1342 } 1343 // Otherwise, `site' is an error type and we do nothing 1344 } 1345 result = tree.type = syms.voidType; 1346 } else { 1347 // Otherwise, we are seeing a regular method call. 1348 // Attribute the arguments, yielding list of argument types, ... 1349 argtypes = attribArgs(tree.args, localEnv); 1350 typeargtypes = attribAnyTypes(tree.typeargs, localEnv); 1351 1352 // ... and attribute the method using as a prototype a methodtype 1353 // whose formal argument types is exactly the list of actual 1354 // arguments (this will also set the method symbol). 1355 Type mpt = newMethTemplate(argtypes, typeargtypes); 1356 localEnv.info.varArgs = false; 1357 Type mtype = attribExpr(tree.meth, localEnv, mpt); 1358 if (localEnv.info.varArgs) 1359 assert mtype.isErroneous() || tree.varargsElement != null; 1360 1361 // Compute the result type. 1362 Type restype = mtype.getReturnType(); 1363 assert restype.tag != WILDCARD : mtype; 1364 1365 // as a special case, array.clone() has a result that is 1366 // the same as static type of the array being cloned 1367 if (tree.meth.getTag() == JCTree.SELECT && 1368 allowCovariantReturns && 1369 methName == names.clone && 1370 types.isArray(((JCFieldAccess) tree.meth).selected.type)) 1371 restype = ((JCFieldAccess) tree.meth).selected.type; 1372 1373 // as a special case, x.getClass() has type Class<? extends |X|> 1374 if (allowGenerics && 1375 methName == names.getClass && tree.args.isEmpty()) { 1376 Type qualifier = (tree.meth.getTag() == JCTree.SELECT) 1377 ? ((JCFieldAccess) tree.meth).selected.type 1378 : env.enclClass.sym.type; 1379 restype = new 1380 ClassType(restype.getEnclosingType(), 1381 List.<Type>of(new WildcardType(types.erasure(qualifier), 1382 BoundKind.EXTENDS, 1383 syms.boundClass)), 1384 restype.tsym); 1385 } 1386 1387 // as a special case, MethodHandle.<T>invoke(abc) and InvokeDynamic.<T>foo(abc) 1388 // has type <T>, and T can be a primitive type. 1389 if (tree.meth.getTag() == JCTree.SELECT && !typeargtypes.isEmpty()) { 1390 Type selt = ((JCFieldAccess) tree.meth).selected.type; 1391 if ((selt == syms.methodHandleType && methName == names.invoke) || selt == syms.invokeDynamicType) { 1392 assert types.isSameType(restype, typeargtypes.head) : mtype; 1393 typeargtypesNonRefOK = true; 1394 } 1395 } 1396 1397 if (!typeargtypesNonRefOK) { 1398 chk.checkRefTypes(tree.typeargs, typeargtypes); 1399 } 1400 1401 // Check that value of resulting type is admissible in the 1402 // current context. Also, capture the return type 1403 result = checkReturn(tree, capture(restype), VAL, pkind, pt); 1404 } 1405 chk.validate(tree.typeargs, localEnv); 1406 } 1407 //where 1408 /** Check that given application node appears as first statement 1409 * in a constructor call. 1410 * @param tree The application node 1411 * @param env The environment current at the application. 1412 */ 1413 boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) { 1414 JCMethodDecl enclMethod = env.enclMethod; 1415 if (enclMethod != null && enclMethod.name == names.init) { 1416 JCBlock body = enclMethod.body; 1417 if (body.stats.head.getTag() == JCTree.EXEC && 1418 ((JCExpressionStatement) body.stats.head).expr == tree) 1419 return true; 1420 } 1421 log.error(tree.pos(),"call.must.be.first.stmt.in.ctor", 1422 TreeInfo.name(tree.meth)); 1423 return false; 1424 } 1425 1426 /** Obtain a method type with given argument types. 1427 */ 1428 Type newMethTemplate(List<Type> argtypes, List<Type> typeargtypes) { 1429 MethodType mt = new MethodType(argtypes, null, null, syms.methodClass); 1430 return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt); 1431 } 1432 1433 public void visitNewClass(JCNewClass tree) { 1434 Type owntype = types.createErrorType(tree.type); 1435 1436 // The local environment of a class creation is 1437 // a new environment nested in the current one. 1438 Env<AttrContext> localEnv = env.dup(tree, env.info.dup()); 1439 1440 // The anonymous inner class definition of the new expression, 1441 // if one is defined by it. 1442 JCClassDecl cdef = tree.def; 1443 1444 // If enclosing class is given, attribute it, and 1445 // complete class name to be fully qualified 1446 JCExpression clazz = tree.clazz; // Class field following new 1447 JCExpression clazzid = // Identifier in class field 1448 (clazz.getTag() == JCTree.TYPEAPPLY) 1449 ? ((JCTypeApply) clazz).clazz 1450 : clazz; 1451 1452 JCExpression clazzid1 = clazzid; // The same in fully qualified form 1453 1454 if (tree.encl != null) { 1455 // We are seeing a qualified new, of the form 1456 // <expr>.new C <...> (...) ... 1457 // In this case, we let clazz stand for the name of the 1458 // allocated class C prefixed with the type of the qualifier 1459 // expression, so that we can 1460 // resolve it with standard techniques later. I.e., if 1461 // <expr> has type T, then <expr>.new C <...> (...) 1462 // yields a clazz T.C. 1463 Type encltype = chk.checkRefType(tree.encl.pos(), 1464 attribExpr(tree.encl, env)); 1465 clazzid1 = make.at(clazz.pos).Select(make.Type(encltype), 1466 ((JCIdent) clazzid).name); 1467 if (clazz.getTag() == JCTree.TYPEAPPLY) 1468 clazz = make.at(tree.pos). 1469 TypeApply(clazzid1, 1470 ((JCTypeApply) clazz).arguments); 1471 else 1472 clazz = clazzid1; 1473 // System.out.println(clazz + " generated.");//DEBUG 1474 } 1475 1476 // Attribute clazz expression and store 1477 // symbol + type back into the attributed tree. 1478 Type clazztype = attribType(clazz, env); 1479 chk.validate(clazz, localEnv); 1480 clazztype = chk.checkNewClassType(clazz.pos(), clazztype, true, pt); 1481 if (tree.encl != null) { 1482 // We have to work in this case to store 1483 // symbol + type back into the attributed tree. 1484 tree.clazz.type = clazztype; 1485 TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1)); 1486 clazzid.type = ((JCIdent) clazzid).sym.type; 1487 if (!clazztype.isErroneous()) { 1488 if (cdef != null && clazztype.tsym.isInterface()) { 1489 log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new"); 1490 } else if (clazztype.tsym.isStatic()) { 1491 log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym); 1492 } 1493 } 1494 } else if (!clazztype.tsym.isInterface() && 1495 clazztype.getEnclosingType().tag == CLASS) { 1496 // Check for the existence of an apropos outer instance 1497 rs.resolveImplicitThis(tree.pos(), env, clazztype); 1498 } 1499 1500 // Attribute constructor arguments. 1501 List<Type> argtypes = attribArgs(tree.args, localEnv); 1502 List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv); 1503 1504 // If we have made no mistakes in the class type... 1505 if (clazztype.tag == CLASS) { 1506 // Enums may not be instantiated except implicitly 1507 if (allowEnums && 1508 (clazztype.tsym.flags_field&Flags.ENUM) != 0 && 1509 (env.tree.getTag() != JCTree.VARDEF || 1510 (((JCVariableDecl) env.tree).mods.flags&Flags.ENUM) == 0 || 1511 ((JCVariableDecl) env.tree).init != tree)) 1512 log.error(tree.pos(), "enum.cant.be.instantiated"); 1513 // Check that class is not abstract 1514 if (cdef == null && 1515 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) { 1516 log.error(tree.pos(), "abstract.cant.be.instantiated", 1517 clazztype.tsym); 1518 } else if (cdef != null && clazztype.tsym.isInterface()) { 1519 // Check that no constructor arguments are given to 1520 // anonymous classes implementing an interface 1521 if (!argtypes.isEmpty()) 1522 log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args"); 1523 1524 if (!typeargtypes.isEmpty()) 1525 log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs"); 1526 1527 // Error recovery: pretend no arguments were supplied. 1528 argtypes = List.nil(); 1529 typeargtypes = List.nil(); 1530 } 1531 1532 // Resolve the called constructor under the assumption 1533 // that we are referring to a superclass instance of the 1534 // current instance (JLS ???). 1535 else { 1536 localEnv.info.selectSuper = cdef != null; 1537 localEnv.info.varArgs = false; 1538 tree.constructor = rs.resolveConstructor( 1539 tree.pos(), localEnv, clazztype, argtypes, typeargtypes); 1540 tree.constructorType = checkMethod(clazztype, 1541 tree.constructor, 1542 localEnv, 1543 tree.args, 1544 argtypes, 1545 typeargtypes, 1546 localEnv.info.varArgs); 1547 if (localEnv.info.varArgs) 1548 assert tree.constructorType.isErroneous() || tree.varargsElement != null; 1549 } 1550 1551 if (cdef != null) { 1552 // We are seeing an anonymous class instance creation. 1553 // In this case, the class instance creation 1554 // expression 1555 // 1556 // E.new <typeargs1>C<typargs2>(args) { ... } 1557 // 1558 // is represented internally as 1559 // 1560 // E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } ) . 1561 // 1562 // This expression is then *transformed* as follows: 1563 // 1564 // (1) add a STATIC flag to the class definition 1565 // if the current environment is static 1566 // (2) add an extends or implements clause 1567 // (3) add a constructor. 1568 // 1569 // For instance, if C is a class, and ET is the type of E, 1570 // the expression 1571 // 1572 // E.new <typeargs1>C<typargs2>(args) { ... } 1573 // 1574 // is translated to (where X is a fresh name and typarams is the 1575 // parameter list of the super constructor): 1576 // 1577 // new <typeargs1>X(<*nullchk*>E, args) where 1578 // X extends C<typargs2> { 1579 // <typarams> X(ET e, args) { 1580 // e.<typeargs1>super(args) 1581 // } 1582 // ... 1583 // } 1584 if (Resolve.isStatic(env)) cdef.mods.flags |= STATIC; 1585 clazz = TreeInfo.isDiamond(tree) ? 1586 make.Type(clazztype) 1587 : clazz; 1588 if (clazztype.tsym.isInterface()) { 1589 cdef.implementing = List.of(clazz); 1590 } else { 1591 cdef.extending = clazz; 1592 } 1593 1594 attribStat(cdef, localEnv); 1595 1596 // If an outer instance is given, 1597 // prefix it to the constructor arguments 1598 // and delete it from the new expression 1599 if (tree.encl != null && !clazztype.tsym.isInterface()) { 1600 tree.args = tree.args.prepend(makeNullCheck(tree.encl)); 1601 argtypes = argtypes.prepend(tree.encl.type); 1602 tree.encl = null; 1603 } 1604 1605 // Reassign clazztype and recompute constructor. 1606 clazztype = cdef.sym.type; 1607 Symbol sym = rs.resolveConstructor( 1608 tree.pos(), localEnv, clazztype, argtypes, 1609 typeargtypes, true, tree.varargsElement != null); 1610 assert sym.kind < AMBIGUOUS || tree.constructor.type.isErroneous(); 1611 tree.constructor = sym; 1612 if (tree.constructor.kind > ERRONEOUS) { 1613 tree.constructorType = syms.errType; 1614 } 1615 else { 1616 tree.constructorType = checkMethod(clazztype, 1617 tree.constructor, 1618 localEnv, 1619 tree.args, 1620 argtypes, 1621 typeargtypes, 1622 localEnv.info.varArgs); 1623 } 1624 } 1625 1626 if (tree.constructor != null && tree.constructor.kind == MTH) 1627 owntype = clazztype; 1628 } 1629 result = check(tree, owntype, VAL, pkind, pt); 1630 chk.validate(tree.typeargs, localEnv); 1631 } 1632 1633 /** Make an attributed null check tree. 1634 */ 1635 public JCExpression makeNullCheck(JCExpression arg) { 1636 // optimization: X.this is never null; skip null check 1637 Name name = TreeInfo.name(arg); 1638 if (name == names._this || name == names._super) return arg; 1639 1640 int optag = JCTree.NULLCHK; 1641 JCUnary tree = make.at(arg.pos).Unary(optag, arg); 1642 tree.operator = syms.nullcheck; 1643 tree.type = arg.type; 1644 return tree; 1645 } 1646 1647 public void visitNewArray(JCNewArray tree) { 1648 Type owntype = types.createErrorType(tree.type); 1649 Type elemtype; 1650 if (tree.elemtype != null) { 1651 elemtype = attribType(tree.elemtype, env); 1652 chk.validate(tree.elemtype, env); 1653 owntype = elemtype; 1654 for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) { 1655 attribExpr(l.head, env, syms.intType); 1656 owntype = new ArrayType(owntype, syms.arrayClass); 1657 } 1658 } else { 1659 // we are seeing an untyped aggregate { ... } 1660 // this is allowed only if the prototype is an array 1661 if (pt.tag == ARRAY) { 1662 elemtype = types.elemtype(pt); 1663 } else { 1664 if (pt.tag != ERROR) { 1665 log.error(tree.pos(), "illegal.initializer.for.type", 1666 pt); 1667 } 1668 elemtype = types.createErrorType(pt); 1669 } 1670 } 1671 if (tree.elems != null) { 1672 attribExprs(tree.elems, env, elemtype); 1673 owntype = new ArrayType(elemtype, syms.arrayClass); 1674 } 1675 if (!types.isReifiable(elemtype)) 1676 log.error(tree.pos(), "generic.array.creation"); 1677 result = check(tree, owntype, VAL, pkind, pt); 1678 } 1679 1680 public void visitParens(JCParens tree) { 1681 Type owntype = attribTree(tree.expr, env, pkind, pt); 1682 result = check(tree, owntype, pkind, pkind, pt); 1683 Symbol sym = TreeInfo.symbol(tree); 1684 if (sym != null && (sym.kind&(TYP|PCK)) != 0) 1685 log.error(tree.pos(), "illegal.start.of.type"); 1686 } 1687 1688 public void visitAssign(JCAssign tree) { 1689 Type owntype = attribTree(tree.lhs, env.dup(tree), VAR, Type.noType); 1690 Type capturedType = capture(owntype); 1691 attribExpr(tree.rhs, env, owntype); 1692 result = check(tree, capturedType, VAL, pkind, pt); 1693 } 1694 1695 public void visitAssignop(JCAssignOp tree) { 1696 // Attribute arguments. 1697 Type owntype = attribTree(tree.lhs, env, VAR, Type.noType); 1698 Type operand = attribExpr(tree.rhs, env); 1699 // Find operator. 1700 Symbol operator = tree.operator = rs.resolveBinaryOperator( 1701 tree.pos(), tree.getTag() - JCTree.ASGOffset, env, 1702 owntype, operand); 1703 1704 if (operator.kind == MTH) { 1705 chk.checkOperator(tree.pos(), 1706 (OperatorSymbol)operator, 1707 tree.getTag() - JCTree.ASGOffset, 1708 owntype, 1709 operand); 1710 chk.checkDivZero(tree.rhs.pos(), operator, operand); 1711 chk.checkCastable(tree.rhs.pos(), 1712 operator.type.getReturnType(), 1713 owntype); 1714 } 1715 result = check(tree, owntype, VAL, pkind, pt); 1716 } 1717 1718 public void visitUnary(JCUnary tree) { 1719 // Attribute arguments. 1720 Type argtype = (JCTree.PREINC <= tree.getTag() && tree.getTag() <= JCTree.POSTDEC) 1721 ? attribTree(tree.arg, env, VAR, Type.noType) 1722 : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env)); 1723 1724 // Find operator. 1725 Symbol operator = tree.operator = 1726 rs.resolveUnaryOperator(tree.pos(), tree.getTag(), env, argtype); 1727 1728 Type owntype = types.createErrorType(tree.type); 1729 if (operator.kind == MTH) { 1730 owntype = (JCTree.PREINC <= tree.getTag() && tree.getTag() <= JCTree.POSTDEC) 1731 ? tree.arg.type 1732 : operator.type.getReturnType(); 1733 int opc = ((OperatorSymbol)operator).opcode; 1734 1735 // If the argument is constant, fold it. 1736 if (argtype.constValue() != null) { 1737 Type ctype = cfolder.fold1(opc, argtype); 1738 if (ctype != null) { 1739 owntype = cfolder.coerce(ctype, owntype); 1740 1741 // Remove constant types from arguments to 1742 // conserve space. The parser will fold concatenations 1743 // of string literals; the code here also 1744 // gets rid of intermediate results when some of the 1745 // operands are constant identifiers. 1746 if (tree.arg.type.tsym == syms.stringType.tsym) { 1747 tree.arg.type = syms.stringType; 1748 } 1749 } 1750 } 1751 } 1752 result = check(tree, owntype, VAL, pkind, pt); 1753 } 1754 1755 public void visitBinary(JCBinary tree) { 1756 // Attribute arguments. 1757 Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env)); 1758 Type right = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.rhs, env)); 1759 1760 // Find operator. 1761 Symbol operator = tree.operator = 1762 rs.resolveBinaryOperator(tree.pos(), tree.getTag(), env, left, right); 1763 1764 Type owntype = types.createErrorType(tree.type); 1765 if (operator.kind == MTH) { 1766 owntype = operator.type.getReturnType(); 1767 int opc = chk.checkOperator(tree.lhs.pos(), 1768 (OperatorSymbol)operator, 1769 tree.getTag(), 1770 left, 1771 right); 1772 1773 // If both arguments are constants, fold them. 1774 if (left.constValue() != null && right.constValue() != null) { 1775 Type ctype = cfolder.fold2(opc, left, right); 1776 if (ctype != null) { 1777 owntype = cfolder.coerce(ctype, owntype); 1778 1779 // Remove constant types from arguments to 1780 // conserve space. The parser will fold concatenations 1781 // of string literals; the code here also 1782 // gets rid of intermediate results when some of the 1783 // operands are constant identifiers. 1784 if (tree.lhs.type.tsym == syms.stringType.tsym) { 1785 tree.lhs.type = syms.stringType; 1786 } 1787 if (tree.rhs.type.tsym == syms.stringType.tsym) { 1788 tree.rhs.type = syms.stringType; 1789 } 1790 } 1791 } 1792 1793 // Check that argument types of a reference ==, != are 1794 // castable to each other, (JLS???). 1795 if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) { 1796 if (!types.isCastable(left, right, new Warner(tree.pos()))) { 1797 log.error(tree.pos(), "incomparable.types", left, right); 1798 } 1799 } 1800 1801 chk.checkDivZero(tree.rhs.pos(), operator, right); 1802 } 1803 result = check(tree, owntype, VAL, pkind, pt); 1804 } 1805 1806 public void visitTypeCast(JCTypeCast tree) { 1807 Type clazztype = attribType(tree.clazz, env); 1808 chk.validate(tree.clazz, env); 1809 Type exprtype = attribExpr(tree.expr, env, Infer.anyPoly); 1810 Type owntype = chk.checkCastable(tree.expr.pos(), exprtype, clazztype); 1811 if (exprtype.constValue() != null) 1812 owntype = cfolder.coerce(exprtype, owntype); 1813 result = check(tree, capture(owntype), VAL, pkind, pt); 1814 } 1815 1816 public void visitTypeTest(JCInstanceOf tree) { 1817 Type exprtype = chk.checkNullOrRefType( 1818 tree.expr.pos(), attribExpr(tree.expr, env)); 1819 Type clazztype = chk.checkReifiableReferenceType( 1820 tree.clazz.pos(), attribType(tree.clazz, env)); 1821 chk.validate(tree.clazz, env); 1822 chk.checkCastable(tree.expr.pos(), exprtype, clazztype); 1823 result = check(tree, syms.booleanType, VAL, pkind, pt); 1824 } 1825 1826 public void visitIndexed(JCArrayAccess tree) { 1827 Type owntype = types.createErrorType(tree.type); 1828 Type atype = attribExpr(tree.indexed, env); 1829 attribExpr(tree.index, env, syms.intType); 1830 if (types.isArray(atype)) 1831 owntype = types.elemtype(atype); 1832 else if (atype.tag != ERROR) 1833 log.error(tree.pos(), "array.req.but.found", atype); 1834 if ((pkind & VAR) == 0) owntype = capture(owntype); 1835 result = check(tree, owntype, VAR, pkind, pt); 1836 } 1837 1838 public void visitIdent(JCIdent tree) { 1839 Symbol sym; 1840 boolean varArgs = false; 1841 1842 // Find symbol 1843 if (pt.tag == METHOD || pt.tag == FORALL) { 1844 // If we are looking for a method, the prototype `pt' will be a 1845 // method type with the type of the call's arguments as parameters. 1846 env.info.varArgs = false; 1847 sym = rs.resolveMethod(tree.pos(), env, tree.name, pt.getParameterTypes(), pt.getTypeArguments()); 1848 varArgs = env.info.varArgs; 1849 } else if (tree.sym != null && tree.sym.kind != VAR) { 1850 sym = tree.sym; 1851 } else { 1852 sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind); 1853 } 1854 tree.sym = sym; 1855 1856 // (1) Also find the environment current for the class where 1857 // sym is defined (`symEnv'). 1858 // Only for pre-tiger versions (1.4 and earlier): 1859 // (2) Also determine whether we access symbol out of an anonymous 1860 // class in a this or super call. This is illegal for instance 1861 // members since such classes don't carry a this$n link. 1862 // (`noOuterThisPath'). 1863 Env<AttrContext> symEnv = env; 1864 boolean noOuterThisPath = false; 1865 if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class 1866 (sym.kind & (VAR | MTH | TYP)) != 0 && 1867 sym.owner.kind == TYP && 1868 tree.name != names._this && tree.name != names._super) { 1869 1870 // Find environment in which identifier is defined. 1871 while (symEnv.outer != null && 1872 !sym.isMemberOf(symEnv.enclClass.sym, types)) { 1873 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0) 1874 noOuterThisPath = !allowAnonOuterThis; 1875 symEnv = symEnv.outer; 1876 } 1877 } 1878 1879 // If symbol is a variable, ... 1880 if (sym.kind == VAR) { 1881 VarSymbol v = (VarSymbol)sym; 1882 1883 // ..., evaluate its initializer, if it has one, and check for 1884 // illegal forward reference. 1885 checkInit(tree, env, v, false); 1886 1887 // If symbol is a local variable accessed from an embedded 1888 // inner class check that it is final. 1889 if (v.owner.kind == MTH && 1890 v.owner != env.info.scope.owner && 1891 (v.flags_field & FINAL) == 0) { 1892 log.error(tree.pos(), 1893 "local.var.accessed.from.icls.needs.final", 1894 v); 1895 } 1896 1897 // If we are expecting a variable (as opposed to a value), check 1898 // that the variable is assignable in the current environment. 1899 if (pkind == VAR) 1900 checkAssignable(tree.pos(), v, null, env); 1901 } 1902 1903 // In a constructor body, 1904 // if symbol is a field or instance method, check that it is 1905 // not accessed before the supertype constructor is called. 1906 if ((symEnv.info.isSelfCall || noOuterThisPath) && 1907 (sym.kind & (VAR | MTH)) != 0 && 1908 sym.owner.kind == TYP && 1909 (sym.flags() & STATIC) == 0) { 1910 chk.earlyRefError(tree.pos(), sym.kind == VAR ? sym : thisSym(tree.pos(), env)); 1911 } 1912 Env<AttrContext> env1 = env; 1913 if (sym.kind != ERR && sym.kind != TYP && sym.owner != null && sym.owner != env1.enclClass.sym) { 1914 // If the found symbol is inaccessible, then it is 1915 // accessed through an enclosing instance. Locate this 1916 // enclosing instance: 1917 while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym)) 1918 env1 = env1.outer; 1919 } 1920 result = checkId(tree, env1.enclClass.sym.type, sym, env, pkind, pt, varArgs); 1921 } 1922 1923 public void visitSelect(JCFieldAccess tree) { 1924 // Determine the expected kind of the qualifier expression. 1925 int skind = 0; 1926 if (tree.name == names._this || tree.name == names._super || 1927 tree.name == names._class) 1928 { 1929 skind = TYP; 1930 } else { 1931 if ((pkind & PCK) != 0) skind = skind | PCK; 1932 if ((pkind & TYP) != 0) skind = skind | TYP | PCK; 1933 if ((pkind & (VAL | MTH)) != 0) skind = skind | VAL | TYP; 1934 } 1935 1936 // Attribute the qualifier expression, and determine its symbol (if any). 1937 Type site = attribTree(tree.selected, env, skind, Infer.anyPoly); 1938 if ((pkind & (PCK | TYP)) == 0) 1939 site = capture(site); // Capture field access 1940 1941 // don't allow T.class T[].class, etc 1942 if (skind == TYP) { 1943 Type elt = site; 1944 while (elt.tag == ARRAY) 1945 elt = ((ArrayType)elt).elemtype; 1946 if (elt.tag == TYPEVAR) { 1947 log.error(tree.pos(), "type.var.cant.be.deref"); 1948 result = types.createErrorType(tree.type); 1949 return; 1950 } 1951 } 1952 1953 // If qualifier symbol is a type or `super', assert `selectSuper' 1954 // for the selection. This is relevant for determining whether 1955 // protected symbols are accessible. 1956 Symbol sitesym = TreeInfo.symbol(tree.selected); 1957 boolean selectSuperPrev = env.info.selectSuper; 1958 env.info.selectSuper = 1959 sitesym != null && 1960 sitesym.name == names._super; 1961 1962 // If selected expression is polymorphic, strip 1963 // type parameters and remember in env.info.tvars, so that 1964 // they can be added later (in Attr.checkId and Infer.instantiateMethod). 1965 if (tree.selected.type.tag == FORALL) { 1966 ForAll pstype = (ForAll)tree.selected.type; 1967 env.info.tvars = pstype.tvars; 1968 site = tree.selected.type = pstype.qtype; 1969 } 1970 1971 // Determine the symbol represented by the selection. 1972 env.info.varArgs = false; 1973 Symbol sym = selectSym(tree, site, env, pt, pkind); 1974 if (sym.exists() && !isType(sym) && (pkind & (PCK | TYP)) != 0) { 1975 site = capture(site); 1976 sym = selectSym(tree, site, env, pt, pkind); 1977 } 1978 boolean varArgs = env.info.varArgs; 1979 tree.sym = sym; 1980 1981 if (site.tag == TYPEVAR && !isType(sym) && sym.kind != ERR) { 1982 while (site.tag == TYPEVAR) site = site.getUpperBound(); 1983 site = capture(site); 1984 } 1985 1986 // If that symbol is a variable, ... 1987 if (sym.kind == VAR) { 1988 VarSymbol v = (VarSymbol)sym; 1989 1990 // ..., evaluate its initializer, if it has one, and check for 1991 // illegal forward reference. 1992 checkInit(tree, env, v, true); 1993 1994 // If we are expecting a variable (as opposed to a value), check 1995 // that the variable is assignable in the current environment. 1996 if (pkind == VAR) 1997 checkAssignable(tree.pos(), v, tree.selected, env); 1998 } 1999 2000 // Disallow selecting a type from an expression 2001 if (isType(sym) && (sitesym==null || (sitesym.kind&(TYP|PCK)) == 0)) { 2002 tree.type = check(tree.selected, pt, 2003 sitesym == null ? VAL : sitesym.kind, TYP|PCK, pt); 2004 } 2005 2006 if (isType(sitesym)) { 2007 if (sym.name == names._this) { 2008 // If `C' is the currently compiled class, check that 2009 // C.this' does not appear in a call to a super(...) 2010 if (env.info.isSelfCall && 2011 site.tsym == env.enclClass.sym) { 2012 chk.earlyRefError(tree.pos(), sym); 2013 } 2014 } else { 2015 // Check if type-qualified fields or methods are static (JLS) 2016 if ((sym.flags() & STATIC) == 0 && 2017 sym.name != names._super && 2018 (sym.kind == VAR || sym.kind == MTH)) { 2019 rs.access(rs.new StaticError(sym), 2020 tree.pos(), site, sym.name, true); 2021 } 2022 } 2023 } 2024 2025 // If we are selecting an instance member via a `super', ... 2026 if (env.info.selectSuper && (sym.flags() & STATIC) == 0) { 2027 2028 // Check that super-qualified symbols are not abstract (JLS) 2029 rs.checkNonAbstract(tree.pos(), sym); 2030 2031 if (site.isRaw()) { 2032 // Determine argument types for site. 2033 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym); 2034 if (site1 != null) site = site1; 2035 } 2036 } 2037 2038 env.info.selectSuper = selectSuperPrev; 2039 result = checkId(tree, site, sym, env, pkind, pt, varArgs); 2040 env.info.tvars = List.nil(); 2041 } 2042 //where 2043 /** Determine symbol referenced by a Select expression, 2044 * 2045 * @param tree The select tree. 2046 * @param site The type of the selected expression, 2047 * @param env The current environment. 2048 * @param pt The current prototype. 2049 * @param pkind The expected kind(s) of the Select expression. 2050 */ 2051 private Symbol selectSym(JCFieldAccess tree, 2052 Type site, 2053 Env<AttrContext> env, 2054 Type pt, 2055 int pkind) { 2056 DiagnosticPosition pos = tree.pos(); 2057 Name name = tree.name; 2058 2059 switch (site.tag) { 2060 case PACKAGE: 2061 return rs.access( 2062 rs.findIdentInPackage(env, site.tsym, name, pkind), 2063 pos, site, name, true); 2064 case ARRAY: 2065 case CLASS: 2066 if (pt.tag == METHOD || pt.tag == FORALL) { 2067 return rs.resolveQualifiedMethod( 2068 pos, env, site, name, pt.getParameterTypes(), pt.getTypeArguments()); 2069 } else if (name == names._this || name == names._super) { 2070 return rs.resolveSelf(pos, env, site.tsym, name); 2071 } else if (name == names._class) { 2072 // In this case, we have already made sure in 2073 // visitSelect that qualifier expression is a type. 2074 Type t = syms.classType; 2075 List<Type> typeargs = allowGenerics 2076 ? List.of(types.erasure(site)) 2077 : List.<Type>nil(); 2078 t = new ClassType(t.getEnclosingType(), typeargs, t.tsym); 2079 return new VarSymbol( 2080 STATIC | PUBLIC | FINAL, names._class, t, site.tsym); 2081 } else { 2082 // We are seeing a plain identifier as selector. 2083 Symbol sym = rs.findIdentInType(env, site, name, pkind); 2084 if ((pkind & ERRONEOUS) == 0) 2085 sym = rs.access(sym, pos, site, name, true); 2086 return sym; 2087 } 2088 case WILDCARD: 2089 throw new AssertionError(tree); 2090 case TYPEVAR: 2091 // Normally, site.getUpperBound() shouldn't be null. 2092 // It should only happen during memberEnter/attribBase 2093 // when determining the super type which *must* be 2094 // done before attributing the type variables. In 2095 // other words, we are seeing this illegal program: 2096 // class B<T> extends A<T.foo> {} 2097 Symbol sym = (site.getUpperBound() != null) 2098 ? selectSym(tree, capture(site.getUpperBound()), env, pt, pkind) 2099 : null; 2100 if (sym == null) { 2101 log.error(pos, "type.var.cant.be.deref"); 2102 return syms.errSymbol; 2103 } else { 2104 Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ? 2105 rs.new AccessError(env, site, sym) : 2106 sym; 2107 rs.access(sym2, pos, site, name, true); 2108 return sym; 2109 } 2110 case ERROR: 2111 // preserve identifier names through errors 2112 return types.createErrorType(name, site.tsym, site).tsym; 2113 default: 2114 // The qualifier expression is of a primitive type -- only 2115 // .class is allowed for these. 2116 if (name == names._class) { 2117 // In this case, we have already made sure in Select that 2118 // qualifier expression is a type. 2119 Type t = syms.classType; 2120 Type arg = types.boxedClass(site).type; 2121 t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym); 2122 return new VarSymbol( 2123 STATIC | PUBLIC | FINAL, names._class, t, site.tsym); 2124 } else { 2125 log.error(pos, "cant.deref", site); 2126 return syms.errSymbol; 2127 } 2128 } 2129 } 2130 2131 /** Determine type of identifier or select expression and check that 2132 * (1) the referenced symbol is not deprecated 2133 * (2) the symbol's type is safe (@see checkSafe) 2134 * (3) if symbol is a variable, check that its type and kind are 2135 * compatible with the prototype and protokind. 2136 * (4) if symbol is an instance field of a raw type, 2137 * which is being assigned to, issue an unchecked warning if its 2138 * type changes under erasure. 2139 * (5) if symbol is an instance method of a raw type, issue an 2140 * unchecked warning if its argument types change under erasure. 2141 * If checks succeed: 2142 * If symbol is a constant, return its constant type 2143 * else if symbol is a method, return its result type 2144 * otherwise return its type. 2145 * Otherwise return errType. 2146 * 2147 * @param tree The syntax tree representing the identifier 2148 * @param site If this is a select, the type of the selected 2149 * expression, otherwise the type of the current class. 2150 * @param sym The symbol representing the identifier. 2151 * @param env The current environment. 2152 * @param pkind The set of expected kinds. 2153 * @param pt The expected type. 2154 */ 2155 Type checkId(JCTree tree, 2156 Type site, 2157 Symbol sym, 2158 Env<AttrContext> env, 2159 int pkind, 2160 Type pt, 2161 boolean useVarargs) { 2162 if (pt.isErroneous()) return types.createErrorType(site); 2163 Type owntype; // The computed type of this identifier occurrence. 2164 switch (sym.kind) { 2165 case TYP: 2166 // For types, the computed type equals the symbol's type, 2167 // except for two situations: 2168 owntype = sym.type; 2169 if (owntype.tag == CLASS) { 2170 Type ownOuter = owntype.getEnclosingType(); 2171 2172 // (a) If the symbol's type is parameterized, erase it 2173 // because no type parameters were given. 2174 // We recover generic outer type later in visitTypeApply. 2175 if (owntype.tsym.type.getTypeArguments().nonEmpty()) { 2176 owntype = types.erasure(owntype); 2177 } 2178 2179 // (b) If the symbol's type is an inner class, then 2180 // we have to interpret its outer type as a superclass 2181 // of the site type. Example: 2182 // 2183 // class Tree<A> { class Visitor { ... } } 2184 // class PointTree extends Tree<Point> { ... } 2185 // ...PointTree.Visitor... 2186 // 2187 // Then the type of the last expression above is 2188 // Tree<Point>.Visitor. 2189 else if (ownOuter.tag == CLASS && site != ownOuter) { 2190 Type normOuter = site; 2191 if (normOuter.tag == CLASS) 2192 normOuter = types.asEnclosingSuper(site, ownOuter.tsym); 2193 if (normOuter == null) // perhaps from an import 2194 normOuter = types.erasure(ownOuter); 2195 if (normOuter != ownOuter) 2196 owntype = new ClassType( 2197 normOuter, List.<Type>nil(), owntype.tsym); 2198 } 2199 } 2200 break; 2201 case VAR: 2202 VarSymbol v = (VarSymbol)sym; 2203 // Test (4): if symbol is an instance field of a raw type, 2204 // which is being assigned to, issue an unchecked warning if 2205 // its type changes under erasure. 2206 if (allowGenerics && 2207 pkind == VAR && 2208 v.owner.kind == TYP && 2209 (v.flags() & STATIC) == 0 && 2210 (site.tag == CLASS || site.tag == TYPEVAR)) { 2211 Type s = types.asOuterSuper(site, v.owner); 2212 if (s != null && 2213 s.isRaw() && 2214 !types.isSameType(v.type, v.erasure(types))) { 2215 chk.warnUnchecked(tree.pos(), 2216 "unchecked.assign.to.var", 2217 v, s); 2218 } 2219 } 2220 // The computed type of a variable is the type of the 2221 // variable symbol, taken as a member of the site type. 2222 owntype = (sym.owner.kind == TYP && 2223 sym.name != names._this && sym.name != names._super) 2224 ? types.memberType(site, sym) 2225 : sym.type; 2226 2227 if (env.info.tvars.nonEmpty()) { 2228 Type owntype1 = new ForAll(env.info.tvars, owntype); 2229 for (List<Type> l = env.info.tvars; l.nonEmpty(); l = l.tail) 2230 if (!owntype.contains(l.head)) { 2231 log.error(tree.pos(), "undetermined.type", owntype1); 2232 owntype1 = types.createErrorType(owntype1); 2233 } 2234 owntype = owntype1; 2235 } 2236 2237 // If the variable is a constant, record constant value in 2238 // computed type. 2239 if (v.getConstValue() != null && isStaticReference(tree)) 2240 owntype = owntype.constType(v.getConstValue()); 2241 2242 if (pkind == VAL) { 2243 owntype = capture(owntype); // capture "names as expressions" 2244 } 2245 break; 2246 case MTH: { 2247 JCMethodInvocation app = (JCMethodInvocation)env.tree; 2248 owntype = checkMethod(site, sym, env, app.args, 2249 pt.getParameterTypes(), pt.getTypeArguments(), 2250 env.info.varArgs); 2251 break; 2252 } 2253 case PCK: case ERR: 2254 owntype = sym.type; 2255 break; 2256 default: 2257 throw new AssertionError("unexpected kind: " + sym.kind + 2258 " in tree " + tree); 2259 } 2260 2261 // Test (1): emit a `deprecation' warning if symbol is deprecated. 2262 // (for constructors, the error was given when the constructor was 2263 // resolved) 2264 if (sym.name != names.init && 2265 (sym.flags() & DEPRECATED) != 0 && 2266 (env.info.scope.owner.flags() & DEPRECATED) == 0 && 2267 sym.outermostClass() != env.info.scope.owner.outermostClass()) 2268 chk.warnDeprecated(tree.pos(), sym); 2269 2270 if ((sym.flags() & PROPRIETARY) != 0) { 2271 if (enableSunApiLintControl) 2272 chk.warnSunApi(tree.pos(), "sun.proprietary", sym); 2273 else 2274 log.strictWarning(tree.pos(), "sun.proprietary", sym); 2275 } 2276 2277 // Test (3): if symbol is a variable, check that its type and 2278 // kind are compatible with the prototype and protokind. 2279 return check(tree, owntype, sym.kind, pkind, pt); 2280 } 2281 2282 /** Check that variable is initialized and evaluate the variable's 2283 * initializer, if not yet done. Also check that variable is not 2284 * referenced before it is defined. 2285 * @param tree The tree making up the variable reference. 2286 * @param env The current environment. 2287 * @param v The variable's symbol. 2288 */ 2289 private void checkInit(JCTree tree, 2290 Env<AttrContext> env, 2291 VarSymbol v, 2292 boolean onlyWarning) { 2293 // System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " + 2294 // tree.pos + " " + v.pos + " " + 2295 // Resolve.isStatic(env));//DEBUG 2296 2297 // A forward reference is diagnosed if the declaration position 2298 // of the variable is greater than the current tree position 2299 // and the tree and variable definition occur in the same class 2300 // definition. Note that writes don't count as references. 2301 // This check applies only to class and instance 2302 // variables. Local variables follow different scope rules, 2303 // and are subject to definite assignment checking. 2304 if ((env.info.enclVar == v || v.pos > tree.pos) && 2305 v.owner.kind == TYP && 2306 canOwnInitializer(env.info.scope.owner) && 2307 v.owner == env.info.scope.owner.enclClass() && 2308 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) && 2309 (env.tree.getTag() != JCTree.ASSIGN || 2310 TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) { 2311 String suffix = (env.info.enclVar == v) ? 2312 "self.ref" : "forward.ref"; 2313 if (!onlyWarning || isStaticEnumField(v)) { 2314 log.error(tree.pos(), "illegal." + suffix); 2315 } else if (useBeforeDeclarationWarning) { 2316 log.warning(tree.pos(), suffix, v); 2317 } 2318 } 2319 2320 v.getConstValue(); // ensure initializer is evaluated 2321 2322 checkEnumInitializer(tree, env, v); 2323 } 2324 2325 /** 2326 * Check for illegal references to static members of enum. In 2327 * an enum type, constructors and initializers may not 2328 * reference its static members unless they are constant. 2329 * 2330 * @param tree The tree making up the variable reference. 2331 * @param env The current environment. 2332 * @param v The variable's symbol. 2333 * @see JLS 3rd Ed. (8.9 Enums) 2334 */ 2335 private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) { 2336 // JLS 3rd Ed.: 2337 // 2338 // "It is a compile-time error to reference a static field 2339 // of an enum type that is not a compile-time constant 2340 // (15.28) from constructors, instance initializer blocks, 2341 // or instance variable initializer expressions of that 2342 // type. It is a compile-time error for the constructors, 2343 // instance initializer blocks, or instance variable 2344 // initializer expressions of an enum constant e to refer 2345 // to itself or to an enum constant of the same type that 2346 // is declared to the right of e." 2347 if (isStaticEnumField(v)) { 2348 ClassSymbol enclClass = env.info.scope.owner.enclClass(); 2349 2350 if (enclClass == null || enclClass.owner == null) 2351 return; 2352 2353 // See if the enclosing class is the enum (or a 2354 // subclass thereof) declaring v. If not, this 2355 // reference is OK. 2356 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type)) 2357 return; 2358 2359 // If the reference isn't from an initializer, then 2360 // the reference is OK. 2361 if (!Resolve.isInitializer(env)) 2362 return; 2363 2364 log.error(tree.pos(), "illegal.enum.static.ref"); 2365 } 2366 } 2367 2368 /** Is the given symbol a static, non-constant field of an Enum? 2369 * Note: enum literals should not be regarded as such 2370 */ 2371 private boolean isStaticEnumField(VarSymbol v) { 2372 return Flags.isEnum(v.owner) && 2373 Flags.isStatic(v) && 2374 !Flags.isConstant(v) && 2375 v.name != names._class; 2376 } 2377 2378 /** Can the given symbol be the owner of code which forms part 2379 * if class initialization? This is the case if the symbol is 2380 * a type or field, or if the symbol is the synthetic method. 2381 * owning a block. 2382 */ 2383 private boolean canOwnInitializer(Symbol sym) { 2384 return 2385 (sym.kind & (VAR | TYP)) != 0 || 2386 (sym.kind == MTH && (sym.flags() & BLOCK) != 0); 2387 } 2388 2389 Warner noteWarner = new Warner(); 2390 2391 /** 2392 * Check that method arguments conform to its instantation. 2393 **/ 2394 public Type checkMethod(Type site, 2395 Symbol sym, 2396 Env<AttrContext> env, 2397 final List<JCExpression> argtrees, 2398 List<Type> argtypes, 2399 List<Type> typeargtypes, 2400 boolean useVarargs) { 2401 // Test (5): if symbol is an instance method of a raw type, issue 2402 // an unchecked warning if its argument types change under erasure. 2403 if (allowGenerics && 2404 (sym.flags() & STATIC) == 0 && 2405 (site.tag == CLASS || site.tag == TYPEVAR)) { 2406 Type s = types.asOuterSuper(site, sym.owner); 2407 if (s != null && s.isRaw() && 2408 !types.isSameTypes(sym.type.getParameterTypes(), 2409 sym.erasure(types).getParameterTypes())) { 2410 chk.warnUnchecked(env.tree.pos(), 2411 "unchecked.call.mbr.of.raw.type", 2412 sym, s); 2413 } 2414 } 2415 2416 // Compute the identifier's instantiated type. 2417 // For methods, we need to compute the instance type by 2418 // Resolve.instantiate from the symbol's type as well as 2419 // any type arguments and value arguments. 2420 noteWarner.warned = false; 2421 Type owntype = rs.instantiate(env, 2422 site, 2423 sym, 2424 argtypes, 2425 typeargtypes, 2426 true, 2427 useVarargs, 2428 noteWarner); 2429 boolean warned = noteWarner.warned; 2430 2431 // If this fails, something went wrong; we should not have 2432 // found the identifier in the first place. 2433 if (owntype == null) { 2434 if (!pt.isErroneous()) 2435 log.error(env.tree.pos(), 2436 "internal.error.cant.instantiate", 2437 sym, site, 2438 Type.toString(pt.getParameterTypes())); 2439 owntype = types.createErrorType(site); 2440 } else { 2441 // System.out.println("call : " + env.tree); 2442 // System.out.println("method : " + owntype); 2443 // System.out.println("actuals: " + argtypes); 2444 List<Type> formals = owntype.getParameterTypes(); 2445 Type last = useVarargs ? formals.last() : null; 2446 if (sym.name==names.init && 2447 sym.owner == syms.enumSym) 2448 formals = formals.tail.tail; 2449 List<JCExpression> args = argtrees; 2450 while (formals.head != last) { 2451 JCTree arg = args.head; 2452 Warner warn = chk.convertWarner(arg.pos(), arg.type, formals.head); 2453 assertConvertible(arg, arg.type, formals.head, warn); 2454 warned |= warn.warned; 2455 args = args.tail; 2456 formals = formals.tail; 2457 } 2458 if (useVarargs) { 2459 Type varArg = types.elemtype(last); 2460 while (args.tail != null) { 2461 JCTree arg = args.head; 2462 Warner warn = chk.convertWarner(arg.pos(), arg.type, varArg); 2463 assertConvertible(arg, arg.type, varArg, warn); 2464 warned |= warn.warned; 2465 args = args.tail; 2466 } 2467 } else if ((sym.flags() & VARARGS) != 0 && allowVarargs) { 2468 // non-varargs call to varargs method 2469 Type varParam = owntype.getParameterTypes().last(); 2470 Type lastArg = argtypes.last(); 2471 if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) && 2472 !types.isSameType(types.erasure(varParam), types.erasure(lastArg))) 2473 log.warning(argtrees.last().pos(), "inexact.non-varargs.call", 2474 types.elemtype(varParam), 2475 varParam); 2476 } 2477 2478 if (warned && sym.type.tag == FORALL) { 2479 chk.warnUnchecked(env.tree.pos(), 2480 "unchecked.meth.invocation.applied", 2481 kindName(sym), 2482 sym.name, 2483 rs.methodArguments(sym.type.getParameterTypes()), 2484 rs.methodArguments(argtypes), 2485 kindName(sym.location()), 2486 sym.location()); 2487 owntype = new MethodType(owntype.getParameterTypes(), 2488 types.erasure(owntype.getReturnType()), 2489 owntype.getThrownTypes(), 2490 syms.methodClass); 2491 } 2492 if (useVarargs) { 2493 JCTree tree = env.tree; 2494 Type argtype = owntype.getParameterTypes().last(); 2495 if (!types.isReifiable(argtype)) 2496 chk.warnUnchecked(env.tree.pos(), 2497 "unchecked.generic.array.creation", 2498 argtype); 2499 Type elemtype = types.elemtype(argtype); 2500 switch (tree.getTag()) { 2501 case JCTree.APPLY: 2502 ((JCMethodInvocation) tree).varargsElement = elemtype; 2503 break; 2504 case JCTree.NEWCLASS: 2505 ((JCNewClass) tree).varargsElement = elemtype; 2506 break; 2507 default: 2508 throw new AssertionError(""+tree); 2509 } 2510 } 2511 } 2512 return owntype; 2513 } 2514 2515 private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) { 2516 if (types.isConvertible(actual, formal, warn)) 2517 return; 2518 2519 if (formal.isCompound() 2520 && types.isSubtype(actual, types.supertype(formal)) 2521 && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn)) 2522 return; 2523 2524 if (false) { 2525 // TODO: make assertConvertible work 2526 chk.typeError(tree.pos(), diags.fragment("incompatible.types"), actual, formal); 2527 throw new AssertionError("Tree: " + tree 2528 + " actual:" + actual 2529 + " formal: " + formal); 2530 } 2531 } 2532 2533 public void visitLiteral(JCLiteral tree) { 2534 result = check( 2535 tree, litType(tree.typetag).constType(tree.value), VAL, pkind, pt); 2536 } 2537 //where 2538 /** Return the type of a literal with given type tag. 2539 */ 2540 Type litType(int tag) { 2541 return (tag == TypeTags.CLASS) ? syms.stringType : syms.typeOfTag[tag]; 2542 } 2543 2544 public void visitTypeIdent(JCPrimitiveTypeTree tree) { 2545 result = check(tree, syms.typeOfTag[tree.typetag], TYP, pkind, pt); 2546 } 2547 2548 public void visitTypeArray(JCArrayTypeTree tree) { 2549 Type etype = attribType(tree.elemtype, env); 2550 Type type = new ArrayType(etype, syms.arrayClass); 2551 result = check(tree, type, TYP, pkind, pt); 2552 } 2553 2554 /** Visitor method for parameterized types. 2555 * Bound checking is left until later, since types are attributed 2556 * before supertype structure is completely known 2557 */ 2558 public void visitTypeApply(JCTypeApply tree) { 2559 Type owntype = types.createErrorType(tree.type); 2560 2561 // Attribute functor part of application and make sure it's a class. 2562 Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env)); 2563 2564 // Attribute type parameters 2565 List<Type> actuals = attribTypes(tree.arguments, env); 2566 2567 if (clazztype.tag == CLASS) { 2568 List<Type> formals = clazztype.tsym.type.getTypeArguments(); 2569 2570 if (actuals.length() == formals.length() || actuals.isEmpty()) { 2571 List<Type> a = actuals; 2572 List<Type> f = formals; 2573 while (a.nonEmpty()) { 2574 a.head = a.head.withTypeVar(f.head); 2575 a = a.tail; 2576 f = f.tail; 2577 } 2578 // Compute the proper generic outer 2579 Type clazzOuter = clazztype.getEnclosingType(); 2580 if (clazzOuter.tag == CLASS) { 2581 Type site; 2582 JCExpression clazz = TreeInfo.typeIn(tree.clazz); 2583 if (clazz.getTag() == JCTree.IDENT) { 2584 site = env.enclClass.sym.type; 2585 } else if (clazz.getTag() == JCTree.SELECT) { 2586 site = ((JCFieldAccess) clazz).selected.type; 2587 } else throw new AssertionError(""+tree); 2588 if (clazzOuter.tag == CLASS && site != clazzOuter) { 2589 if (site.tag == CLASS) 2590 site = types.asOuterSuper(site, clazzOuter.tsym); 2591 if (site == null) 2592 site = types.erasure(clazzOuter); 2593 clazzOuter = site; 2594 } 2595 } 2596 if (actuals.nonEmpty()) { 2597 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym); 2598 } 2599 else if (TreeInfo.isDiamond(tree)) { 2600 //a type apply with no explicit type arguments - diamond operator 2601 //the result type is a forall F where F's tvars are the type-variables 2602 //that will be inferred when F is checked against the expected type 2603 List<Type> ftvars = clazztype.tsym.type.getTypeArguments(); 2604 List<Type> new_tvars = types.newInstances(ftvars); 2605 clazztype = new ClassType(clazzOuter, new_tvars, clazztype.tsym); 2606 owntype = new ForAll(new_tvars, clazztype); 2607 } 2608 } else { 2609 if (formals.length() != 0) { 2610 log.error(tree.pos(), "wrong.number.type.args", 2611 Integer.toString(formals.length())); 2612 } else { 2613 log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym); 2614 } 2615 owntype = types.createErrorType(tree.type); 2616 } 2617 } 2618 result = check(tree, owntype, TYP, pkind, pt); 2619 } 2620 2621 public void visitTypeParameter(JCTypeParameter tree) { 2622 TypeVar a = (TypeVar)tree.type; 2623 Set<Type> boundSet = new HashSet<Type>(); 2624 if (a.bound.isErroneous()) 2625 return; 2626 List<Type> bs = types.getBounds(a); 2627 if (tree.bounds.nonEmpty()) { 2628 // accept class or interface or typevar as first bound. 2629 Type b = checkBase(bs.head, tree.bounds.head, env, false, false, false); 2630 boundSet.add(types.erasure(b)); 2631 if (b.isErroneous()) { 2632 a.bound = b; 2633 } 2634 else if (b.tag == TYPEVAR) { 2635 // if first bound was a typevar, do not accept further bounds. 2636 if (tree.bounds.tail.nonEmpty()) { 2637 log.error(tree.bounds.tail.head.pos(), 2638 "type.var.may.not.be.followed.by.other.bounds"); 2639 tree.bounds = List.of(tree.bounds.head); 2640 a.bound = bs.head; 2641 } 2642 } else { 2643 // if first bound was a class or interface, accept only interfaces 2644 // as further bounds. 2645 for (JCExpression bound : tree.bounds.tail) { 2646 bs = bs.tail; 2647 Type i = checkBase(bs.head, bound, env, false, true, false); 2648 if (i.isErroneous()) 2649 a.bound = i; 2650 else if (i.tag == CLASS) 2651 chk.checkNotRepeated(bound.pos(), types.erasure(i), boundSet); 2652 } 2653 } 2654 } 2655 bs = types.getBounds(a); 2656 2657 // in case of multiple bounds ... 2658 if (bs.length() > 1) { 2659 // ... the variable's bound is a class type flagged COMPOUND 2660 // (see comment for TypeVar.bound). 2661 // In this case, generate a class tree that represents the 2662 // bound class, ... 2663 JCTree extending; 2664 List<JCExpression> implementing; 2665 if ((bs.head.tsym.flags() & INTERFACE) == 0) { 2666 extending = tree.bounds.head; 2667 implementing = tree.bounds.tail; 2668 } else { 2669 extending = null; 2670 implementing = tree.bounds; 2671 } 2672 JCClassDecl cd = make.at(tree.pos).ClassDef( 2673 make.Modifiers(PUBLIC | ABSTRACT), 2674 tree.name, List.<JCTypeParameter>nil(), 2675 extending, implementing, List.<JCTree>nil()); 2676 2677 ClassSymbol c = (ClassSymbol)a.getUpperBound().tsym; 2678 assert (c.flags() & COMPOUND) != 0; 2679 cd.sym = c; 2680 c.sourcefile = env.toplevel.sourcefile; 2681 2682 // ... and attribute the bound class 2683 c.flags_field |= UNATTRIBUTED; 2684 Env<AttrContext> cenv = enter.classEnv(cd, env); 2685 enter.typeEnvs.put(c, cenv); 2686 } 2687 } 2688 2689 2690 public void visitWildcard(JCWildcard tree) { 2691 //- System.err.println("visitWildcard("+tree+");");//DEBUG 2692 Type type = (tree.kind.kind == BoundKind.UNBOUND) 2693 ? syms.objectType 2694 : attribType(tree.inner, env); 2695 result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type), 2696 tree.kind.kind, 2697 syms.boundClass), 2698 TYP, pkind, pt); 2699 } 2700 2701 public void visitAnnotation(JCAnnotation tree) { 2702 log.error(tree.pos(), "annotation.not.valid.for.type", pt); 2703 result = tree.type = syms.errType; 2704 } 2705 2706 public void visitAnnotatedType(JCAnnotatedType tree) { 2707 result = tree.type = attribType(tree.getUnderlyingType(), env); 2708 } 2709 2710 public void visitErroneous(JCErroneous tree) { 2711 if (tree.errs != null) 2712 for (JCTree err : tree.errs) 2713 attribTree(err, env, ERR, pt); 2714 result = tree.type = syms.errType; 2715 } 2716 2717 /** Default visitor method for all other trees. 2718 */ 2719 public void visitTree(JCTree tree) { 2720 throw new AssertionError(); 2721 } 2722 2723 /** Main method: attribute class definition associated with given class symbol. 2724 * reporting completion failures at the given position. 2725 * @param pos The source position at which completion errors are to be 2726 * reported. 2727 * @param c The class symbol whose definition will be attributed. 2728 */ 2729 public void attribClass(DiagnosticPosition pos, ClassSymbol c) { 2730 try { 2731 annotate.flush(); 2732 attribClass(c); 2733 } catch (CompletionFailure ex) { 2734 chk.completionError(pos, ex); 2735 } 2736 } 2737 2738 /** Attribute class definition associated with given class symbol. 2739 * @param c The class symbol whose definition will be attributed. 2740 */ 2741 void attribClass(ClassSymbol c) throws CompletionFailure { 2742 if (c.type.tag == ERROR) return; 2743 2744 // Check for cycles in the inheritance graph, which can arise from 2745 // ill-formed class files. 2746 chk.checkNonCyclic(null, c.type); 2747 2748 Type st = types.supertype(c.type); 2749 if ((c.flags_field & Flags.COMPOUND) == 0) { 2750 // First, attribute superclass. 2751 if (st.tag == CLASS) 2752 attribClass((ClassSymbol)st.tsym); 2753 2754 // Next attribute owner, if it is a class. 2755 if (c.owner.kind == TYP && c.owner.type.tag == CLASS) 2756 attribClass((ClassSymbol)c.owner); 2757 } 2758 2759 // The previous operations might have attributed the current class 2760 // if there was a cycle. So we test first whether the class is still 2761 // UNATTRIBUTED. 2762 if ((c.flags_field & UNATTRIBUTED) != 0) { 2763 c.flags_field &= ~UNATTRIBUTED; 2764 2765 // Get environment current at the point of class definition. 2766 Env<AttrContext> env = enter.typeEnvs.get(c); 2767 2768 // The info.lint field in the envs stored in enter.typeEnvs is deliberately uninitialized, 2769 // because the annotations were not available at the time the env was created. Therefore, 2770 // we look up the environment chain for the first enclosing environment for which the 2771 // lint value is set. Typically, this is the parent env, but might be further if there 2772 // are any envs created as a result of TypeParameter nodes. 2773 Env<AttrContext> lintEnv = env; 2774 while (lintEnv.info.lint == null) 2775 lintEnv = lintEnv.next; 2776 2777 // Having found the enclosing lint value, we can initialize the lint value for this class 2778 env.info.lint = lintEnv.info.lint.augment(c.attributes_field, c.flags()); 2779 2780 Lint prevLint = chk.setLint(env.info.lint); 2781 JavaFileObject prev = log.useSource(c.sourcefile); 2782 2783 try { 2784 // java.lang.Enum may not be subclassed by a non-enum 2785 if (st.tsym == syms.enumSym && 2786 ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0)) 2787 log.error(env.tree.pos(), "enum.no.subclassing"); 2788 2789 // Enums may not be extended by source-level classes 2790 if (st.tsym != null && 2791 ((st.tsym.flags_field & Flags.ENUM) != 0) && 2792 ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0) && 2793 !target.compilerBootstrap(c)) { 2794 log.error(env.tree.pos(), "enum.types.not.extensible"); 2795 } 2796 attribClassBody(env, c); 2797 2798 chk.checkDeprecatedAnnotation(env.tree.pos(), c); 2799 } finally { 2800 log.useSource(prev); 2801 chk.setLint(prevLint); 2802 } 2803 2804 } 2805 } 2806 2807 public void visitImport(JCImport tree) { 2808 // nothing to do 2809 } 2810 2811 /** Finish the attribution of a class. */ 2812 private void attribClassBody(Env<AttrContext> env, ClassSymbol c) { 2813 JCClassDecl tree = (JCClassDecl)env.tree; 2814 assert c == tree.sym; 2815 2816 // Validate annotations 2817 chk.validateAnnotations(tree.mods.annotations, c); 2818 2819 // Validate type parameters, supertype and interfaces. 2820 attribBounds(tree.typarams); 2821 chk.validate(tree.typarams, env); 2822 chk.validate(tree.extending, env); 2823 chk.validate(tree.implementing, env); 2824 2825 // If this is a non-abstract class, check that it has no abstract 2826 // methods or unimplemented methods of an implemented interface. 2827 if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) { 2828 if (!relax) 2829 chk.checkAllDefined(tree.pos(), c); 2830 } 2831 2832 if ((c.flags() & ANNOTATION) != 0) { 2833 if (tree.implementing.nonEmpty()) 2834 log.error(tree.implementing.head.pos(), 2835 "cant.extend.intf.annotation"); 2836 if (tree.typarams.nonEmpty()) 2837 log.error(tree.typarams.head.pos(), 2838 "intf.annotation.cant.have.type.params"); 2839 } else { 2840 // Check that all extended classes and interfaces 2841 // are compatible (i.e. no two define methods with same arguments 2842 // yet different return types). (JLS 8.4.6.3) 2843 chk.checkCompatibleSupertypes(tree.pos(), c.type); 2844 } 2845 2846 // Check that class does not import the same parameterized interface 2847 // with two different argument lists. 2848 chk.checkClassBounds(tree.pos(), c.type); 2849 2850 tree.type = c.type; 2851 2852 boolean assertsEnabled = false; 2853 assert assertsEnabled = true; 2854 if (assertsEnabled) { 2855 for (List<JCTypeParameter> l = tree.typarams; 2856 l.nonEmpty(); l = l.tail) 2857 assert env.info.scope.lookup(l.head.name).scope != null; 2858 } 2859 2860 // Check that a generic class doesn't extend Throwable 2861 if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType)) 2862 log.error(tree.extending.pos(), "generic.throwable"); 2863 2864 // Check that all methods which implement some 2865 // method conform to the method they implement. 2866 chk.checkImplementations(tree); 2867 2868 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) { 2869 // Attribute declaration 2870 attribStat(l.head, env); 2871 // Check that declarations in inner classes are not static (JLS 8.1.2) 2872 // Make an exception for static constants. 2873 if (c.owner.kind != PCK && 2874 ((c.flags() & STATIC) == 0 || c.name == names.empty) && 2875 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) { 2876 Symbol sym = null; 2877 if (l.head.getTag() == JCTree.VARDEF) sym = ((JCVariableDecl) l.head).sym; 2878 if (sym == null || 2879 sym.kind != VAR || 2880 ((VarSymbol) sym).getConstValue() == null) 2881 log.error(l.head.pos(), "icls.cant.have.static.decl"); 2882 } 2883 } 2884 2885 // Check for cycles among non-initial constructors. 2886 chk.checkCyclicConstructors(tree); 2887 2888 // Check for cycles among annotation elements. 2889 chk.checkNonCyclicElements(tree); 2890 2891 // Check for proper use of serialVersionUID 2892 if (env.info.lint.isEnabled(Lint.LintCategory.SERIAL) && 2893 isSerializable(c) && 2894 (c.flags() & Flags.ENUM) == 0 && 2895 (c.flags() & ABSTRACT) == 0) { 2896 checkSerialVersionUID(tree, c); 2897 } 2898 2899 // Check type annotations applicability rules 2900 validateTypeAnnotations(tree); 2901 } 2902 // where 2903 /** check if a class is a subtype of Serializable, if that is available. */ 2904 private boolean isSerializable(ClassSymbol c) { 2905 try { 2906 syms.serializableType.complete(); 2907 } 2908 catch (CompletionFailure e) { 2909 return false; 2910 } 2911 return types.isSubtype(c.type, syms.serializableType); 2912 } 2913 2914 /** Check that an appropriate serialVersionUID member is defined. */ 2915 private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) { 2916 2917 // check for presence of serialVersionUID 2918 Scope.Entry e = c.members().lookup(names.serialVersionUID); 2919 while (e.scope != null && e.sym.kind != VAR) e = e.next(); 2920 if (e.scope == null) { 2921 log.warning(tree.pos(), "missing.SVUID", c); 2922 return; 2923 } 2924 2925 // check that it is static final 2926 VarSymbol svuid = (VarSymbol)e.sym; 2927 if ((svuid.flags() & (STATIC | FINAL)) != 2928 (STATIC | FINAL)) 2929 log.warning(TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c); 2930 2931 // check that it is long 2932 else if (svuid.type.tag != TypeTags.LONG) 2933 log.warning(TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c); 2934 2935 // check constant 2936 else if (svuid.getConstValue() == null) 2937 log.warning(TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c); 2938 } 2939 2940 private Type capture(Type type) { 2941 return types.capture(type); 2942 } 2943 2944 private void validateTypeAnnotations(JCTree tree) { 2945 tree.accept(typeAnnotationsValidator); 2946 } 2947 //where 2948 private final JCTree.Visitor typeAnnotationsValidator = 2949 new TreeScanner() { 2950 public void visitAnnotation(JCAnnotation tree) { 2951 if (tree instanceof JCTypeAnnotation) { 2952 chk.validateTypeAnnotation((JCTypeAnnotation)tree, false); 2953 } 2954 super.visitAnnotation(tree); 2955 } 2956 public void visitTypeParameter(JCTypeParameter tree) { 2957 chk.validateTypeAnnotations(tree.annotations, true); 2958 // don't call super. skip type annotations 2959 scan(tree.bounds); 2960 } 2961 public void visitMethodDef(JCMethodDecl tree) { 2962 // need to check static methods 2963 if ((tree.sym.flags() & Flags.STATIC) != 0) { 2964 for (JCTypeAnnotation a : tree.receiverAnnotations) { 2965 if (chk.isTypeAnnotation(a, false)) 2966 log.error(a.pos(), "annotation.type.not.applicable"); 2967 } 2968 } 2969 super.visitMethodDef(tree); 2970 } 2971 }; 2972 }