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