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 913 // Attribute all cases and 914 // check that there are no duplicate case labels or default clauses. 915 Set<Object> labels = new HashSet<Object>(); // The set of case labels. 916 boolean hasDefault = false; // Is there a default label? 917 for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) { 918 JCCase c = l.head; 919 Env<AttrContext> caseEnv = 920 switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup())); 921 if (c.pat != null) { 922 if (enumSwitch) { 923 Symbol sym = enumConstant(c.pat, seltype); 924 if (sym == null) { 925 log.error(c.pat.pos(), "enum.const.req"); 926 } else if (!labels.add(sym)) { 927 log.error(c.pos(), "duplicate.case.label"); 928 } 929 } else { 930 Type pattype = attribExpr(c.pat, switchEnv, seltype); 931 if (pattype.tag != ERROR) { 932 if (pattype.constValue() == null) { 933 log.error(c.pat.pos(), 934 (stringSwitch ? "string.const.req" : "const.expr.req")); 935 } else if (labels.contains(pattype.constValue())) { 936 log.error(c.pos(), "duplicate.case.label"); 937 } else { 938 labels.add(pattype.constValue()); 939 } 940 } 941 } 942 } else if (hasDefault) { 943 log.error(c.pos(), "duplicate.default.label"); 944 } else { 945 hasDefault = true; 946 } 947 attribStats(c.stats, caseEnv); 948 caseEnv.info.scope.leave(); 949 addVars(c.stats, switchEnv.info.scope); 950 } 951 952 switchEnv.info.scope.leave(); 953 result = null; 954 } 955 // where 956 /** Add any variables defined in stats to the switch scope. */ 957 private static void addVars(List<JCStatement> stats, Scope switchScope) { 958 for (;stats.nonEmpty(); stats = stats.tail) { 959 JCTree stat = stats.head; 960 if (stat.getTag() == JCTree.VARDEF) 961 switchScope.enter(((JCVariableDecl) stat).sym); 962 } 963 } 964 // where 965 /** Return the selected enumeration constant symbol, or null. */ 966 private Symbol enumConstant(JCTree tree, Type enumType) { 967 if (tree.getTag() != JCTree.IDENT) { 968 log.error(tree.pos(), "enum.label.must.be.unqualified.enum"); 969 return syms.errSymbol; 970 } 971 JCIdent ident = (JCIdent)tree; 972 Name name = ident.name; 973 for (Scope.Entry e = enumType.tsym.members().lookup(name); 974 e.scope != null; e = e.next()) { 975 if (e.sym.kind == VAR) { 976 Symbol s = ident.sym = e.sym; 977 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated 978 ident.type = s.type; 979 return ((s.flags_field & Flags.ENUM) == 0) 980 ? null : s; 981 } 982 } 983 return null; 984 } 985 986 public void visitSynchronized(JCSynchronized tree) { 987 chk.checkRefType(tree.pos(), attribExpr(tree.lock, env)); 988 attribStat(tree.body, env); 989 result = null; 990 } 991 992 public void visitTry(JCTry tree) { 993 // Attribute body 994 attribStat(tree.body, env.dup(tree, env.info.dup())); 995 996 // Attribute catch clauses 997 for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) { 998 JCCatch c = l.head; 999 Env<AttrContext> catchEnv = 1000 env.dup(c, env.info.dup(env.info.scope.dup())); 1001 Type ctype = attribStat(c.param, catchEnv); 1002 if (c.param.type.tsym.kind == Kinds.VAR) { 1003 c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER); 1004 } 1005 chk.checkType(c.param.vartype.pos(), 1006 chk.checkClassType(c.param.vartype.pos(), ctype), 1007 syms.throwableType); 1008 attribStat(c.body, catchEnv); 1009 catchEnv.info.scope.leave(); 1010 } 1011 1012 // Attribute finalizer 1013 if (tree.finalizer != null) attribStat(tree.finalizer, env); 1014 result = null; 1015 } 1016 1017 public void visitConditional(JCConditional tree) { 1018 attribExpr(tree.cond, env, syms.booleanType); 1019 attribExpr(tree.truepart, env); 1020 attribExpr(tree.falsepart, env); 1021 result = check(tree, 1022 capture(condType(tree.pos(), tree.cond.type, 1023 tree.truepart.type, tree.falsepart.type)), 1024 VAL, pkind, pt); 1025 } 1026 //where 1027 /** Compute the type of a conditional expression, after 1028 * checking that it exists. See Spec 15.25. 1029 * 1030 * @param pos The source position to be used for 1031 * error diagnostics. 1032 * @param condtype The type of the expression's condition. 1033 * @param thentype The type of the expression's then-part. 1034 * @param elsetype The type of the expression's else-part. 1035 */ 1036 private Type condType(DiagnosticPosition pos, 1037 Type condtype, 1038 Type thentype, 1039 Type elsetype) { 1040 Type ctype = condType1(pos, condtype, thentype, elsetype); 1041 1042 // If condition and both arms are numeric constants, 1043 // evaluate at compile-time. 1044 return ((condtype.constValue() != null) && 1045 (thentype.constValue() != null) && 1046 (elsetype.constValue() != null)) 1047 ? cfolder.coerce(condtype.isTrue()?thentype:elsetype, ctype) 1048 : ctype; 1049 } 1050 /** Compute the type of a conditional expression, after 1051 * checking that it exists. Does not take into 1052 * account the special case where condition and both arms 1053 * are constants. 1054 * 1055 * @param pos The source position to be used for error 1056 * diagnostics. 1057 * @param condtype The type of the expression's condition. 1058 * @param thentype The type of the expression's then-part. 1059 * @param elsetype The type of the expression's else-part. 1060 */ 1061 private Type condType1(DiagnosticPosition pos, Type condtype, 1062 Type thentype, Type elsetype) { 1063 // If same type, that is the result 1064 if (types.isSameType(thentype, elsetype)) 1065 return thentype.baseType(); 1066 1067 Type thenUnboxed = (!allowBoxing || thentype.isPrimitive()) 1068 ? thentype : types.unboxedType(thentype); 1069 Type elseUnboxed = (!allowBoxing || elsetype.isPrimitive()) 1070 ? elsetype : types.unboxedType(elsetype); 1071 1072 // Otherwise, if both arms can be converted to a numeric 1073 // type, return the least numeric type that fits both arms 1074 // (i.e. return larger of the two, or return int if one 1075 // arm is short, the other is char). 1076 if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) { 1077 // If one arm has an integer subrange type (i.e., byte, 1078 // short, or char), and the other is an integer constant 1079 // that fits into the subrange, return the subrange type. 1080 if (thenUnboxed.tag < INT && elseUnboxed.tag == INT && 1081 types.isAssignable(elseUnboxed, thenUnboxed)) 1082 return thenUnboxed.baseType(); 1083 if (elseUnboxed.tag < INT && thenUnboxed.tag == INT && 1084 types.isAssignable(thenUnboxed, elseUnboxed)) 1085 return elseUnboxed.baseType(); 1086 1087 for (int i = BYTE; i < VOID; i++) { 1088 Type candidate = syms.typeOfTag[i]; 1089 if (types.isSubtype(thenUnboxed, candidate) && 1090 types.isSubtype(elseUnboxed, candidate)) 1091 return candidate; 1092 } 1093 } 1094 1095 // Those were all the cases that could result in a primitive 1096 if (allowBoxing) { 1097 if (thentype.isPrimitive()) 1098 thentype = types.boxedClass(thentype).type; 1099 if (elsetype.isPrimitive()) 1100 elsetype = types.boxedClass(elsetype).type; 1101 } 1102 1103 if (types.isSubtype(thentype, elsetype)) 1104 return elsetype.baseType(); 1105 if (types.isSubtype(elsetype, thentype)) 1106 return thentype.baseType(); 1107 1108 if (!allowBoxing || thentype.tag == VOID || elsetype.tag == VOID) { 1109 log.error(pos, "neither.conditional.subtype", 1110 thentype, elsetype); 1111 return thentype.baseType(); 1112 } 1113 1114 // both are known to be reference types. The result is 1115 // lub(thentype,elsetype). This cannot fail, as it will 1116 // always be possible to infer "Object" if nothing better. 1117 return types.lub(thentype.baseType(), elsetype.baseType()); 1118 } 1119 1120 public void visitIf(JCIf tree) { 1121 attribExpr(tree.cond, env, syms.booleanType); 1122 attribStat(tree.thenpart, env); 1123 if (tree.elsepart != null) 1124 attribStat(tree.elsepart, env); 1125 chk.checkEmptyIf(tree); 1126 result = null; 1127 } 1128 1129 public void visitExec(JCExpressionStatement tree) { 1130 attribExpr(tree.expr, env); 1131 result = null; 1132 } 1133 1134 public void visitBreak(JCBreak tree) { 1135 tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env); 1136 result = null; 1137 } 1138 1139 public void visitContinue(JCContinue tree) { 1140 tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env); 1141 result = null; 1142 } 1143 //where 1144 /** Return the target of a break or continue statement, if it exists, 1145 * report an error if not. 1146 * Note: The target of a labelled break or continue is the 1147 * (non-labelled) statement tree referred to by the label, 1148 * not the tree representing the labelled statement itself. 1149 * 1150 * @param pos The position to be used for error diagnostics 1151 * @param tag The tag of the jump statement. This is either 1152 * Tree.BREAK or Tree.CONTINUE. 1153 * @param label The label of the jump statement, or null if no 1154 * label is given. 1155 * @param env The environment current at the jump statement. 1156 */ 1157 private JCTree findJumpTarget(DiagnosticPosition pos, 1158 int tag, 1159 Name label, 1160 Env<AttrContext> env) { 1161 // Search environments outwards from the point of jump. 1162 Env<AttrContext> env1 = env; 1163 LOOP: 1164 while (env1 != null) { 1165 switch (env1.tree.getTag()) { 1166 case JCTree.LABELLED: 1167 JCLabeledStatement labelled = (JCLabeledStatement)env1.tree; 1168 if (label == labelled.label) { 1169 // If jump is a continue, check that target is a loop. 1170 if (tag == JCTree.CONTINUE) { 1171 if (labelled.body.getTag() != JCTree.DOLOOP && 1172 labelled.body.getTag() != JCTree.WHILELOOP && 1173 labelled.body.getTag() != JCTree.FORLOOP && 1174 labelled.body.getTag() != JCTree.FOREACHLOOP) 1175 log.error(pos, "not.loop.label", label); 1176 // Found labelled statement target, now go inwards 1177 // to next non-labelled tree. 1178 return TreeInfo.referencedStatement(labelled); 1179 } else { 1180 return labelled; 1181 } 1182 } 1183 break; 1184 case JCTree.DOLOOP: 1185 case JCTree.WHILELOOP: 1186 case JCTree.FORLOOP: 1187 case JCTree.FOREACHLOOP: 1188 if (label == null) return env1.tree; 1189 break; 1190 case JCTree.SWITCH: 1191 if (label == null && tag == JCTree.BREAK) return env1.tree; 1192 break; 1193 case JCTree.METHODDEF: 1194 case JCTree.CLASSDEF: 1195 break LOOP; 1196 default: 1197 } 1198 env1 = env1.next; 1199 } 1200 if (label != null) 1201 log.error(pos, "undef.label", label); 1202 else if (tag == JCTree.CONTINUE) 1203 log.error(pos, "cont.outside.loop"); 1204 else 1205 log.error(pos, "break.outside.switch.loop"); 1206 return null; 1207 } 1208 1209 public void visitReturn(JCReturn tree) { 1210 // Check that there is an enclosing method which is 1211 // nested within than the enclosing class. 1212 if (env.enclMethod == null || 1213 env.enclMethod.sym.owner != env.enclClass.sym) { 1214 log.error(tree.pos(), "ret.outside.meth"); 1215 1216 } else { 1217 // Attribute return expression, if it exists, and check that 1218 // it conforms to result type of enclosing method. 1219 Symbol m = env.enclMethod.sym; 1220 if (m.type.getReturnType().tag == VOID) { 1221 if (tree.expr != null) 1222 log.error(tree.expr.pos(), 1223 "cant.ret.val.from.meth.decl.void"); 1224 } else if (tree.expr == null) { 1225 log.error(tree.pos(), "missing.ret.val"); 1226 } else { 1227 attribExpr(tree.expr, env, m.type.getReturnType()); 1228 } 1229 } 1230 result = null; 1231 } 1232 1233 public void visitThrow(JCThrow tree) { 1234 attribExpr(tree.expr, env, syms.throwableType); 1235 result = null; 1236 } 1237 1238 public void visitAssert(JCAssert tree) { 1239 attribExpr(tree.cond, env, syms.booleanType); 1240 if (tree.detail != null) { 1241 chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env)); 1242 } 1243 result = null; 1244 } 1245 1246 /** Visitor method for method invocations. 1247 * NOTE: The method part of an application will have in its type field 1248 * the return type of the method, not the method's type itself! 1249 */ 1250 public void visitApply(JCMethodInvocation tree) { 1251 // The local environment of a method application is 1252 // a new environment nested in the current one. 1253 Env<AttrContext> localEnv = env.dup(tree, env.info.dup()); 1254 1255 // The types of the actual method arguments. 1256 List<Type> argtypes; 1257 1258 // The types of the actual method type arguments. 1259 List<Type> typeargtypes = null; 1260 boolean typeargtypesNonRefOK = false; 1261 1262 Name methName = TreeInfo.name(tree.meth); 1263 1264 boolean isConstructorCall = 1265 methName == names._this || methName == names._super; 1266 1267 if (isConstructorCall) { 1268 // We are seeing a ...this(...) or ...super(...) call. 1269 // Check that this is the first statement in a constructor. 1270 if (checkFirstConstructorStat(tree, env)) { 1271 1272 // Record the fact 1273 // that this is a constructor call (using isSelfCall). 1274 localEnv.info.isSelfCall = true; 1275 1276 // Attribute arguments, yielding list of argument types. 1277 argtypes = attribArgs(tree.args, localEnv); 1278 typeargtypes = attribTypes(tree.typeargs, localEnv); 1279 1280 // Variable `site' points to the class in which the called 1281 // constructor is defined. 1282 Type site = env.enclClass.sym.type; 1283 if (methName == names._super) { 1284 if (site == syms.objectType) { 1285 log.error(tree.meth.pos(), "no.superclass", site); 1286 site = types.createErrorType(syms.objectType); 1287 } else { 1288 site = types.supertype(site); 1289 } 1290 } 1291 1292 if (site.tag == CLASS) { 1293 Type encl = site.getEnclosingType(); 1294 while (encl != null && encl.tag == TYPEVAR) 1295 encl = encl.getUpperBound(); 1296 if (encl.tag == CLASS) { 1297 // we are calling a nested class 1298 1299 if (tree.meth.getTag() == JCTree.SELECT) { 1300 JCTree qualifier = ((JCFieldAccess) tree.meth).selected; 1301 1302 // We are seeing a prefixed call, of the form 1303 // <expr>.super(...). 1304 // Check that the prefix expression conforms 1305 // to the outer instance type of the class. 1306 chk.checkRefType(qualifier.pos(), 1307 attribExpr(qualifier, localEnv, 1308 encl)); 1309 } else if (methName == names._super) { 1310 // qualifier omitted; check for existence 1311 // of an appropriate implicit qualifier. 1312 rs.resolveImplicitThis(tree.meth.pos(), 1313 localEnv, site); 1314 } 1315 } else if (tree.meth.getTag() == JCTree.SELECT) { 1316 log.error(tree.meth.pos(), "illegal.qual.not.icls", 1317 site.tsym); 1318 } 1319 1320 // if we're calling a java.lang.Enum constructor, 1321 // prefix the implicit String and int parameters 1322 if (site.tsym == syms.enumSym && allowEnums) 1323 argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType); 1324 1325 // Resolve the called constructor under the assumption 1326 // that we are referring to a superclass instance of the 1327 // current instance (JLS ???). 1328 boolean selectSuperPrev = localEnv.info.selectSuper; 1329 localEnv.info.selectSuper = true; 1330 localEnv.info.varArgs = false; 1331 Symbol sym = rs.resolveConstructor( 1332 tree.meth.pos(), localEnv, site, argtypes, typeargtypes); 1333 localEnv.info.selectSuper = selectSuperPrev; 1334 1335 // Set method symbol to resolved constructor... 1336 TreeInfo.setSymbol(tree.meth, sym); 1337 1338 // ...and check that it is legal in the current context. 1339 // (this will also set the tree's type) 1340 Type mpt = newMethTemplate(argtypes, typeargtypes); 1341 checkId(tree.meth, site, sym, localEnv, MTH, 1342 mpt, tree.varargsElement != null); 1343 } 1344 // Otherwise, `site' is an error type and we do nothing 1345 } 1346 result = tree.type = syms.voidType; 1347 } else { 1348 // Otherwise, we are seeing a regular method call. 1349 // Attribute the arguments, yielding list of argument types, ... 1350 argtypes = attribArgs(tree.args, localEnv); 1351 typeargtypes = attribAnyTypes(tree.typeargs, localEnv); 1352 1353 // ... and attribute the method using as a prototype a methodtype 1354 // whose formal argument types is exactly the list of actual 1355 // arguments (this will also set the method symbol). 1356 Type mpt = newMethTemplate(argtypes, typeargtypes); 1357 localEnv.info.varArgs = false; 1358 Type mtype = attribExpr(tree.meth, localEnv, mpt); 1359 if (localEnv.info.varArgs) 1360 assert mtype.isErroneous() || tree.varargsElement != null; 1361 1362 // Compute the result type. 1363 Type restype = mtype.getReturnType(); 1364 assert restype.tag != WILDCARD : mtype; 1365 1366 // as a special case, array.clone() has a result that is 1367 // the same as static type of the array being cloned 1368 if (tree.meth.getTag() == JCTree.SELECT && 1369 allowCovariantReturns && 1370 methName == names.clone && 1371 types.isArray(((JCFieldAccess) tree.meth).selected.type)) 1372 restype = ((JCFieldAccess) tree.meth).selected.type; 1373 1374 // as a special case, x.getClass() has type Class<? extends |X|> 1375 if (allowGenerics && 1376 methName == names.getClass && tree.args.isEmpty()) { 1377 Type qualifier = (tree.meth.getTag() == JCTree.SELECT) 1378 ? ((JCFieldAccess) tree.meth).selected.type 1379 : env.enclClass.sym.type; 1380 restype = new 1381 ClassType(restype.getEnclosingType(), 1382 List.<Type>of(new WildcardType(types.erasure(qualifier), 1383 BoundKind.EXTENDS, 1384 syms.boundClass)), 1385 restype.tsym); 1386 } 1387 1388 // as a special case, MethodHandle.<T>invoke(abc) and InvokeDynamic.<T>foo(abc) 1389 // has type <T>, and T can be a primitive type. 1390 if (tree.meth.getTag() == JCTree.SELECT && !typeargtypes.isEmpty()) { 1391 Type selt = ((JCFieldAccess) tree.meth).selected.type; 1392 if ((selt == syms.methodHandleType && methName == names.invoke) || selt == syms.invokeDynamicType) { 1393 assert types.isSameType(restype, typeargtypes.head) : mtype; 1394 typeargtypesNonRefOK = true; 1395 } 1396 } 1397 1398 if (!typeargtypesNonRefOK) { 1399 chk.checkRefTypes(tree.typeargs, typeargtypes); 1400 } 1401 1402 // Check that value of resulting type is admissible in the 1403 // current context. Also, capture the return type 1404 result = checkReturn(tree, capture(restype), VAL, pkind, pt); 1405 } 1406 chk.validate(tree.typeargs, localEnv); 1407 } 1408 //where 1409 /** Check that given application node appears as first statement 1410 * in a constructor call. 1411 * @param tree The application node 1412 * @param env The environment current at the application. 1413 */ 1414 boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) { 1415 JCMethodDecl enclMethod = env.enclMethod; 1416 if (enclMethod != null && enclMethod.name == names.init) { 1417 JCBlock body = enclMethod.body; 1418 if (body.stats.head.getTag() == JCTree.EXEC && 1419 ((JCExpressionStatement) body.stats.head).expr == tree) 1420 return true; 1421 } 1422 log.error(tree.pos(),"call.must.be.first.stmt.in.ctor", 1423 TreeInfo.name(tree.meth)); 1424 return false; 1425 } 1426 1427 /** Obtain a method type with given argument types. 1428 */ 1429 Type newMethTemplate(List<Type> argtypes, List<Type> typeargtypes) { 1430 MethodType mt = new MethodType(argtypes, null, null, syms.methodClass); 1431 return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt); 1432 } 1433 1434 public void visitNewClass(JCNewClass tree) { 1435 Type owntype = types.createErrorType(tree.type); 1436 1437 // The local environment of a class creation is 1438 // a new environment nested in the current one. 1439 Env<AttrContext> localEnv = env.dup(tree, env.info.dup()); 1440 1441 // The anonymous inner class definition of the new expression, 1442 // if one is defined by it. 1443 JCClassDecl cdef = tree.def; 1444 1445 // If enclosing class is given, attribute it, and 1446 // complete class name to be fully qualified 1447 JCExpression clazz = tree.clazz; // Class field following new 1448 JCExpression clazzid = // Identifier in class field 1449 (clazz.getTag() == JCTree.TYPEAPPLY) 1450 ? ((JCTypeApply) clazz).clazz 1451 : clazz; 1452 1453 JCExpression clazzid1 = clazzid; // The same in fully qualified form 1454 1455 if (tree.encl != null) { 1456 // We are seeing a qualified new, of the form 1457 // <expr>.new C <...> (...) ... 1458 // In this case, we let clazz stand for the name of the 1459 // allocated class C prefixed with the type of the qualifier 1460 // expression, so that we can 1461 // resolve it with standard techniques later. I.e., if 1462 // <expr> has type T, then <expr>.new C <...> (...) 1463 // yields a clazz T.C. 1464 Type encltype = chk.checkRefType(tree.encl.pos(), 1465 attribExpr(tree.encl, env)); 1466 clazzid1 = make.at(clazz.pos).Select(make.Type(encltype), 1467 ((JCIdent) clazzid).name); 1468 if (clazz.getTag() == JCTree.TYPEAPPLY) 1469 clazz = make.at(tree.pos). 1470 TypeApply(clazzid1, 1471 ((JCTypeApply) clazz).arguments); 1472 else 1473 clazz = clazzid1; 1474 // System.out.println(clazz + " generated.");//DEBUG 1475 } 1476 1477 // Attribute clazz expression and store 1478 // symbol + type back into the attributed tree. 1479 Type clazztype = attribType(clazz, env); 1480 chk.validate(clazz, localEnv); 1481 clazztype = chk.checkNewClassType(clazz.pos(), clazztype, true, pt); 1482 if (tree.encl != null) { 1483 // We have to work in this case to store 1484 // symbol + type back into the attributed tree. 1485 tree.clazz.type = clazztype; 1486 TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1)); 1487 clazzid.type = ((JCIdent) clazzid).sym.type; 1488 if (!clazztype.isErroneous()) { 1489 if (cdef != null && clazztype.tsym.isInterface()) { 1490 log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new"); 1491 } else if (clazztype.tsym.isStatic()) { 1492 log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym); 1493 } 1494 } 1495 } else if (!clazztype.tsym.isInterface() && 1496 clazztype.getEnclosingType().tag == CLASS) { 1497 // Check for the existence of an apropos outer instance 1498 rs.resolveImplicitThis(tree.pos(), env, clazztype); 1499 } 1500 1501 // Attribute constructor arguments. 1502 List<Type> argtypes = attribArgs(tree.args, localEnv); 1503 List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv); 1504 1505 // If we have made no mistakes in the class type... 1506 if (clazztype.tag == CLASS) { 1507 // Enums may not be instantiated except implicitly 1508 if (allowEnums && 1509 (clazztype.tsym.flags_field&Flags.ENUM) != 0 && 1510 (env.tree.getTag() != JCTree.VARDEF || 1511 (((JCVariableDecl) env.tree).mods.flags&Flags.ENUM) == 0 || 1512 ((JCVariableDecl) env.tree).init != tree)) 1513 log.error(tree.pos(), "enum.cant.be.instantiated"); 1514 // Check that class is not abstract 1515 if (cdef == null && 1516 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) { 1517 log.error(tree.pos(), "abstract.cant.be.instantiated", 1518 clazztype.tsym); 1519 } else if (cdef != null && clazztype.tsym.isInterface()) { 1520 // Check that no constructor arguments are given to 1521 // anonymous classes implementing an interface 1522 if (!argtypes.isEmpty()) 1523 log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args"); 1524 1525 if (!typeargtypes.isEmpty()) 1526 log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs"); 1527 1528 // Error recovery: pretend no arguments were supplied. 1529 argtypes = List.nil(); 1530 typeargtypes = List.nil(); 1531 } 1532 1533 // Resolve the called constructor under the assumption 1534 // that we are referring to a superclass instance of the 1535 // current instance (JLS ???). 1536 else { 1537 localEnv.info.selectSuper = cdef != null; 1538 localEnv.info.varArgs = false; 1539 tree.constructor = rs.resolveConstructor( 1540 tree.pos(), localEnv, clazztype, argtypes, typeargtypes); 1541 tree.constructorType = checkMethod(clazztype, 1542 tree.constructor, 1543 localEnv, 1544 tree.args, 1545 argtypes, 1546 typeargtypes, 1547 localEnv.info.varArgs); 1548 if (localEnv.info.varArgs) 1549 assert tree.constructorType.isErroneous() || tree.varargsElement != null; 1550 } 1551 1552 if (cdef != null) { 1553 // We are seeing an anonymous class instance creation. 1554 // In this case, the class instance creation 1555 // expression 1556 // 1557 // E.new <typeargs1>C<typargs2>(args) { ... } 1558 // 1559 // is represented internally as 1560 // 1561 // E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } ) . 1562 // 1563 // This expression is then *transformed* as follows: 1564 // 1565 // (1) add a STATIC flag to the class definition 1566 // if the current environment is static 1567 // (2) add an extends or implements clause 1568 // (3) add a constructor. 1569 // 1570 // For instance, if C is a class, and ET is the type of E, 1571 // the expression 1572 // 1573 // E.new <typeargs1>C<typargs2>(args) { ... } 1574 // 1575 // is translated to (where X is a fresh name and typarams is the 1576 // parameter list of the super constructor): 1577 // 1578 // new <typeargs1>X(<*nullchk*>E, args) where 1579 // X extends C<typargs2> { 1580 // <typarams> X(ET e, args) { 1581 // e.<typeargs1>super(args) 1582 // } 1583 // ... 1584 // } 1585 if (Resolve.isStatic(env)) cdef.mods.flags |= STATIC; 1586 clazz = TreeInfo.isDiamond(tree) ? 1587 make.Type(clazztype) 1588 : clazz; 1589 if (clazztype.tsym.isInterface()) { 1590 cdef.implementing = List.of(clazz); 1591 } else { 1592 cdef.extending = clazz; 1593 } 1594 1595 attribStat(cdef, localEnv); 1596 1597 // If an outer instance is given, 1598 // prefix it to the constructor arguments 1599 // and delete it from the new expression 1600 if (tree.encl != null && !clazztype.tsym.isInterface()) { 1601 tree.args = tree.args.prepend(makeNullCheck(tree.encl)); 1602 argtypes = argtypes.prepend(tree.encl.type); 1603 tree.encl = null; 1604 } 1605 1606 // Reassign clazztype and recompute constructor. 1607 clazztype = cdef.sym.type; 1608 Symbol sym = rs.resolveConstructor( 1609 tree.pos(), localEnv, clazztype, argtypes, 1610 typeargtypes, true, tree.varargsElement != null); 1611 assert sym.kind < AMBIGUOUS || tree.constructor.type.isErroneous(); 1612 tree.constructor = sym; 1613 if (tree.constructor.kind > ERRONEOUS) { 1614 tree.constructorType = syms.errType; 1615 } 1616 else { 1617 tree.constructorType = checkMethod(clazztype, 1618 tree.constructor, 1619 localEnv, 1620 tree.args, 1621 argtypes, 1622 typeargtypes, 1623 localEnv.info.varArgs); 1624 } 1625 } 1626 1627 if (tree.constructor != null && tree.constructor.kind == MTH) 1628 owntype = clazztype; 1629 } 1630 result = check(tree, owntype, VAL, pkind, pt); 1631 chk.validate(tree.typeargs, localEnv); 1632 } 1633 1634 /** Make an attributed null check tree. 1635 */ 1636 public JCExpression makeNullCheck(JCExpression arg) { 1637 // optimization: X.this is never null; skip null check 1638 Name name = TreeInfo.name(arg); 1639 if (name == names._this || name == names._super) return arg; 1640 1641 int optag = JCTree.NULLCHK; 1642 JCUnary tree = make.at(arg.pos).Unary(optag, arg); 1643 tree.operator = syms.nullcheck; 1644 tree.type = arg.type; 1645 return tree; 1646 } 1647 1648 public void visitNewArray(JCNewArray tree) { 1649 Type owntype = types.createErrorType(tree.type); 1650 Type elemtype; 1651 if (tree.elemtype != null) { 1652 elemtype = attribType(tree.elemtype, env); 1653 chk.validate(tree.elemtype, env); 1654 owntype = elemtype; 1655 for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) { 1656 attribExpr(l.head, env, syms.intType); 1657 owntype = new ArrayType(owntype, syms.arrayClass); 1658 } 1659 } else { 1660 // we are seeing an untyped aggregate { ... } 1661 // this is allowed only if the prototype is an array 1662 if (pt.tag == ARRAY) { 1663 elemtype = types.elemtype(pt); 1664 } else { 1665 if (pt.tag != ERROR) { 1666 log.error(tree.pos(), "illegal.initializer.for.type", 1667 pt); 1668 } 1669 elemtype = types.createErrorType(pt); 1670 } 1671 } 1672 if (tree.elems != null) { 1673 attribExprs(tree.elems, env, elemtype); 1674 owntype = new ArrayType(elemtype, syms.arrayClass); 1675 } 1676 if (!types.isReifiable(elemtype)) 1677 log.error(tree.pos(), "generic.array.creation"); 1678 result = check(tree, owntype, VAL, pkind, pt); 1679 } 1680 1681 public void visitParens(JCParens tree) { 1682 Type owntype = attribTree(tree.expr, env, pkind, pt); 1683 result = check(tree, owntype, pkind, pkind, pt); 1684 Symbol sym = TreeInfo.symbol(tree); 1685 if (sym != null && (sym.kind&(TYP|PCK)) != 0) 1686 log.error(tree.pos(), "illegal.start.of.type"); 1687 } 1688 1689 public void visitAssign(JCAssign tree) { 1690 Type owntype = attribTree(tree.lhs, env.dup(tree), VAR, Type.noType); 1691 Type capturedType = capture(owntype); 1692 attribExpr(tree.rhs, env, owntype); 1693 result = check(tree, capturedType, VAL, pkind, pt); 1694 } 1695 1696 public void visitAssignop(JCAssignOp tree) { 1697 // Attribute arguments. 1698 Type owntype = attribTree(tree.lhs, env, VAR, Type.noType); 1699 Type operand = attribExpr(tree.rhs, env); 1700 // Find operator. 1701 Symbol operator = tree.operator = rs.resolveBinaryOperator( 1702 tree.pos(), tree.getTag() - JCTree.ASGOffset, env, 1703 owntype, operand); 1704 1705 if (operator.kind == MTH) { 1706 chk.checkOperator(tree.pos(), 1707 (OperatorSymbol)operator, 1708 tree.getTag() - JCTree.ASGOffset, 1709 owntype, 1710 operand); 1711 chk.checkDivZero(tree.rhs.pos(), operator, operand); 1712 chk.checkCastable(tree.rhs.pos(), 1713 operator.type.getReturnType(), 1714 owntype); 1715 } 1716 result = check(tree, owntype, VAL, pkind, pt); 1717 } 1718 1719 public void visitUnary(JCUnary tree) { 1720 // Attribute arguments. 1721 Type argtype = (JCTree.PREINC <= tree.getTag() && tree.getTag() <= JCTree.POSTDEC) 1722 ? attribTree(tree.arg, env, VAR, Type.noType) 1723 : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env)); 1724 1725 // Find operator. 1726 Symbol operator = tree.operator = 1727 rs.resolveUnaryOperator(tree.pos(), tree.getTag(), env, argtype); 1728 1729 Type owntype = types.createErrorType(tree.type); 1730 if (operator.kind == MTH) { 1731 owntype = (JCTree.PREINC <= tree.getTag() && tree.getTag() <= JCTree.POSTDEC) 1732 ? tree.arg.type 1733 : operator.type.getReturnType(); 1734 int opc = ((OperatorSymbol)operator).opcode; 1735 1736 // If the argument is constant, fold it. 1737 if (argtype.constValue() != null) { 1738 Type ctype = cfolder.fold1(opc, argtype); 1739 if (ctype != null) { 1740 owntype = cfolder.coerce(ctype, owntype); 1741 1742 // Remove constant types from arguments to 1743 // conserve space. The parser will fold concatenations 1744 // of string literals; the code here also 1745 // gets rid of intermediate results when some of the 1746 // operands are constant identifiers. 1747 if (tree.arg.type.tsym == syms.stringType.tsym) { 1748 tree.arg.type = syms.stringType; 1749 } 1750 } 1751 } 1752 } 1753 result = check(tree, owntype, VAL, pkind, pt); 1754 } 1755 1756 public void visitBinary(JCBinary tree) { 1757 // Attribute arguments. 1758 Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env)); 1759 Type right = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.rhs, env)); 1760 1761 // Find operator. 1762 Symbol operator = tree.operator = 1763 rs.resolveBinaryOperator(tree.pos(), tree.getTag(), env, left, right); 1764 1765 Type owntype = types.createErrorType(tree.type); 1766 if (operator.kind == MTH) { 1767 owntype = operator.type.getReturnType(); 1768 int opc = chk.checkOperator(tree.lhs.pos(), 1769 (OperatorSymbol)operator, 1770 tree.getTag(), 1771 left, 1772 right); 1773 1774 // If both arguments are constants, fold them. 1775 if (left.constValue() != null && right.constValue() != null) { 1776 Type ctype = cfolder.fold2(opc, left, right); 1777 if (ctype != null) { 1778 owntype = cfolder.coerce(ctype, owntype); 1779 1780 // Remove constant types from arguments to 1781 // conserve space. The parser will fold concatenations 1782 // of string literals; the code here also 1783 // gets rid of intermediate results when some of the 1784 // operands are constant identifiers. 1785 if (tree.lhs.type.tsym == syms.stringType.tsym) { 1786 tree.lhs.type = syms.stringType; 1787 } 1788 if (tree.rhs.type.tsym == syms.stringType.tsym) { 1789 tree.rhs.type = syms.stringType; 1790 } 1791 } 1792 } 1793 1794 // Check that argument types of a reference ==, != are 1795 // castable to each other, (JLS???). 1796 if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) { 1797 if (!types.isCastable(left, right, new Warner(tree.pos()))) { 1798 log.error(tree.pos(), "incomparable.types", left, right); 1799 } 1800 } 1801 1802 chk.checkDivZero(tree.rhs.pos(), operator, right); 1803 } 1804 result = check(tree, owntype, VAL, pkind, pt); 1805 } 1806 1807 public void visitTypeCast(JCTypeCast tree) { 1808 Type clazztype = attribType(tree.clazz, env); 1809 chk.validate(tree.clazz, env); 1810 Type exprtype = attribExpr(tree.expr, env, Infer.anyPoly); 1811 Type owntype = chk.checkCastable(tree.expr.pos(), exprtype, clazztype); 1812 if (exprtype.constValue() != null) 1813 owntype = cfolder.coerce(exprtype, owntype); 1814 result = check(tree, capture(owntype), VAL, pkind, pt); 1815 } 1816 1817 public void visitTypeTest(JCInstanceOf tree) { 1818 Type exprtype = chk.checkNullOrRefType( 1819 tree.expr.pos(), attribExpr(tree.expr, env)); 1820 Type clazztype = chk.checkReifiableReferenceType( 1821 tree.clazz.pos(), attribType(tree.clazz, env)); 1822 chk.validate(tree.clazz, env); 1823 chk.checkCastable(tree.expr.pos(), exprtype, clazztype); 1824 result = check(tree, syms.booleanType, VAL, pkind, pt); 1825 } 1826 1827 public void visitIndexed(JCArrayAccess tree) { 1828 Type owntype = types.createErrorType(tree.type); 1829 Type atype = attribExpr(tree.indexed, env); 1830 attribExpr(tree.index, env, syms.intType); 1831 if (types.isArray(atype)) 1832 owntype = types.elemtype(atype); 1833 else if (atype.tag != ERROR) 1834 log.error(tree.pos(), "array.req.but.found", atype); 1835 if ((pkind & VAR) == 0) owntype = capture(owntype); 1836 result = check(tree, owntype, VAR, pkind, pt); 1837 } 1838 1839 public void visitIdent(JCIdent tree) { 1840 Symbol sym; 1841 boolean varArgs = false; 1842 1843 // Find symbol 1844 if (pt.tag == METHOD || pt.tag == FORALL) { 1845 // If we are looking for a method, the prototype `pt' will be a 1846 // method type with the type of the call's arguments as parameters. 1847 env.info.varArgs = false; 1848 sym = rs.resolveMethod(tree.pos(), env, tree.name, pt.getParameterTypes(), pt.getTypeArguments()); 1849 varArgs = env.info.varArgs; 1850 } else if (tree.sym != null && tree.sym.kind != VAR) { 1851 sym = tree.sym; 1852 } else { 1853 sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind); 1854 } 1855 tree.sym = sym; 1856 1857 // (1) Also find the environment current for the class where 1858 // sym is defined (`symEnv'). 1859 // Only for pre-tiger versions (1.4 and earlier): 1860 // (2) Also determine whether we access symbol out of an anonymous 1861 // class in a this or super call. This is illegal for instance 1862 // members since such classes don't carry a this$n link. 1863 // (`noOuterThisPath'). 1864 Env<AttrContext> symEnv = env; 1865 boolean noOuterThisPath = false; 1866 if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class 1867 (sym.kind & (VAR | MTH | TYP)) != 0 && 1868 sym.owner.kind == TYP && 1869 tree.name != names._this && tree.name != names._super) { 1870 1871 // Find environment in which identifier is defined. 1872 while (symEnv.outer != null && 1873 !sym.isMemberOf(symEnv.enclClass.sym, types)) { 1874 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0) 1875 noOuterThisPath = !allowAnonOuterThis; 1876 symEnv = symEnv.outer; 1877 } 1878 } 1879 1880 // If symbol is a variable, ... 1881 if (sym.kind == VAR) { 1882 VarSymbol v = (VarSymbol)sym; 1883 1884 // ..., evaluate its initializer, if it has one, and check for 1885 // illegal forward reference. 1886 checkInit(tree, env, v, false); 1887 1888 // If symbol is a local variable accessed from an embedded 1889 // inner class check that it is final. 1890 if (v.owner.kind == MTH && 1891 v.owner != env.info.scope.owner && 1892 (v.flags_field & FINAL) == 0) { 1893 log.error(tree.pos(), 1894 "local.var.accessed.from.icls.needs.final", 1895 v); 1896 } 1897 1898 // If we are expecting a variable (as opposed to a value), check 1899 // that the variable is assignable in the current environment. 1900 if (pkind == VAR) 1901 checkAssignable(tree.pos(), v, null, env); 1902 } 1903 1904 // In a constructor body, 1905 // if symbol is a field or instance method, check that it is 1906 // not accessed before the supertype constructor is called. 1907 if ((symEnv.info.isSelfCall || noOuterThisPath) && 1908 (sym.kind & (VAR | MTH)) != 0 && 1909 sym.owner.kind == TYP && 1910 (sym.flags() & STATIC) == 0) { 1911 chk.earlyRefError(tree.pos(), sym.kind == VAR ? sym : thisSym(tree.pos(), env)); 1912 } 1913 Env<AttrContext> env1 = env; 1914 if (sym.kind != ERR && sym.kind != TYP && sym.owner != null && sym.owner != env1.enclClass.sym) { 1915 // If the found symbol is inaccessible, then it is 1916 // accessed through an enclosing instance. Locate this 1917 // enclosing instance: 1918 while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym)) 1919 env1 = env1.outer; 1920 } 1921 result = checkId(tree, env1.enclClass.sym.type, sym, env, pkind, pt, varArgs); 1922 } 1923 1924 public void visitSelect(JCFieldAccess tree) { 1925 // Determine the expected kind of the qualifier expression. 1926 int skind = 0; 1927 if (tree.name == names._this || tree.name == names._super || 1928 tree.name == names._class) 1929 { 1930 skind = TYP; 1931 } else { 1932 if ((pkind & PCK) != 0) skind = skind | PCK; 1933 if ((pkind & TYP) != 0) skind = skind | TYP | PCK; 1934 if ((pkind & (VAL | MTH)) != 0) skind = skind | VAL | TYP; 1935 } 1936 1937 // Attribute the qualifier expression, and determine its symbol (if any). 1938 Type site = attribTree(tree.selected, env, skind, Infer.anyPoly); 1939 if ((pkind & (PCK | TYP)) == 0) 1940 site = capture(site); // Capture field access 1941 1942 // don't allow T.class T[].class, etc 1943 if (skind == TYP) { 1944 Type elt = site; 1945 while (elt.tag == ARRAY) 1946 elt = ((ArrayType)elt).elemtype; 1947 if (elt.tag == TYPEVAR) { 1948 log.error(tree.pos(), "type.var.cant.be.deref"); 1949 result = types.createErrorType(tree.type); 1950 return; 1951 } 1952 } 1953 1954 // If qualifier symbol is a type or `super', assert `selectSuper' 1955 // for the selection. This is relevant for determining whether 1956 // protected symbols are accessible. 1957 Symbol sitesym = TreeInfo.symbol(tree.selected); 1958 boolean selectSuperPrev = env.info.selectSuper; 1959 env.info.selectSuper = 1960 sitesym != null && 1961 sitesym.name == names._super; 1962 1963 // If selected expression is polymorphic, strip 1964 // type parameters and remember in env.info.tvars, so that 1965 // they can be added later (in Attr.checkId and Infer.instantiateMethod). 1966 if (tree.selected.type.tag == FORALL) { 1967 ForAll pstype = (ForAll)tree.selected.type; 1968 env.info.tvars = pstype.tvars; 1969 site = tree.selected.type = pstype.qtype; 1970 } 1971 1972 // Determine the symbol represented by the selection. 1973 env.info.varArgs = false; 1974 Symbol sym = selectSym(tree, site, env, pt, pkind); 1975 if (sym.exists() && !isType(sym) && (pkind & (PCK | TYP)) != 0) { 1976 site = capture(site); 1977 sym = selectSym(tree, site, env, pt, pkind); 1978 } 1979 boolean varArgs = env.info.varArgs; 1980 tree.sym = sym; 1981 1982 if (site.tag == TYPEVAR && !isType(sym) && sym.kind != ERR) { 1983 while (site.tag == TYPEVAR) site = site.getUpperBound(); 1984 site = capture(site); 1985 } 1986 1987 // If that symbol is a variable, ... 1988 if (sym.kind == VAR) { 1989 VarSymbol v = (VarSymbol)sym; 1990 1991 // ..., evaluate its initializer, if it has one, and check for 1992 // illegal forward reference. 1993 checkInit(tree, env, v, true); 1994 1995 // If we are expecting a variable (as opposed to a value), check 1996 // that the variable is assignable in the current environment. 1997 if (pkind == VAR) 1998 checkAssignable(tree.pos(), v, tree.selected, env); 1999 } 2000 2001 // Disallow selecting a type from an expression 2002 if (isType(sym) && (sitesym==null || (sitesym.kind&(TYP|PCK)) == 0)) { 2003 tree.type = check(tree.selected, pt, 2004 sitesym == null ? VAL : sitesym.kind, TYP|PCK, pt); 2005 } 2006 2007 if (isType(sitesym)) { 2008 if (sym.name == names._this) { 2009 // If `C' is the currently compiled class, check that 2010 // C.this' does not appear in a call to a super(...) 2011 if (env.info.isSelfCall && 2012 site.tsym == env.enclClass.sym) { 2013 chk.earlyRefError(tree.pos(), sym); 2014 } 2015 } else { 2016 // Check if type-qualified fields or methods are static (JLS) 2017 if ((sym.flags() & STATIC) == 0 && 2018 sym.name != names._super && 2019 (sym.kind == VAR || sym.kind == MTH)) { 2020 rs.access(rs.new StaticError(sym), 2021 tree.pos(), site, sym.name, true); 2022 } 2023 } 2024 } 2025 2026 // If we are selecting an instance member via a `super', ... 2027 if (env.info.selectSuper && (sym.flags() & STATIC) == 0) { 2028 2029 // Check that super-qualified symbols are not abstract (JLS) 2030 rs.checkNonAbstract(tree.pos(), sym); 2031 2032 if (site.isRaw()) { 2033 // Determine argument types for site. 2034 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym); 2035 if (site1 != null) site = site1; 2036 } 2037 } 2038 2039 env.info.selectSuper = selectSuperPrev; 2040 result = checkId(tree, site, sym, env, pkind, pt, varArgs); 2041 env.info.tvars = List.nil(); 2042 } 2043 //where 2044 /** Determine symbol referenced by a Select expression, 2045 * 2046 * @param tree The select tree. 2047 * @param site The type of the selected expression, 2048 * @param env The current environment. 2049 * @param pt The current prototype. 2050 * @param pkind The expected kind(s) of the Select expression. 2051 */ 2052 private Symbol selectSym(JCFieldAccess tree, 2053 Type site, 2054 Env<AttrContext> env, 2055 Type pt, 2056 int pkind) { 2057 DiagnosticPosition pos = tree.pos(); 2058 Name name = tree.name; 2059 2060 switch (site.tag) { 2061 case PACKAGE: 2062 return rs.access( 2063 rs.findIdentInPackage(env, site.tsym, name, pkind), 2064 pos, site, name, true); 2065 case ARRAY: 2066 case CLASS: 2067 if (pt.tag == METHOD || pt.tag == FORALL) { 2068 return rs.resolveQualifiedMethod( 2069 pos, env, site, name, pt.getParameterTypes(), pt.getTypeArguments()); 2070 } else if (name == names._this || name == names._super) { 2071 return rs.resolveSelf(pos, env, site.tsym, name); 2072 } else if (name == names._class) { 2073 // In this case, we have already made sure in 2074 // visitSelect that qualifier expression is a type. 2075 Type t = syms.classType; 2076 List<Type> typeargs = allowGenerics 2077 ? List.of(types.erasure(site)) 2078 : List.<Type>nil(); 2079 t = new ClassType(t.getEnclosingType(), typeargs, t.tsym); 2080 return new VarSymbol( 2081 STATIC | PUBLIC | FINAL, names._class, t, site.tsym); 2082 } else { 2083 // We are seeing a plain identifier as selector. 2084 Symbol sym = rs.findIdentInType(env, site, name, pkind); 2085 if ((pkind & ERRONEOUS) == 0) 2086 sym = rs.access(sym, pos, site, name, true); 2087 return sym; 2088 } 2089 case WILDCARD: 2090 throw new AssertionError(tree); 2091 case TYPEVAR: 2092 // Normally, site.getUpperBound() shouldn't be null. 2093 // It should only happen during memberEnter/attribBase 2094 // when determining the super type which *must* be 2095 // done before attributing the type variables. In 2096 // other words, we are seeing this illegal program: 2097 // class B<T> extends A<T.foo> {} 2098 Symbol sym = (site.getUpperBound() != null) 2099 ? selectSym(tree, capture(site.getUpperBound()), env, pt, pkind) 2100 : null; 2101 if (sym == null) { 2102 log.error(pos, "type.var.cant.be.deref"); 2103 return syms.errSymbol; 2104 } else { 2105 Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ? 2106 rs.new AccessError(env, site, sym) : 2107 sym; 2108 rs.access(sym2, pos, site, name, true); 2109 return sym; 2110 } 2111 case ERROR: 2112 // preserve identifier names through errors 2113 return types.createErrorType(name, site.tsym, site).tsym; 2114 default: 2115 // The qualifier expression is of a primitive type -- only 2116 // .class is allowed for these. 2117 if (name == names._class) { 2118 // In this case, we have already made sure in Select that 2119 // qualifier expression is a type. 2120 Type t = syms.classType; 2121 Type arg = types.boxedClass(site).type; 2122 t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym); 2123 return new VarSymbol( 2124 STATIC | PUBLIC | FINAL, names._class, t, site.tsym); 2125 } else { 2126 log.error(pos, "cant.deref", site); 2127 return syms.errSymbol; 2128 } 2129 } 2130 } 2131 2132 /** Determine type of identifier or select expression and check that 2133 * (1) the referenced symbol is not deprecated 2134 * (2) the symbol's type is safe (@see checkSafe) 2135 * (3) if symbol is a variable, check that its type and kind are 2136 * compatible with the prototype and protokind. 2137 * (4) if symbol is an instance field of a raw type, 2138 * which is being assigned to, issue an unchecked warning if its 2139 * type changes under erasure. 2140 * (5) if symbol is an instance method of a raw type, issue an 2141 * unchecked warning if its argument types change under erasure. 2142 * If checks succeed: 2143 * If symbol is a constant, return its constant type 2144 * else if symbol is a method, return its result type 2145 * otherwise return its type. 2146 * Otherwise return errType. 2147 * 2148 * @param tree The syntax tree representing the identifier 2149 * @param site If this is a select, the type of the selected 2150 * expression, otherwise the type of the current class. 2151 * @param sym The symbol representing the identifier. 2152 * @param env The current environment. 2153 * @param pkind The set of expected kinds. 2154 * @param pt The expected type. 2155 */ 2156 Type checkId(JCTree tree, 2157 Type site, 2158 Symbol sym, 2159 Env<AttrContext> env, 2160 int pkind, 2161 Type pt, 2162 boolean useVarargs) { 2163 if (pt.isErroneous()) return types.createErrorType(site); 2164 Type owntype; // The computed type of this identifier occurrence. 2165 switch (sym.kind) { 2166 case TYP: 2167 // For types, the computed type equals the symbol's type, 2168 // except for two situations: 2169 owntype = sym.type; 2170 if (owntype.tag == CLASS) { 2171 Type ownOuter = owntype.getEnclosingType(); 2172 2173 // (a) If the symbol's type is parameterized, erase it 2174 // because no type parameters were given. 2175 // We recover generic outer type later in visitTypeApply. 2176 if (owntype.tsym.type.getTypeArguments().nonEmpty()) { 2177 owntype = types.erasure(owntype); 2178 } 2179 2180 // (b) If the symbol's type is an inner class, then 2181 // we have to interpret its outer type as a superclass 2182 // of the site type. Example: 2183 // 2184 // class Tree<A> { class Visitor { ... } } 2185 // class PointTree extends Tree<Point> { ... } 2186 // ...PointTree.Visitor... 2187 // 2188 // Then the type of the last expression above is 2189 // Tree<Point>.Visitor. 2190 else if (ownOuter.tag == CLASS && site != ownOuter) { 2191 Type normOuter = site; 2192 if (normOuter.tag == CLASS) 2193 normOuter = types.asEnclosingSuper(site, ownOuter.tsym); 2194 if (normOuter == null) // perhaps from an import 2195 normOuter = types.erasure(ownOuter); 2196 if (normOuter != ownOuter) 2197 owntype = new ClassType( 2198 normOuter, List.<Type>nil(), owntype.tsym); 2199 } 2200 } 2201 break; 2202 case VAR: 2203 VarSymbol v = (VarSymbol)sym; 2204 // Test (4): if symbol is an instance field of a raw type, 2205 // which is being assigned to, issue an unchecked warning if 2206 // its type changes under erasure. 2207 if (allowGenerics && 2208 pkind == VAR && 2209 v.owner.kind == TYP && 2210 (v.flags() & STATIC) == 0 && 2211 (site.tag == CLASS || site.tag == TYPEVAR)) { 2212 Type s = types.asOuterSuper(site, v.owner); 2213 if (s != null && 2214 s.isRaw() && 2215 !types.isSameType(v.type, v.erasure(types))) { 2216 chk.warnUnchecked(tree.pos(), 2217 "unchecked.assign.to.var", 2218 v, s); 2219 } 2220 } 2221 // The computed type of a variable is the type of the 2222 // variable symbol, taken as a member of the site type. 2223 owntype = (sym.owner.kind == TYP && 2224 sym.name != names._this && sym.name != names._super) 2225 ? types.memberType(site, sym) 2226 : sym.type; 2227 2228 if (env.info.tvars.nonEmpty()) { 2229 Type owntype1 = new ForAll(env.info.tvars, owntype); 2230 for (List<Type> l = env.info.tvars; l.nonEmpty(); l = l.tail) 2231 if (!owntype.contains(l.head)) { 2232 log.error(tree.pos(), "undetermined.type", owntype1); 2233 owntype1 = types.createErrorType(owntype1); 2234 } 2235 owntype = owntype1; 2236 } 2237 2238 // If the variable is a constant, record constant value in 2239 // computed type. 2240 if (v.getConstValue() != null && isStaticReference(tree)) 2241 owntype = owntype.constType(v.getConstValue()); 2242 2243 if (pkind == VAL) { 2244 owntype = capture(owntype); // capture "names as expressions" 2245 } 2246 break; 2247 case MTH: { 2248 JCMethodInvocation app = (JCMethodInvocation)env.tree; 2249 owntype = checkMethod(site, sym, env, app.args, 2250 pt.getParameterTypes(), pt.getTypeArguments(), 2251 env.info.varArgs); 2252 break; 2253 } 2254 case PCK: case ERR: 2255 owntype = sym.type; 2256 break; 2257 default: 2258 throw new AssertionError("unexpected kind: " + sym.kind + 2259 " in tree " + tree); 2260 } 2261 2262 // Test (1): emit a `deprecation' warning if symbol is deprecated. 2263 // (for constructors, the error was given when the constructor was 2264 // resolved) 2265 if (sym.name != names.init && 2266 (sym.flags() & DEPRECATED) != 0 && 2267 (env.info.scope.owner.flags() & DEPRECATED) == 0 && 2268 sym.outermostClass() != env.info.scope.owner.outermostClass()) 2269 chk.warnDeprecated(tree.pos(), sym); 2270 2271 if ((sym.flags() & PROPRIETARY) != 0) { 2272 if (enableSunApiLintControl) 2273 chk.warnSunApi(tree.pos(), "sun.proprietary", sym); 2274 else 2275 log.strictWarning(tree.pos(), "sun.proprietary", sym); 2276 } 2277 2278 // Test (3): if symbol is a variable, check that its type and 2279 // kind are compatible with the prototype and protokind. 2280 return check(tree, owntype, sym.kind, pkind, pt); 2281 } 2282 2283 /** Check that variable is initialized and evaluate the variable's 2284 * initializer, if not yet done. Also check that variable is not 2285 * referenced before it is defined. 2286 * @param tree The tree making up the variable reference. 2287 * @param env The current environment. 2288 * @param v The variable's symbol. 2289 */ 2290 private void checkInit(JCTree tree, 2291 Env<AttrContext> env, 2292 VarSymbol v, 2293 boolean onlyWarning) { 2294 // System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " + 2295 // tree.pos + " " + v.pos + " " + 2296 // Resolve.isStatic(env));//DEBUG 2297 2298 // A forward reference is diagnosed if the declaration position 2299 // of the variable is greater than the current tree position 2300 // and the tree and variable definition occur in the same class 2301 // definition. Note that writes don't count as references. 2302 // This check applies only to class and instance 2303 // variables. Local variables follow different scope rules, 2304 // and are subject to definite assignment checking. 2305 if ((env.info.enclVar == v || v.pos > tree.pos) && 2306 v.owner.kind == TYP && 2307 canOwnInitializer(env.info.scope.owner) && 2308 v.owner == env.info.scope.owner.enclClass() && 2309 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) && 2310 (env.tree.getTag() != JCTree.ASSIGN || 2311 TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) { 2312 String suffix = (env.info.enclVar == v) ? 2313 "self.ref" : "forward.ref"; 2314 if (!onlyWarning || isStaticEnumField(v)) { 2315 log.error(tree.pos(), "illegal." + suffix); 2316 } else if (useBeforeDeclarationWarning) { 2317 log.warning(tree.pos(), suffix, v); 2318 } 2319 } 2320 2321 v.getConstValue(); // ensure initializer is evaluated 2322 2323 checkEnumInitializer(tree, env, v); 2324 } 2325 2326 /** 2327 * Check for illegal references to static members of enum. In 2328 * an enum type, constructors and initializers may not 2329 * reference its static members unless they are constant. 2330 * 2331 * @param tree The tree making up the variable reference. 2332 * @param env The current environment. 2333 * @param v The variable's symbol. 2334 * @see JLS 3rd Ed. (8.9 Enums) 2335 */ 2336 private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) { 2337 // JLS 3rd Ed.: 2338 // 2339 // "It is a compile-time error to reference a static field 2340 // of an enum type that is not a compile-time constant 2341 // (15.28) from constructors, instance initializer blocks, 2342 // or instance variable initializer expressions of that 2343 // type. It is a compile-time error for the constructors, 2344 // instance initializer blocks, or instance variable 2345 // initializer expressions of an enum constant e to refer 2346 // to itself or to an enum constant of the same type that 2347 // is declared to the right of e." 2348 if (isStaticEnumField(v)) { 2349 ClassSymbol enclClass = env.info.scope.owner.enclClass(); 2350 2351 if (enclClass == null || enclClass.owner == null) 2352 return; 2353 2354 // See if the enclosing class is the enum (or a 2355 // subclass thereof) declaring v. If not, this 2356 // reference is OK. 2357 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type)) 2358 return; 2359 2360 // If the reference isn't from an initializer, then 2361 // the reference is OK. 2362 if (!Resolve.isInitializer(env)) 2363 return; 2364 2365 log.error(tree.pos(), "illegal.enum.static.ref"); 2366 } 2367 } 2368 2369 /** Is the given symbol a static, non-constant field of an Enum? 2370 * Note: enum literals should not be regarded as such 2371 */ 2372 private boolean isStaticEnumField(VarSymbol v) { 2373 return Flags.isEnum(v.owner) && 2374 Flags.isStatic(v) && 2375 !Flags.isConstant(v) && 2376 v.name != names._class; 2377 } 2378 2379 /** Can the given symbol be the owner of code which forms part 2380 * if class initialization? This is the case if the symbol is 2381 * a type or field, or if the symbol is the synthetic method. 2382 * owning a block. 2383 */ 2384 private boolean canOwnInitializer(Symbol sym) { 2385 return 2386 (sym.kind & (VAR | TYP)) != 0 || 2387 (sym.kind == MTH && (sym.flags() & BLOCK) != 0); 2388 } 2389 2390 Warner noteWarner = new Warner(); 2391 2392 /** 2393 * Check that method arguments conform to its instantation. 2394 **/ 2395 public Type checkMethod(Type site, 2396 Symbol sym, 2397 Env<AttrContext> env, 2398 final List<JCExpression> argtrees, 2399 List<Type> argtypes, 2400 List<Type> typeargtypes, 2401 boolean useVarargs) { 2402 // Test (5): if symbol is an instance method of a raw type, issue 2403 // an unchecked warning if its argument types change under erasure. 2404 if (allowGenerics && 2405 (sym.flags() & STATIC) == 0 && 2406 (site.tag == CLASS || site.tag == TYPEVAR)) { 2407 Type s = types.asOuterSuper(site, sym.owner); 2408 if (s != null && s.isRaw() && 2409 !types.isSameTypes(sym.type.getParameterTypes(), 2410 sym.erasure(types).getParameterTypes())) { 2411 chk.warnUnchecked(env.tree.pos(), 2412 "unchecked.call.mbr.of.raw.type", 2413 sym, s); 2414 } 2415 } 2416 2417 // Compute the identifier's instantiated type. 2418 // For methods, we need to compute the instance type by 2419 // Resolve.instantiate from the symbol's type as well as 2420 // any type arguments and value arguments. 2421 noteWarner.warned = false; 2422 Type owntype = rs.instantiate(env, 2423 site, 2424 sym, 2425 argtypes, 2426 typeargtypes, 2427 true, 2428 useVarargs, 2429 noteWarner); 2430 boolean warned = noteWarner.warned; 2431 2432 // If this fails, something went wrong; we should not have 2433 // found the identifier in the first place. 2434 if (owntype == null) { 2435 if (!pt.isErroneous()) 2436 log.error(env.tree.pos(), 2437 "internal.error.cant.instantiate", 2438 sym, site, 2439 Type.toString(pt.getParameterTypes())); 2440 owntype = types.createErrorType(site); 2441 } else { 2442 // System.out.println("call : " + env.tree); 2443 // System.out.println("method : " + owntype); 2444 // System.out.println("actuals: " + argtypes); 2445 List<Type> formals = owntype.getParameterTypes(); 2446 Type last = useVarargs ? formals.last() : null; 2447 if (sym.name==names.init && 2448 sym.owner == syms.enumSym) 2449 formals = formals.tail.tail; 2450 List<JCExpression> args = argtrees; 2451 while (formals.head != last) { 2452 JCTree arg = args.head; 2453 Warner warn = chk.convertWarner(arg.pos(), arg.type, formals.head); 2454 assertConvertible(arg, arg.type, formals.head, warn); 2455 warned |= warn.warned; 2456 args = args.tail; 2457 formals = formals.tail; 2458 } 2459 if (useVarargs) { 2460 Type varArg = types.elemtype(last); 2461 while (args.tail != null) { 2462 JCTree arg = args.head; 2463 Warner warn = chk.convertWarner(arg.pos(), arg.type, varArg); 2464 assertConvertible(arg, arg.type, varArg, warn); 2465 warned |= warn.warned; 2466 args = args.tail; 2467 } 2468 } else if ((sym.flags() & VARARGS) != 0 && allowVarargs) { 2469 // non-varargs call to varargs method 2470 Type varParam = owntype.getParameterTypes().last(); 2471 Type lastArg = argtypes.last(); 2472 if (types.isSubtypeUnchecked(lastArg, types.elemtype(varParam)) && 2473 !types.isSameType(types.erasure(varParam), types.erasure(lastArg))) 2474 log.warning(argtrees.last().pos(), "inexact.non-varargs.call", 2475 types.elemtype(varParam), 2476 varParam); 2477 } 2478 2479 if (warned && sym.type.tag == FORALL) { 2480 chk.warnUnchecked(env.tree.pos(), 2481 "unchecked.meth.invocation.applied", 2482 kindName(sym), 2483 sym.name, 2484 rs.methodArguments(sym.type.getParameterTypes()), 2485 rs.methodArguments(argtypes), 2486 kindName(sym.location()), 2487 sym.location()); 2488 owntype = new MethodType(owntype.getParameterTypes(), 2489 types.erasure(owntype.getReturnType()), 2490 owntype.getThrownTypes(), 2491 syms.methodClass); 2492 } 2493 if (useVarargs) { 2494 JCTree tree = env.tree; 2495 Type argtype = owntype.getParameterTypes().last(); 2496 if (!types.isReifiable(argtype)) 2497 chk.warnUnchecked(env.tree.pos(), 2498 "unchecked.generic.array.creation", 2499 argtype); 2500 Type elemtype = types.elemtype(argtype); 2501 switch (tree.getTag()) { 2502 case JCTree.APPLY: 2503 ((JCMethodInvocation) tree).varargsElement = elemtype; 2504 break; 2505 case JCTree.NEWCLASS: 2506 ((JCNewClass) tree).varargsElement = elemtype; 2507 break; 2508 default: 2509 throw new AssertionError(""+tree); 2510 } 2511 } 2512 } 2513 return owntype; 2514 } 2515 2516 private void assertConvertible(JCTree tree, Type actual, Type formal, Warner warn) { 2517 if (types.isConvertible(actual, formal, warn)) 2518 return; 2519 2520 if (formal.isCompound() 2521 && types.isSubtype(actual, types.supertype(formal)) 2522 && types.isSubtypeUnchecked(actual, types.interfaces(formal), warn)) 2523 return; 2524 2525 if (false) { 2526 // TODO: make assertConvertible work 2527 chk.typeError(tree.pos(), diags.fragment("incompatible.types"), actual, formal); 2528 throw new AssertionError("Tree: " + tree 2529 + " actual:" + actual 2530 + " formal: " + formal); 2531 } 2532 } 2533 2534 public void visitLiteral(JCLiteral tree) { 2535 result = check( 2536 tree, litType(tree.typetag).constType(tree.value), VAL, pkind, pt); 2537 } 2538 //where 2539 /** Return the type of a literal with given type tag. 2540 */ 2541 Type litType(int tag) { 2542 return (tag == TypeTags.CLASS) ? syms.stringType : syms.typeOfTag[tag]; 2543 } 2544 2545 public void visitTypeIdent(JCPrimitiveTypeTree tree) { 2546 result = check(tree, syms.typeOfTag[tree.typetag], TYP, pkind, pt); 2547 } 2548 2549 public void visitTypeArray(JCArrayTypeTree tree) { 2550 Type etype = attribType(tree.elemtype, env); 2551 Type type = new ArrayType(etype, syms.arrayClass); 2552 result = check(tree, type, TYP, pkind, pt); 2553 } 2554 2555 /** Visitor method for parameterized types. 2556 * Bound checking is left until later, since types are attributed 2557 * before supertype structure is completely known 2558 */ 2559 public void visitTypeApply(JCTypeApply tree) { 2560 Type owntype = types.createErrorType(tree.type); 2561 2562 // Attribute functor part of application and make sure it's a class. 2563 Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env)); 2564 2565 // Attribute type parameters 2566 List<Type> actuals = attribTypes(tree.arguments, env); 2567 2568 if (clazztype.tag == CLASS) { 2569 List<Type> formals = clazztype.tsym.type.getTypeArguments(); 2570 2571 if (actuals.length() == formals.length() || actuals.isEmpty()) { 2572 List<Type> a = actuals; 2573 List<Type> f = formals; 2574 while (a.nonEmpty()) { 2575 a.head = a.head.withTypeVar(f.head); 2576 a = a.tail; 2577 f = f.tail; 2578 } 2579 // Compute the proper generic outer 2580 Type clazzOuter = clazztype.getEnclosingType(); 2581 if (clazzOuter.tag == CLASS) { 2582 Type site; 2583 JCExpression clazz = TreeInfo.typeIn(tree.clazz); 2584 if (clazz.getTag() == JCTree.IDENT) { 2585 site = env.enclClass.sym.type; 2586 } else if (clazz.getTag() == JCTree.SELECT) { 2587 site = ((JCFieldAccess) clazz).selected.type; 2588 } else throw new AssertionError(""+tree); 2589 if (clazzOuter.tag == CLASS && site != clazzOuter) { 2590 if (site.tag == CLASS) 2591 site = types.asOuterSuper(site, clazzOuter.tsym); 2592 if (site == null) 2593 site = types.erasure(clazzOuter); 2594 clazzOuter = site; 2595 } 2596 } 2597 if (actuals.nonEmpty()) { 2598 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym); 2599 } 2600 else if (TreeInfo.isDiamond(tree)) { 2601 //a type apply with no explicit type arguments - diamond operator 2602 //the result type is a forall F where F's tvars are the type-variables 2603 //that will be inferred when F is checked against the expected type 2604 List<Type> ftvars = clazztype.tsym.type.getTypeArguments(); 2605 List<Type> new_tvars = types.newInstances(ftvars); 2606 clazztype = new ClassType(clazzOuter, new_tvars, clazztype.tsym); 2607 owntype = new ForAll(new_tvars, clazztype); 2608 } 2609 } else { 2610 if (formals.length() != 0) { 2611 log.error(tree.pos(), "wrong.number.type.args", 2612 Integer.toString(formals.length())); 2613 } else { 2614 log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym); 2615 } 2616 owntype = types.createErrorType(tree.type); 2617 } 2618 } 2619 result = check(tree, owntype, TYP, pkind, pt); 2620 } 2621 2622 public void visitTypeParameter(JCTypeParameter tree) { 2623 TypeVar a = (TypeVar)tree.type; 2624 Set<Type> boundSet = new HashSet<Type>(); 2625 if (a.bound.isErroneous()) 2626 return; 2627 List<Type> bs = types.getBounds(a); 2628 if (tree.bounds.nonEmpty()) { 2629 // accept class or interface or typevar as first bound. 2630 Type b = checkBase(bs.head, tree.bounds.head, env, false, false, false); 2631 boundSet.add(types.erasure(b)); 2632 if (b.isErroneous()) { 2633 a.bound = b; 2634 } 2635 else if (b.tag == TYPEVAR) { 2636 // if first bound was a typevar, do not accept further bounds. 2637 if (tree.bounds.tail.nonEmpty()) { 2638 log.error(tree.bounds.tail.head.pos(), 2639 "type.var.may.not.be.followed.by.other.bounds"); 2640 tree.bounds = List.of(tree.bounds.head); 2641 a.bound = bs.head; 2642 } 2643 } else { 2644 // if first bound was a class or interface, accept only interfaces 2645 // as further bounds. 2646 for (JCExpression bound : tree.bounds.tail) { 2647 bs = bs.tail; 2648 Type i = checkBase(bs.head, bound, env, false, true, false); 2649 if (i.isErroneous()) 2650 a.bound = i; 2651 else if (i.tag == CLASS) 2652 chk.checkNotRepeated(bound.pos(), types.erasure(i), boundSet); 2653 } 2654 } 2655 } 2656 bs = types.getBounds(a); 2657 2658 // in case of multiple bounds ... 2659 if (bs.length() > 1) { 2660 // ... the variable's bound is a class type flagged COMPOUND 2661 // (see comment for TypeVar.bound). 2662 // In this case, generate a class tree that represents the 2663 // bound class, ... 2664 JCTree extending; 2665 List<JCExpression> implementing; 2666 if ((bs.head.tsym.flags() & INTERFACE) == 0) { 2667 extending = tree.bounds.head; 2668 implementing = tree.bounds.tail; 2669 } else { 2670 extending = null; 2671 implementing = tree.bounds; 2672 } 2673 JCClassDecl cd = make.at(tree.pos).ClassDef( 2674 make.Modifiers(PUBLIC | ABSTRACT), 2675 tree.name, List.<JCTypeParameter>nil(), 2676 extending, implementing, List.<JCTree>nil()); 2677 2678 ClassSymbol c = (ClassSymbol)a.getUpperBound().tsym; 2679 assert (c.flags() & COMPOUND) != 0; 2680 cd.sym = c; 2681 c.sourcefile = env.toplevel.sourcefile; 2682 2683 // ... and attribute the bound class 2684 c.flags_field |= UNATTRIBUTED; 2685 Env<AttrContext> cenv = enter.classEnv(cd, env); 2686 enter.typeEnvs.put(c, cenv); 2687 } 2688 } 2689 2690 2691 public void visitWildcard(JCWildcard tree) { 2692 //- System.err.println("visitWildcard("+tree+");");//DEBUG 2693 Type type = (tree.kind.kind == BoundKind.UNBOUND) 2694 ? syms.objectType 2695 : attribType(tree.inner, env); 2696 result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type), 2697 tree.kind.kind, 2698 syms.boundClass), 2699 TYP, pkind, pt); 2700 } 2701 2702 public void visitAnnotation(JCAnnotation tree) { 2703 log.error(tree.pos(), "annotation.not.valid.for.type", pt); 2704 result = tree.type = syms.errType; 2705 } 2706 2707 public void visitAnnotatedType(JCAnnotatedType tree) { 2708 result = tree.type = attribType(tree.getUnderlyingType(), env); 2709 } 2710 2711 public void visitErroneous(JCErroneous tree) { 2712 if (tree.errs != null) 2713 for (JCTree err : tree.errs) 2714 attribTree(err, env, ERR, pt); 2715 result = tree.type = syms.errType; 2716 } 2717 2718 /** Default visitor method for all other trees. 2719 */ 2720 public void visitTree(JCTree tree) { 2721 throw new AssertionError(); 2722 } 2723 2724 /** Main method: attribute class definition associated with given class symbol. 2725 * reporting completion failures at the given position. 2726 * @param pos The source position at which completion errors are to be 2727 * reported. 2728 * @param c The class symbol whose definition will be attributed. 2729 */ 2730 public void attribClass(DiagnosticPosition pos, ClassSymbol c) { 2731 try { 2732 annotate.flush(); 2733 attribClass(c); 2734 } catch (CompletionFailure ex) { 2735 chk.completionError(pos, ex); 2736 } 2737 } 2738 2739 /** Attribute class definition associated with given class symbol. 2740 * @param c The class symbol whose definition will be attributed. 2741 */ 2742 void attribClass(ClassSymbol c) throws CompletionFailure { 2743 if (c.type.tag == ERROR) return; 2744 2745 // Check for cycles in the inheritance graph, which can arise from 2746 // ill-formed class files. 2747 chk.checkNonCyclic(null, c.type); 2748 2749 Type st = types.supertype(c.type); 2750 if ((c.flags_field & Flags.COMPOUND) == 0) { 2751 // First, attribute superclass. 2752 if (st.tag == CLASS) 2753 attribClass((ClassSymbol)st.tsym); 2754 2755 // Next attribute owner, if it is a class. 2756 if (c.owner.kind == TYP && c.owner.type.tag == CLASS) 2757 attribClass((ClassSymbol)c.owner); 2758 } 2759 2760 // The previous operations might have attributed the current class 2761 // if there was a cycle. So we test first whether the class is still 2762 // UNATTRIBUTED. 2763 if ((c.flags_field & UNATTRIBUTED) != 0) { 2764 c.flags_field &= ~UNATTRIBUTED; 2765 2766 // Get environment current at the point of class definition. 2767 Env<AttrContext> env = enter.typeEnvs.get(c); 2768 2769 // The info.lint field in the envs stored in enter.typeEnvs is deliberately uninitialized, 2770 // because the annotations were not available at the time the env was created. Therefore, 2771 // we look up the environment chain for the first enclosing environment for which the 2772 // lint value is set. Typically, this is the parent env, but might be further if there 2773 // are any envs created as a result of TypeParameter nodes. 2774 Env<AttrContext> lintEnv = env; 2775 while (lintEnv.info.lint == null) 2776 lintEnv = lintEnv.next; 2777 2778 // Having found the enclosing lint value, we can initialize the lint value for this class 2779 env.info.lint = lintEnv.info.lint.augment(c.attributes_field, c.flags()); 2780 2781 Lint prevLint = chk.setLint(env.info.lint); 2782 JavaFileObject prev = log.useSource(c.sourcefile); 2783 2784 try { 2785 // java.lang.Enum may not be subclassed by a non-enum 2786 if (st.tsym == syms.enumSym && 2787 ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0)) 2788 log.error(env.tree.pos(), "enum.no.subclassing"); 2789 2790 // Enums may not be extended by source-level classes 2791 if (st.tsym != null && 2792 ((st.tsym.flags_field & Flags.ENUM) != 0) && 2793 ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0) && 2794 !target.compilerBootstrap(c)) { 2795 log.error(env.tree.pos(), "enum.types.not.extensible"); 2796 } 2797 attribClassBody(env, c); 2798 2799 chk.checkDeprecatedAnnotation(env.tree.pos(), c); 2800 } finally { 2801 log.useSource(prev); 2802 chk.setLint(prevLint); 2803 } 2804 2805 } 2806 } 2807 2808 public void visitImport(JCImport tree) { 2809 // nothing to do 2810 } 2811 2812 /** Finish the attribution of a class. */ 2813 private void attribClassBody(Env<AttrContext> env, ClassSymbol c) { 2814 JCClassDecl tree = (JCClassDecl)env.tree; 2815 assert c == tree.sym; 2816 2817 // Validate annotations 2818 chk.validateAnnotations(tree.mods.annotations, c); 2819 2820 // Validate type parameters, supertype and interfaces. 2821 attribBounds(tree.typarams); 2822 chk.validate(tree.typarams, env); 2823 chk.validate(tree.extending, env); 2824 chk.validate(tree.implementing, env); 2825 2826 // If this is a non-abstract class, check that it has no abstract 2827 // methods or unimplemented methods of an implemented interface. 2828 if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) { 2829 if (!relax) 2830 chk.checkAllDefined(tree.pos(), c); 2831 } 2832 2833 if ((c.flags() & ANNOTATION) != 0) { 2834 if (tree.implementing.nonEmpty()) 2835 log.error(tree.implementing.head.pos(), 2836 "cant.extend.intf.annotation"); 2837 if (tree.typarams.nonEmpty()) 2838 log.error(tree.typarams.head.pos(), 2839 "intf.annotation.cant.have.type.params"); 2840 } else { 2841 // Check that all extended classes and interfaces 2842 // are compatible (i.e. no two define methods with same arguments 2843 // yet different return types). (JLS 8.4.6.3) 2844 chk.checkCompatibleSupertypes(tree.pos(), c.type); 2845 } 2846 2847 // Check that class does not import the same parameterized interface 2848 // with two different argument lists. 2849 chk.checkClassBounds(tree.pos(), c.type); 2850 2851 tree.type = c.type; 2852 2853 boolean assertsEnabled = false; 2854 assert assertsEnabled = true; 2855 if (assertsEnabled) { 2856 for (List<JCTypeParameter> l = tree.typarams; 2857 l.nonEmpty(); l = l.tail) 2858 assert env.info.scope.lookup(l.head.name).scope != null; 2859 } 2860 2861 // Check that a generic class doesn't extend Throwable 2862 if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType)) 2863 log.error(tree.extending.pos(), "generic.throwable"); 2864 2865 // Check that all methods which implement some 2866 // method conform to the method they implement. 2867 chk.checkImplementations(tree); 2868 2869 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) { 2870 // Attribute declaration 2871 attribStat(l.head, env); 2872 // Check that declarations in inner classes are not static (JLS 8.1.2) 2873 // Make an exception for static constants. 2874 if (c.owner.kind != PCK && 2875 ((c.flags() & STATIC) == 0 || c.name == names.empty) && 2876 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) { 2877 Symbol sym = null; 2878 if (l.head.getTag() == JCTree.VARDEF) sym = ((JCVariableDecl) l.head).sym; 2879 if (sym == null || 2880 sym.kind != VAR || 2881 ((VarSymbol) sym).getConstValue() == null) 2882 log.error(l.head.pos(), "icls.cant.have.static.decl"); 2883 } 2884 } 2885 2886 // Check for cycles among non-initial constructors. 2887 chk.checkCyclicConstructors(tree); 2888 2889 // Check for cycles among annotation elements. 2890 chk.checkNonCyclicElements(tree); 2891 2892 // Check for proper use of serialVersionUID 2893 if (env.info.lint.isEnabled(Lint.LintCategory.SERIAL) && 2894 isSerializable(c) && 2895 (c.flags() & Flags.ENUM) == 0 && 2896 (c.flags() & ABSTRACT) == 0) { 2897 checkSerialVersionUID(tree, c); 2898 } 2899 2900 // Check type annotations applicability rules 2901 validateTypeAnnotations(tree); 2902 } 2903 // where 2904 /** check if a class is a subtype of Serializable, if that is available. */ 2905 private boolean isSerializable(ClassSymbol c) { 2906 try { 2907 syms.serializableType.complete(); 2908 } 2909 catch (CompletionFailure e) { 2910 return false; 2911 } 2912 return types.isSubtype(c.type, syms.serializableType); 2913 } 2914 2915 /** Check that an appropriate serialVersionUID member is defined. */ 2916 private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) { 2917 2918 // check for presence of serialVersionUID 2919 Scope.Entry e = c.members().lookup(names.serialVersionUID); 2920 while (e.scope != null && e.sym.kind != VAR) e = e.next(); 2921 if (e.scope == null) { 2922 log.warning(tree.pos(), "missing.SVUID", c); 2923 return; 2924 } 2925 2926 // check that it is static final 2927 VarSymbol svuid = (VarSymbol)e.sym; 2928 if ((svuid.flags() & (STATIC | FINAL)) != 2929 (STATIC | FINAL)) 2930 log.warning(TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c); 2931 2932 // check that it is long 2933 else if (svuid.type.tag != TypeTags.LONG) 2934 log.warning(TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c); 2935 2936 // check constant 2937 else if (svuid.getConstValue() == null) 2938 log.warning(TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c); 2939 } 2940 2941 private Type capture(Type type) { 2942 return types.capture(type); 2943 } 2944 2945 private void validateTypeAnnotations(JCTree tree) { 2946 tree.accept(typeAnnotationsValidator); 2947 } 2948 //where 2949 private final JCTree.Visitor typeAnnotationsValidator = 2950 new TreeScanner() { 2951 public void visitAnnotation(JCAnnotation tree) { 2952 if (tree instanceof JCTypeAnnotation) { 2953 chk.validateTypeAnnotation((JCTypeAnnotation)tree, false); 2954 } 2955 super.visitAnnotation(tree); 2956 } 2957 public void visitTypeParameter(JCTypeParameter tree) { 2958 chk.validateTypeAnnotations(tree.annotations, true); 2959 // don't call super. skip type annotations 2960 scan(tree.bounds); 2961 } 2962 public void visitMethodDef(JCMethodDecl tree) { 2963 // need to check static methods 2964 if ((tree.sym.flags() & Flags.STATIC) != 0) { 2965 for (JCTypeAnnotation a : tree.receiverAnnotations) { 2966 if (chk.isTypeAnnotation(a, false)) 2967 log.error(a.pos(), "annotation.type.not.applicable"); 2968 } 2969 } 2970 super.visitMethodDef(tree); 2971 } 2972 }; 2973 }