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