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