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