1 /* 2 * Copyright (c) 1999, 2013, 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 30 import javax.lang.model.element.ElementKind; 31 import javax.lang.model.type.TypeKind; 32 import javax.tools.JavaFileObject; 33 34 import com.sun.source.tree.IdentifierTree; 35 import com.sun.source.tree.MemberReferenceTree.ReferenceMode; 36 import com.sun.source.tree.MemberSelectTree; 37 import com.sun.source.tree.TreeVisitor; 38 import com.sun.source.util.SimpleTreeVisitor; 39 import com.sun.tools.javac.code.*; 40 import com.sun.tools.javac.code.Lint.LintCategory; 41 import com.sun.tools.javac.code.Symbol.*; 42 import com.sun.tools.javac.code.Type.*; 43 import com.sun.tools.javac.comp.Check.CheckContext; 44 import com.sun.tools.javac.comp.DeferredAttr.AttrMode; 45 import com.sun.tools.javac.comp.Infer.InferenceContext; 46 import com.sun.tools.javac.comp.Infer.FreeTypeListener; 47 import com.sun.tools.javac.jvm.*; 48 import com.sun.tools.javac.tree.*; 49 import com.sun.tools.javac.tree.JCTree.*; 50 import com.sun.tools.javac.tree.JCTree.JCPolyExpression.*; 51 import com.sun.tools.javac.util.*; 52 import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; 53 import com.sun.tools.javac.util.List; 54 import static com.sun.tools.javac.code.Flags.*; 55 import static com.sun.tools.javac.code.Flags.ANNOTATION; 56 import static com.sun.tools.javac.code.Flags.BLOCK; 57 import static com.sun.tools.javac.code.Kinds.*; 58 import static com.sun.tools.javac.code.Kinds.ERRONEOUS; 59 import static com.sun.tools.javac.code.TypeTag.*; 60 import static com.sun.tools.javac.code.TypeTag.WILDCARD; 61 import static com.sun.tools.javac.tree.JCTree.Tag.*; 62 63 /** This is the main context-dependent analysis phase in GJC. It 64 * encompasses name resolution, type checking and constant folding as 65 * subtasks. Some subtasks involve auxiliary classes. 66 * @see Check 67 * @see Resolve 68 * @see ConstFold 69 * @see Infer 70 * 71 * <p><b>This is NOT part of any supported API. 72 * If you write code that depends on this, you do so at your own risk. 73 * This code and its internal interfaces are subject to change or 74 * deletion without notice.</b> 75 */ 76 public class Attr extends JCTree.Visitor { 77 protected static final Context.Key<Attr> attrKey = 78 new Context.Key<Attr>(); 79 80 final Names names; 81 final Log log; 82 final Symtab syms; 83 final Resolve rs; 84 final Infer infer; 85 final DeferredAttr deferredAttr; 86 final Check chk; 87 final Flow flow; 88 final MemberEnter memberEnter; 89 final TreeMaker make; 90 final ConstFold cfolder; 91 final Enter enter; 92 final Target target; 93 final Types types; 94 final JCDiagnostic.Factory diags; 95 final Annotate annotate; 96 final DeferredLintHandler deferredLintHandler; 97 98 public static Attr instance(Context context) { 99 Attr instance = context.get(attrKey); 100 if (instance == null) 101 instance = new Attr(context); 102 return instance; 103 } 104 105 protected Attr(Context context) { 106 context.put(attrKey, this); 107 108 names = Names.instance(context); 109 log = Log.instance(context); 110 syms = Symtab.instance(context); 111 rs = Resolve.instance(context); 112 chk = Check.instance(context); 113 flow = Flow.instance(context); 114 memberEnter = MemberEnter.instance(context); 115 make = TreeMaker.instance(context); 116 enter = Enter.instance(context); 117 infer = Infer.instance(context); 118 deferredAttr = DeferredAttr.instance(context); 119 cfolder = ConstFold.instance(context); 120 target = Target.instance(context); 121 types = Types.instance(context); 122 diags = JCDiagnostic.Factory.instance(context); 123 annotate = Annotate.instance(context); 124 deferredLintHandler = DeferredLintHandler.instance(context); 125 126 Options options = Options.instance(context); 127 128 Source source = Source.instance(context); 129 allowGenerics = source.allowGenerics(); 130 allowVarargs = source.allowVarargs(); 131 allowEnums = source.allowEnums(); 132 allowBoxing = source.allowBoxing(); 133 allowCovariantReturns = source.allowCovariantReturns(); 134 allowAnonOuterThis = source.allowAnonOuterThis(); 135 allowStringsInSwitch = source.allowStringsInSwitch(); 136 allowPoly = source.allowPoly(); 137 allowLambda = source.allowLambda(); 138 allowDefaultMethods = source.allowDefaultMethods(); 139 sourceName = source.name; 140 relax = (options.isSet("-retrofit") || 141 options.isSet("-relax")); 142 findDiamonds = options.get("findDiamond") != null && 143 source.allowDiamond(); 144 useBeforeDeclarationWarning = options.isSet("useBeforeDeclarationWarning"); 145 identifyLambdaCandidate = options.getBoolean("identifyLambdaCandidate", false); 146 147 statInfo = new ResultInfo(NIL, Type.noType); 148 varInfo = new ResultInfo(VAR, Type.noType); 149 unknownExprInfo = new ResultInfo(VAL, Type.noType); 150 unknownTypeInfo = new ResultInfo(TYP, Type.noType); 151 recoveryInfo = new RecoveryInfo(deferredAttr.emptyDeferredAttrContext); 152 } 153 154 /** Switch: relax some constraints for retrofit mode. 155 */ 156 boolean relax; 157 158 /** Switch: support target-typing inference 159 */ 160 boolean allowPoly; 161 162 /** Switch: support generics? 163 */ 164 boolean allowGenerics; 165 166 /** Switch: allow variable-arity methods. 167 */ 168 boolean allowVarargs; 169 170 /** Switch: support enums? 171 */ 172 boolean allowEnums; 173 174 /** Switch: support boxing and unboxing? 175 */ 176 boolean allowBoxing; 177 178 /** Switch: support covariant result types? 179 */ 180 boolean allowCovariantReturns; 181 182 /** Switch: support lambda expressions ? 183 */ 184 boolean allowLambda; 185 186 /** Switch: support default methods ? 187 */ 188 boolean allowDefaultMethods; 189 190 /** Switch: allow references to surrounding object from anonymous 191 * objects during constructor call? 192 */ 193 boolean allowAnonOuterThis; 194 195 /** Switch: generates a warning if diamond can be safely applied 196 * to a given new expression 197 */ 198 boolean findDiamonds; 199 200 /** 201 * Internally enables/disables diamond finder feature 202 */ 203 static final boolean allowDiamondFinder = true; 204 205 /** 206 * Switch: warn about use of variable before declaration? 207 * RFE: 6425594 208 */ 209 boolean useBeforeDeclarationWarning; 210 211 /** 212 * Switch: generate warnings whenever an anonymous inner class that is convertible 213 * to a lambda expression is found 214 */ 215 boolean identifyLambdaCandidate; 216 217 /** 218 * Switch: allow strings in switch? 219 */ 220 boolean allowStringsInSwitch; 221 222 /** 223 * Switch: name of source level; used for error reporting. 224 */ 225 String sourceName; 226 227 /** Check kind and type of given tree against protokind and prototype. 228 * If check succeeds, store type in tree and return it. 229 * If check fails, store errType in tree and return it. 230 * No checks are performed if the prototype is a method type. 231 * It is not necessary in this case since we know that kind and type 232 * are correct. 233 * 234 * @param tree The tree whose kind and type is checked 235 * @param ownkind The computed kind of the tree 236 * @param resultInfo The expected result of the tree 237 */ 238 Type check(final JCTree tree, final Type found, final int ownkind, final ResultInfo resultInfo) { 239 InferenceContext inferenceContext = resultInfo.checkContext.inferenceContext(); 240 Type owntype = found; 241 if (!owntype.hasTag(ERROR) && !resultInfo.pt.hasTag(METHOD) && !resultInfo.pt.hasTag(FORALL)) { 242 if (inferenceContext.free(found)) { 243 inferenceContext.addFreeTypeListener(List.of(found, resultInfo.pt), new FreeTypeListener() { 244 @Override 245 public void typesInferred(InferenceContext inferenceContext) { 246 ResultInfo pendingResult = 247 resultInfo.dup(inferenceContext.asInstType(resultInfo.pt)); 248 check(tree, inferenceContext.asInstType(found), ownkind, pendingResult); 249 } 250 }); 251 return tree.type = resultInfo.pt; 252 } else { 253 if ((ownkind & ~resultInfo.pkind) == 0) { 254 owntype = resultInfo.check(tree, owntype); 255 } else { 256 log.error(tree.pos(), "unexpected.type", 257 kindNames(resultInfo.pkind), 258 kindName(ownkind)); 259 owntype = types.createErrorType(owntype); 260 } 261 } 262 } 263 tree.type = owntype; 264 return owntype; 265 } 266 267 /** Is given blank final variable assignable, i.e. in a scope where it 268 * may be assigned to even though it is final? 269 * @param v The blank final variable. 270 * @param env The current environment. 271 */ 272 boolean isAssignableAsBlankFinal(VarSymbol v, Env<AttrContext> env) { 273 Symbol owner = owner(env); 274 // owner refers to the innermost variable, method or 275 // initializer block declaration at this point. 276 return 277 v.owner == owner 278 || 279 ((owner.name == names.init || // i.e. we are in a constructor 280 owner.kind == VAR || // i.e. we are in a variable initializer 281 (owner.flags() & BLOCK) != 0) // i.e. we are in an initializer block 282 && 283 v.owner == owner.owner 284 && 285 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env)); 286 } 287 288 /** 289 * Return the innermost enclosing owner symbol in a given attribution context 290 */ 291 Symbol owner(Env<AttrContext> env) { 292 while (true) { 293 switch (env.tree.getTag()) { 294 case VARDEF: 295 //a field can be owner 296 VarSymbol vsym = ((JCVariableDecl)env.tree).sym; 297 if (vsym.owner.kind == TYP) { 298 return vsym; 299 } 300 break; 301 case METHODDEF: 302 //method def is always an owner 303 return ((JCMethodDecl)env.tree).sym; 304 case CLASSDEF: 305 //class def is always an owner 306 return ((JCClassDecl)env.tree).sym; 307 case LAMBDA: 308 //a lambda is an owner - return a fresh synthetic method symbol 309 return new MethodSymbol(0, names.empty, null, syms.methodClass); 310 case BLOCK: 311 //static/instance init blocks are owner 312 Symbol blockSym = env.info.scope.owner; 313 if ((blockSym.flags() & BLOCK) != 0) { 314 return blockSym; 315 } 316 break; 317 case TOPLEVEL: 318 //toplevel is always an owner (for pkge decls) 319 return env.info.scope.owner; 320 } 321 Assert.checkNonNull(env.next); 322 env = env.next; 323 } 324 } 325 326 /** Check that variable can be assigned to. 327 * @param pos The current source code position. 328 * @param v The assigned varaible 329 * @param base If the variable is referred to in a Select, the part 330 * to the left of the `.', null otherwise. 331 * @param env The current environment. 332 */ 333 void checkAssignable(DiagnosticPosition pos, VarSymbol v, JCTree base, Env<AttrContext> env) { 334 if ((v.flags() & FINAL) != 0 && 335 ((v.flags() & HASINIT) != 0 336 || 337 !((base == null || 338 (base.hasTag(IDENT) && TreeInfo.name(base) == names._this)) && 339 isAssignableAsBlankFinal(v, env)))) { 340 if (v.isResourceVariable()) { //TWR resource 341 log.error(pos, "try.resource.may.not.be.assigned", v); 342 } else { 343 log.error(pos, "cant.assign.val.to.final.var", v); 344 } 345 } 346 } 347 348 /** Does tree represent a static reference to an identifier? 349 * It is assumed that tree is either a SELECT or an IDENT. 350 * We have to weed out selects from non-type names here. 351 * @param tree The candidate tree. 352 */ 353 boolean isStaticReference(JCTree tree) { 354 if (tree.hasTag(SELECT)) { 355 Symbol lsym = TreeInfo.symbol(((JCFieldAccess) tree).selected); 356 if (lsym == null || lsym.kind != TYP) { 357 return false; 358 } 359 } 360 return true; 361 } 362 363 /** Is this symbol a type? 364 */ 365 static boolean isType(Symbol sym) { 366 return sym != null && sym.kind == TYP; 367 } 368 369 /** The current `this' symbol. 370 * @param env The current environment. 371 */ 372 Symbol thisSym(DiagnosticPosition pos, Env<AttrContext> env) { 373 return rs.resolveSelf(pos, env, env.enclClass.sym, names._this); 374 } 375 376 /** Attribute a parsed identifier. 377 * @param tree Parsed identifier name 378 * @param topLevel The toplevel to use 379 */ 380 public Symbol attribIdent(JCTree tree, JCCompilationUnit topLevel) { 381 Env<AttrContext> localEnv = enter.topLevelEnv(topLevel); 382 localEnv.enclClass = make.ClassDef(make.Modifiers(0), 383 syms.errSymbol.name, 384 null, null, null, null); 385 localEnv.enclClass.sym = syms.errSymbol; 386 return tree.accept(identAttributer, localEnv); 387 } 388 // where 389 private TreeVisitor<Symbol,Env<AttrContext>> identAttributer = new IdentAttributer(); 390 private class IdentAttributer extends SimpleTreeVisitor<Symbol,Env<AttrContext>> { 391 @Override 392 public Symbol visitMemberSelect(MemberSelectTree node, Env<AttrContext> env) { 393 Symbol site = visit(node.getExpression(), env); 394 if (site.kind == ERR) 395 return site; 396 Name name = (Name)node.getIdentifier(); 397 if (site.kind == PCK) { 398 env.toplevel.packge = (PackageSymbol)site; 399 return rs.findIdentInPackage(env, (TypeSymbol)site, name, TYP | PCK); 400 } else { 401 env.enclClass.sym = (ClassSymbol)site; 402 return rs.findMemberType(env, site.asType(), name, (TypeSymbol)site); 403 } 404 } 405 406 @Override 407 public Symbol visitIdentifier(IdentifierTree node, Env<AttrContext> env) { 408 return rs.findIdent(env, (Name)node.getName(), TYP | PCK); 409 } 410 } 411 412 public Type coerce(Type etype, Type ttype) { 413 return cfolder.coerce(etype, ttype); 414 } 415 416 public Type attribType(JCTree node, TypeSymbol sym) { 417 Env<AttrContext> env = enter.typeEnvs.get(sym); 418 Env<AttrContext> localEnv = env.dup(node, env.info.dup()); 419 return attribTree(node, localEnv, unknownTypeInfo); 420 } 421 422 public Type attribImportQualifier(JCImport tree, Env<AttrContext> env) { 423 // Attribute qualifying package or class. 424 JCFieldAccess s = (JCFieldAccess)tree.qualid; 425 return attribTree(s.selected, 426 env, 427 new ResultInfo(tree.staticImport ? TYP : (TYP | PCK), 428 Type.noType)); 429 } 430 431 public Env<AttrContext> attribExprToTree(JCTree expr, Env<AttrContext> env, JCTree tree) { 432 breakTree = tree; 433 JavaFileObject prev = log.useSource(env.toplevel.sourcefile); 434 try { 435 attribExpr(expr, env); 436 } catch (BreakAttr b) { 437 return b.env; 438 } catch (AssertionError ae) { 439 if (ae.getCause() instanceof BreakAttr) { 440 return ((BreakAttr)(ae.getCause())).env; 441 } else { 442 throw ae; 443 } 444 } finally { 445 breakTree = null; 446 log.useSource(prev); 447 } 448 return env; 449 } 450 451 public Env<AttrContext> attribStatToTree(JCTree stmt, Env<AttrContext> env, JCTree tree) { 452 breakTree = tree; 453 JavaFileObject prev = log.useSource(env.toplevel.sourcefile); 454 try { 455 attribStat(stmt, env); 456 } catch (BreakAttr b) { 457 return b.env; 458 } catch (AssertionError ae) { 459 if (ae.getCause() instanceof BreakAttr) { 460 return ((BreakAttr)(ae.getCause())).env; 461 } else { 462 throw ae; 463 } 464 } finally { 465 breakTree = null; 466 log.useSource(prev); 467 } 468 return env; 469 } 470 471 private JCTree breakTree = null; 472 473 private static class BreakAttr extends RuntimeException { 474 static final long serialVersionUID = -6924771130405446405L; 475 private Env<AttrContext> env; 476 private BreakAttr(Env<AttrContext> env) { 477 this.env = copyEnv(env); 478 } 479 480 private Env<AttrContext> copyEnv(Env<AttrContext> env) { 481 Env<AttrContext> newEnv = 482 env.dup(env.tree, env.info.dup(copyScope(env.info.scope))); 483 if (newEnv.outer != null) { 484 newEnv.outer = copyEnv(newEnv.outer); 485 } 486 return newEnv; 487 } 488 489 private Scope copyScope(Scope sc) { 490 Scope newScope = new Scope(sc.owner); 491 List<Symbol> elemsList = List.nil(); 492 while (sc != null) { 493 for (Scope.Entry e = sc.elems ; e != null ; e = e.sibling) { 494 elemsList = elemsList.prepend(e.sym); 495 } 496 sc = sc.next; 497 } 498 for (Symbol s : elemsList) { 499 newScope.enter(s); 500 } 501 return newScope; 502 } 503 } 504 505 class ResultInfo { 506 final int pkind; 507 final Type pt; 508 final CheckContext checkContext; 509 510 ResultInfo(int pkind, Type pt) { 511 this(pkind, pt, chk.basicHandler); 512 } 513 514 protected ResultInfo(int pkind, Type pt, CheckContext checkContext) { 515 this.pkind = pkind; 516 this.pt = pt; 517 this.checkContext = checkContext; 518 } 519 520 protected Type check(final DiagnosticPosition pos, final Type found) { 521 return chk.checkType(pos, found, pt, checkContext); 522 } 523 524 protected ResultInfo dup(Type newPt) { 525 return new ResultInfo(pkind, newPt, checkContext); 526 } 527 528 protected ResultInfo dup(CheckContext newContext) { 529 return new ResultInfo(pkind, pt, newContext); 530 } 531 } 532 533 class RecoveryInfo extends ResultInfo { 534 535 public RecoveryInfo(final DeferredAttr.DeferredAttrContext deferredAttrContext) { 536 super(Kinds.VAL, Type.recoveryType, new Check.NestedCheckContext(chk.basicHandler) { 537 @Override 538 public DeferredAttr.DeferredAttrContext deferredAttrContext() { 539 return deferredAttrContext; 540 } 541 @Override 542 public boolean compatible(Type found, Type req, Warner warn) { 543 return true; 544 } 545 @Override 546 public void report(DiagnosticPosition pos, JCDiagnostic details) { 547 chk.basicHandler.report(pos, details); 548 } 549 }); 550 } 551 552 @Override 553 protected Type check(DiagnosticPosition pos, Type found) { 554 return chk.checkNonVoid(pos, super.check(pos, found)); 555 } 556 } 557 558 final ResultInfo statInfo; 559 final ResultInfo varInfo; 560 final ResultInfo unknownExprInfo; 561 final ResultInfo unknownTypeInfo; 562 final ResultInfo recoveryInfo; 563 564 Type pt() { 565 return resultInfo.pt; 566 } 567 568 int pkind() { 569 return resultInfo.pkind; 570 } 571 572 /* ************************************************************************ 573 * Visitor methods 574 *************************************************************************/ 575 576 /** Visitor argument: the current environment. 577 */ 578 Env<AttrContext> env; 579 580 /** Visitor argument: the currently expected attribution result. 581 */ 582 ResultInfo resultInfo; 583 584 /** Visitor result: the computed type. 585 */ 586 Type result; 587 588 /** Visitor method: attribute a tree, catching any completion failure 589 * exceptions. Return the tree's type. 590 * 591 * @param tree The tree to be visited. 592 * @param env The environment visitor argument. 593 * @param resultInfo The result info visitor argument. 594 */ 595 Type attribTree(JCTree tree, Env<AttrContext> env, ResultInfo resultInfo) { 596 Env<AttrContext> prevEnv = this.env; 597 ResultInfo prevResult = this.resultInfo; 598 try { 599 this.env = env; 600 this.resultInfo = resultInfo; 601 tree.accept(this); 602 if (tree == breakTree && 603 resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) { 604 throw new BreakAttr(env); 605 } 606 return result; 607 } catch (CompletionFailure ex) { 608 tree.type = syms.errType; 609 return chk.completionError(tree.pos(), ex); 610 } finally { 611 this.env = prevEnv; 612 this.resultInfo = prevResult; 613 } 614 } 615 616 /** Derived visitor method: attribute an expression tree. 617 */ 618 public Type attribExpr(JCTree tree, Env<AttrContext> env, Type pt) { 619 return attribTree(tree, env, new ResultInfo(VAL, !pt.hasTag(ERROR) ? pt : Type.noType)); 620 } 621 622 /** Derived visitor method: attribute an expression tree with 623 * no constraints on the computed type. 624 */ 625 public Type attribExpr(JCTree tree, Env<AttrContext> env) { 626 return attribTree(tree, env, unknownExprInfo); 627 } 628 629 /** Derived visitor method: attribute a type tree. 630 */ 631 public Type attribType(JCTree tree, Env<AttrContext> env) { 632 Type result = attribType(tree, env, Type.noType); 633 return result; 634 } 635 636 /** Derived visitor method: attribute a type tree. 637 */ 638 Type attribType(JCTree tree, Env<AttrContext> env, Type pt) { 639 Type result = attribTree(tree, env, new ResultInfo(TYP, pt)); 640 return result; 641 } 642 643 /** Derived visitor method: attribute a statement or definition tree. 644 */ 645 public Type attribStat(JCTree tree, Env<AttrContext> env) { 646 return attribTree(tree, env, statInfo); 647 } 648 649 /** Attribute a list of expressions, returning a list of types. 650 */ 651 List<Type> attribExprs(List<JCExpression> trees, Env<AttrContext> env, Type pt) { 652 ListBuffer<Type> ts = new ListBuffer<Type>(); 653 for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail) 654 ts.append(attribExpr(l.head, env, pt)); 655 return ts.toList(); 656 } 657 658 /** Attribute a list of statements, returning nothing. 659 */ 660 <T extends JCTree> void attribStats(List<T> trees, Env<AttrContext> env) { 661 for (List<T> l = trees; l.nonEmpty(); l = l.tail) 662 attribStat(l.head, env); 663 } 664 665 /** Attribute the arguments in a method call, returning a list of types. 666 */ 667 List<Type> attribArgs(List<JCExpression> trees, Env<AttrContext> env) { 668 ListBuffer<Type> argtypes = new ListBuffer<Type>(); 669 for (JCExpression arg : trees) { 670 Type argtype = allowPoly && TreeInfo.isPoly(arg, env.tree) ? 671 deferredAttr.new DeferredType(arg, env) : 672 chk.checkNonVoid(arg, attribExpr(arg, env, Infer.anyPoly)); 673 argtypes.append(argtype); 674 } 675 return argtypes.toList(); 676 } 677 678 /** Attribute a type argument list, returning a list of types. 679 * Caller is responsible for calling checkRefTypes. 680 */ 681 List<Type> attribAnyTypes(List<JCExpression> trees, Env<AttrContext> env) { 682 ListBuffer<Type> argtypes = new ListBuffer<Type>(); 683 for (List<JCExpression> l = trees; l.nonEmpty(); l = l.tail) 684 argtypes.append(attribType(l.head, env)); 685 return argtypes.toList(); 686 } 687 688 /** Attribute a type argument list, returning a list of types. 689 * Check that all the types are references. 690 */ 691 List<Type> attribTypes(List<JCExpression> trees, Env<AttrContext> env) { 692 List<Type> types = attribAnyTypes(trees, env); 693 return chk.checkRefTypes(trees, types); 694 } 695 696 /** 697 * Attribute type variables (of generic classes or methods). 698 * Compound types are attributed later in attribBounds. 699 * @param typarams the type variables to enter 700 * @param env the current environment 701 */ 702 void attribTypeVariables(List<JCTypeParameter> typarams, Env<AttrContext> env) { 703 for (JCTypeParameter tvar : typarams) { 704 TypeVar a = (TypeVar)tvar.type; 705 a.tsym.flags_field |= UNATTRIBUTED; 706 a.bound = Type.noType; 707 if (!tvar.bounds.isEmpty()) { 708 List<Type> bounds = List.of(attribType(tvar.bounds.head, env)); 709 for (JCExpression bound : tvar.bounds.tail) 710 bounds = bounds.prepend(attribType(bound, env)); 711 types.setBounds(a, bounds.reverse()); 712 } else { 713 // if no bounds are given, assume a single bound of 714 // java.lang.Object. 715 types.setBounds(a, List.of(syms.objectType)); 716 } 717 a.tsym.flags_field &= ~UNATTRIBUTED; 718 } 719 for (JCTypeParameter tvar : typarams) { 720 chk.checkNonCyclic(tvar.pos(), (TypeVar)tvar.type); 721 } 722 } 723 724 /** 725 * Attribute the type references in a list of annotations. 726 */ 727 void attribAnnotationTypes(List<JCAnnotation> annotations, 728 Env<AttrContext> env) { 729 for (List<JCAnnotation> al = annotations; al.nonEmpty(); al = al.tail) { 730 JCAnnotation a = al.head; 731 attribType(a.annotationType, env); 732 } 733 } 734 735 /** 736 * Attribute a "lazy constant value". 737 * @param env The env for the const value 738 * @param initializer The initializer for the const value 739 * @param type The expected type, or null 740 * @see VarSymbol#setLazyConstValue 741 */ 742 public Object attribLazyConstantValue(Env<AttrContext> env, 743 JCTree.JCExpression initializer, 744 Type type) { 745 746 // in case no lint value has been set up for this env, scan up 747 // env stack looking for smallest enclosing env for which it is set. 748 Env<AttrContext> lintEnv = env; 749 while (lintEnv.info.lint == null) 750 lintEnv = lintEnv.next; 751 752 // Having found the enclosing lint value, we can initialize the lint value for this class 753 // ... but ... 754 // There's a problem with evaluating annotations in the right order, such that 755 // env.info.enclVar.attributes_field might not yet have been evaluated, and so might be 756 // null. In that case, calling augment will throw an NPE. To avoid this, for now we 757 // revert to the jdk 6 behavior and ignore the (unevaluated) attributes. 758 if (env.info.enclVar.annotations.pendingCompletion()) { 759 env.info.lint = lintEnv.info.lint; 760 } else { 761 env.info.lint = lintEnv.info.lint.augment(env.info.enclVar.annotations, 762 env.info.enclVar.flags()); 763 } 764 765 Lint prevLint = chk.setLint(env.info.lint); 766 JavaFileObject prevSource = log.useSource(env.toplevel.sourcefile); 767 768 try { 769 memberEnter.typeAnnotate(initializer, env, env.info.enclVar); 770 annotate.flush(); 771 Type itype = attribExpr(initializer, env, type); 772 if (itype.constValue() != null) 773 return coerce(itype, type).constValue(); 774 else 775 return null; 776 } finally { 777 env.info.lint = prevLint; 778 log.useSource(prevSource); 779 } 780 } 781 782 /** Attribute type reference in an `extends' or `implements' clause. 783 * Supertypes of anonymous inner classes are usually already attributed. 784 * 785 * @param tree The tree making up the type reference. 786 * @param env The environment current at the reference. 787 * @param classExpected true if only a class is expected here. 788 * @param interfaceExpected true if only an interface is expected here. 789 */ 790 Type attribBase(JCTree tree, 791 Env<AttrContext> env, 792 boolean classExpected, 793 boolean interfaceExpected, 794 boolean checkExtensible) { 795 Type t = tree.type != null ? 796 tree.type : 797 attribType(tree, env); 798 return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible); 799 } 800 Type checkBase(Type t, 801 JCTree tree, 802 Env<AttrContext> env, 803 boolean classExpected, 804 boolean interfaceExpected, 805 boolean checkExtensible) { 806 if (t.isErroneous()) 807 return t; 808 if (t.hasTag(TYPEVAR) && !classExpected && !interfaceExpected) { 809 // check that type variable is already visible 810 if (t.getUpperBound() == null) { 811 log.error(tree.pos(), "illegal.forward.ref"); 812 return types.createErrorType(t); 813 } 814 } else { 815 t = chk.checkClassType(tree.pos(), t, checkExtensible|!allowGenerics); 816 } 817 if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) { 818 log.error(tree.pos(), "intf.expected.here"); 819 // return errType is necessary since otherwise there might 820 // be undetected cycles which cause attribution to loop 821 return types.createErrorType(t); 822 } else if (checkExtensible && 823 classExpected && 824 (t.tsym.flags() & INTERFACE) != 0) { 825 log.error(tree.pos(), "no.intf.expected.here"); 826 return types.createErrorType(t); 827 } 828 if (checkExtensible && 829 ((t.tsym.flags() & FINAL) != 0)) { 830 log.error(tree.pos(), 831 "cant.inherit.from.final", t.tsym); 832 } 833 chk.checkNonCyclic(tree.pos(), t); 834 return t; 835 } 836 837 Type attribIdentAsEnumType(Env<AttrContext> env, JCIdent id) { 838 Assert.check((env.enclClass.sym.flags() & ENUM) != 0); 839 id.type = env.info.scope.owner.type; 840 id.sym = env.info.scope.owner; 841 return id.type; 842 } 843 844 public void visitClassDef(JCClassDecl tree) { 845 // Local classes have not been entered yet, so we need to do it now: 846 if ((env.info.scope.owner.kind & (VAR | MTH)) != 0) 847 enter.classEnter(tree, env); 848 849 ClassSymbol c = tree.sym; 850 if (c == null) { 851 // exit in case something drastic went wrong during enter. 852 result = null; 853 } else { 854 // make sure class has been completed: 855 c.complete(); 856 857 // If this class appears as an anonymous class 858 // in a superclass constructor call where 859 // no explicit outer instance is given, 860 // disable implicit outer instance from being passed. 861 // (This would be an illegal access to "this before super"). 862 if (env.info.isSelfCall && 863 env.tree.hasTag(NEWCLASS) && 864 ((JCNewClass) env.tree).encl == null) 865 { 866 c.flags_field |= NOOUTERTHIS; 867 } 868 attribClass(tree.pos(), c); 869 result = tree.type = c.type; 870 } 871 } 872 873 public void visitMethodDef(JCMethodDecl tree) { 874 MethodSymbol m = tree.sym; 875 boolean isDefaultMethod = (m.flags() & DEFAULT) != 0; 876 877 Lint lint = env.info.lint.augment(m.annotations, m.flags()); 878 Lint prevLint = chk.setLint(lint); 879 MethodSymbol prevMethod = chk.setMethod(m); 880 try { 881 deferredLintHandler.flush(tree.pos()); 882 chk.checkDeprecatedAnnotation(tree.pos(), m); 883 884 885 // Create a new environment with local scope 886 // for attributing the method. 887 Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env); 888 localEnv.info.lint = lint; 889 890 attribStats(tree.typarams, localEnv); 891 892 // If we override any other methods, check that we do so properly. 893 // JLS ??? 894 if (m.isStatic()) { 895 chk.checkHideClashes(tree.pos(), env.enclClass.type, m); 896 } else { 897 chk.checkOverrideClashes(tree.pos(), env.enclClass.type, m); 898 } 899 chk.checkOverride(tree, m); 900 901 if (isDefaultMethod && types.overridesObjectMethod(m.enclClass(), m)) { 902 log.error(tree, "default.overrides.object.member", m.name, Kinds.kindName(m.location()), m.location()); 903 } 904 905 // Enter all type parameters into the local method scope. 906 for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail) 907 localEnv.info.scope.enterIfAbsent(l.head.type.tsym); 908 909 ClassSymbol owner = env.enclClass.sym; 910 if ((owner.flags() & ANNOTATION) != 0 && 911 tree.params.nonEmpty()) 912 log.error(tree.params.head.pos(), 913 "intf.annotation.members.cant.have.params"); 914 915 // Attribute all value parameters. 916 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) { 917 attribStat(l.head, localEnv); 918 } 919 920 chk.checkVarargsMethodDecl(localEnv, tree); 921 922 // Check that type parameters are well-formed. 923 chk.validate(tree.typarams, localEnv); 924 925 // Check that result type is well-formed. 926 chk.validate(tree.restype, localEnv); 927 928 // Check that receiver type is well-formed. 929 if (tree.recvparam != null) { 930 // Use a new environment to check the receiver parameter. 931 // Otherwise I get "might not have been initialized" errors. 932 // Is there a better way? 933 Env<AttrContext> newEnv = memberEnter.methodEnv(tree, env); 934 attribType(tree.recvparam, newEnv); 935 chk.validate(tree.recvparam, newEnv); 936 if (!(tree.recvparam.type == m.owner.type || types.isSameType(tree.recvparam.type, m.owner.type))) { 937 // The == covers the common non-generic case, but for generic classes we need isSameType; 938 // note that equals didn't work. 939 log.error(tree.recvparam.pos(), "incorrect.receiver.type"); 940 } 941 } 942 943 // annotation method checks 944 if ((owner.flags() & ANNOTATION) != 0) { 945 // annotation method cannot have throws clause 946 if (tree.thrown.nonEmpty()) { 947 log.error(tree.thrown.head.pos(), 948 "throws.not.allowed.in.intf.annotation"); 949 } 950 // annotation method cannot declare type-parameters 951 if (tree.typarams.nonEmpty()) { 952 log.error(tree.typarams.head.pos(), 953 "intf.annotation.members.cant.have.type.params"); 954 } 955 // validate annotation method's return type (could be an annotation type) 956 chk.validateAnnotationType(tree.restype); 957 // ensure that annotation method does not clash with members of Object/Annotation 958 chk.validateAnnotationMethod(tree.pos(), m); 959 960 if (tree.defaultValue != null) { 961 // if default value is an annotation, check it is a well-formed 962 // annotation value (e.g. no duplicate values, no missing values, etc.) 963 chk.validateAnnotationTree(tree.defaultValue); 964 } 965 } 966 967 for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail) 968 chk.checkType(l.head.pos(), l.head.type, syms.throwableType); 969 970 if (tree.body == null) { 971 // Empty bodies are only allowed for 972 // abstract, native, or interface methods, or for methods 973 // in a retrofit signature class. 974 if (isDefaultMethod || (tree.sym.flags() & (ABSTRACT | NATIVE)) == 0 && 975 !relax) 976 log.error(tree.pos(), "missing.meth.body.or.decl.abstract"); 977 if (tree.defaultValue != null) { 978 if ((owner.flags() & ANNOTATION) == 0) 979 log.error(tree.pos(), 980 "default.allowed.in.intf.annotation.member"); 981 } 982 } else if ((tree.sym.flags() & ABSTRACT) != 0 && !isDefaultMethod) { 983 if ((owner.flags() & INTERFACE) != 0) { 984 log.error(tree.body.pos(), "intf.meth.cant.have.body"); 985 } else { 986 log.error(tree.pos(), "abstract.meth.cant.have.body"); 987 } 988 } else if ((tree.mods.flags & NATIVE) != 0) { 989 log.error(tree.pos(), "native.meth.cant.have.body"); 990 } else { 991 // Add an implicit super() call unless an explicit call to 992 // super(...) or this(...) is given 993 // or we are compiling class java.lang.Object. 994 if (tree.name == names.init && owner.type != syms.objectType) { 995 JCBlock body = tree.body; 996 if (body.stats.isEmpty() || 997 !TreeInfo.isSelfCall(body.stats.head)) { 998 body.stats = body.stats. 999 prepend(memberEnter.SuperCall(make.at(body.pos), 1000 List.<Type>nil(), 1001 List.<JCVariableDecl>nil(), 1002 false)); 1003 } else if ((env.enclClass.sym.flags() & ENUM) != 0 && 1004 (tree.mods.flags & GENERATEDCONSTR) == 0 && 1005 TreeInfo.isSuperCall(body.stats.head)) { 1006 // enum constructors are not allowed to call super 1007 // directly, so make sure there aren't any super calls 1008 // in enum constructors, except in the compiler 1009 // generated one. 1010 log.error(tree.body.stats.head.pos(), 1011 "call.to.super.not.allowed.in.enum.ctor", 1012 env.enclClass.sym); 1013 } 1014 } 1015 1016 // Attribute all type annotations in the body 1017 memberEnter.typeAnnotate(tree.body, localEnv, m); 1018 annotate.flush(); 1019 1020 // Attribute method body. 1021 attribStat(tree.body, localEnv); 1022 } 1023 1024 localEnv.info.scope.leave(); 1025 result = tree.type = m.type; 1026 chk.validateAnnotations(tree.mods.annotations, m); 1027 } 1028 finally { 1029 chk.setLint(prevLint); 1030 chk.setMethod(prevMethod); 1031 } 1032 } 1033 1034 public void visitVarDef(JCVariableDecl tree) { 1035 // Local variables have not been entered yet, so we need to do it now: 1036 if (env.info.scope.owner.kind == MTH) { 1037 if (tree.sym != null) { 1038 // parameters have already been entered 1039 env.info.scope.enter(tree.sym); 1040 } else { 1041 memberEnter.memberEnter(tree, env); 1042 annotate.flush(); 1043 } 1044 } else { 1045 if (tree.init != null) { 1046 // Field initializer expression need to be entered. 1047 memberEnter.typeAnnotate(tree.init, env, tree.sym); 1048 annotate.flush(); 1049 } 1050 } 1051 1052 VarSymbol v = tree.sym; 1053 Lint lint = env.info.lint.augment(v.annotations, v.flags()); 1054 Lint prevLint = chk.setLint(lint); 1055 1056 // Check that the variable's declared type is well-formed. 1057 chk.validate(tree.vartype, env); 1058 deferredLintHandler.flush(tree.pos()); 1059 1060 try { 1061 chk.checkDeprecatedAnnotation(tree.pos(), v); 1062 1063 if (tree.init != null) { 1064 if ((v.flags_field & FINAL) != 0 && 1065 !tree.init.hasTag(NEWCLASS) && 1066 !tree.init.hasTag(LAMBDA) && 1067 !tree.init.hasTag(REFERENCE)) { 1068 // In this case, `v' is final. Ensure that it's initializer is 1069 // evaluated. 1070 v.getConstValue(); // ensure initializer is evaluated 1071 } else { 1072 // Attribute initializer in a new environment 1073 // with the declared variable as owner. 1074 // Check that initializer conforms to variable's declared type. 1075 Env<AttrContext> initEnv = memberEnter.initEnv(tree, env); 1076 initEnv.info.lint = lint; 1077 // In order to catch self-references, we set the variable's 1078 // declaration position to maximal possible value, effectively 1079 // marking the variable as undefined. 1080 initEnv.info.enclVar = v; 1081 attribExpr(tree.init, initEnv, v.type); 1082 } 1083 } 1084 result = tree.type = v.type; 1085 chk.validateAnnotations(tree.mods.annotations, v); 1086 } 1087 finally { 1088 chk.setLint(prevLint); 1089 } 1090 } 1091 1092 public void visitSkip(JCSkip tree) { 1093 result = null; 1094 } 1095 1096 public void visitBlock(JCBlock tree) { 1097 if (env.info.scope.owner.kind == TYP) { 1098 // Block is a static or instance initializer; 1099 // let the owner of the environment be a freshly 1100 // created BLOCK-method. 1101 Env<AttrContext> localEnv = 1102 env.dup(tree, env.info.dup(env.info.scope.dupUnshared())); 1103 localEnv.info.scope.owner = 1104 new MethodSymbol(tree.flags | BLOCK | 1105 env.info.scope.owner.flags() & STRICTFP, names.empty, null, 1106 env.info.scope.owner); 1107 if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++; 1108 1109 // Attribute all type annotations in the block 1110 memberEnter.typeAnnotate(tree, localEnv, localEnv.info.scope.owner); 1111 annotate.flush(); 1112 1113 attribStats(tree.stats, localEnv); 1114 } else { 1115 // Create a new local environment with a local scope. 1116 Env<AttrContext> localEnv = 1117 env.dup(tree, env.info.dup(env.info.scope.dup())); 1118 try { 1119 attribStats(tree.stats, localEnv); 1120 } finally { 1121 localEnv.info.scope.leave(); 1122 } 1123 } 1124 result = null; 1125 } 1126 1127 public void visitDoLoop(JCDoWhileLoop tree) { 1128 attribStat(tree.body, env.dup(tree)); 1129 attribExpr(tree.cond, env, syms.booleanType); 1130 result = null; 1131 } 1132 1133 public void visitWhileLoop(JCWhileLoop tree) { 1134 attribExpr(tree.cond, env, syms.booleanType); 1135 attribStat(tree.body, env.dup(tree)); 1136 result = null; 1137 } 1138 1139 public void visitForLoop(JCForLoop tree) { 1140 Env<AttrContext> loopEnv = 1141 env.dup(env.tree, env.info.dup(env.info.scope.dup())); 1142 try { 1143 attribStats(tree.init, loopEnv); 1144 if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType); 1145 loopEnv.tree = tree; // before, we were not in loop! 1146 attribStats(tree.step, loopEnv); 1147 attribStat(tree.body, loopEnv); 1148 result = null; 1149 } 1150 finally { 1151 loopEnv.info.scope.leave(); 1152 } 1153 } 1154 1155 public void visitForeachLoop(JCEnhancedForLoop tree) { 1156 Env<AttrContext> loopEnv = 1157 env.dup(env.tree, env.info.dup(env.info.scope.dup())); 1158 try { 1159 attribStat(tree.var, loopEnv); 1160 Type exprType = types.upperBound(attribExpr(tree.expr, loopEnv)); 1161 chk.checkNonVoid(tree.pos(), exprType); 1162 Type elemtype = types.elemtype(exprType); // perhaps expr is an array? 1163 if (elemtype == null) { 1164 // or perhaps expr implements Iterable<T>? 1165 Type base = types.asSuper(exprType, syms.iterableType.tsym); 1166 if (base == null) { 1167 log.error(tree.expr.pos(), 1168 "foreach.not.applicable.to.type", 1169 exprType, 1170 diags.fragment("type.req.array.or.iterable")); 1171 elemtype = types.createErrorType(exprType); 1172 } else { 1173 List<Type> iterableParams = base.allparams(); 1174 elemtype = iterableParams.isEmpty() 1175 ? syms.objectType 1176 : types.upperBound(iterableParams.head); 1177 } 1178 } 1179 chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type); 1180 loopEnv.tree = tree; // before, we were not in loop! 1181 attribStat(tree.body, loopEnv); 1182 result = null; 1183 } 1184 finally { 1185 loopEnv.info.scope.leave(); 1186 } 1187 } 1188 1189 public void visitLabelled(JCLabeledStatement tree) { 1190 // Check that label is not used in an enclosing statement 1191 Env<AttrContext> env1 = env; 1192 while (env1 != null && !env1.tree.hasTag(CLASSDEF)) { 1193 if (env1.tree.hasTag(LABELLED) && 1194 ((JCLabeledStatement) env1.tree).label == tree.label) { 1195 log.error(tree.pos(), "label.already.in.use", 1196 tree.label); 1197 break; 1198 } 1199 env1 = env1.next; 1200 } 1201 1202 attribStat(tree.body, env.dup(tree)); 1203 result = null; 1204 } 1205 1206 public void visitSwitch(JCSwitch tree) { 1207 Type seltype = attribExpr(tree.selector, env); 1208 1209 Env<AttrContext> switchEnv = 1210 env.dup(tree, env.info.dup(env.info.scope.dup())); 1211 1212 try { 1213 1214 boolean enumSwitch = 1215 allowEnums && 1216 (seltype.tsym.flags() & Flags.ENUM) != 0; 1217 boolean stringSwitch = false; 1218 if (types.isSameType(seltype, syms.stringType)) { 1219 if (allowStringsInSwitch) { 1220 stringSwitch = true; 1221 } else { 1222 log.error(tree.selector.pos(), "string.switch.not.supported.in.source", sourceName); 1223 } 1224 } 1225 if (!enumSwitch && !stringSwitch) 1226 seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType); 1227 1228 // Attribute all cases and 1229 // check that there are no duplicate case labels or default clauses. 1230 Set<Object> labels = new HashSet<Object>(); // The set of case labels. 1231 boolean hasDefault = false; // Is there a default label? 1232 for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) { 1233 JCCase c = l.head; 1234 Env<AttrContext> caseEnv = 1235 switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup())); 1236 try { 1237 if (c.pat != null) { 1238 if (enumSwitch) { 1239 Symbol sym = enumConstant(c.pat, seltype); 1240 if (sym == null) { 1241 log.error(c.pat.pos(), "enum.label.must.be.unqualified.enum"); 1242 } else if (!labels.add(sym)) { 1243 log.error(c.pos(), "duplicate.case.label"); 1244 } 1245 } else { 1246 Type pattype = attribExpr(c.pat, switchEnv, seltype); 1247 if (!pattype.hasTag(ERROR)) { 1248 if (pattype.constValue() == null) { 1249 log.error(c.pat.pos(), 1250 (stringSwitch ? "string.const.req" : "const.expr.req")); 1251 } else if (labels.contains(pattype.constValue())) { 1252 log.error(c.pos(), "duplicate.case.label"); 1253 } else { 1254 labels.add(pattype.constValue()); 1255 } 1256 } 1257 } 1258 } else if (hasDefault) { 1259 log.error(c.pos(), "duplicate.default.label"); 1260 } else { 1261 hasDefault = true; 1262 } 1263 attribStats(c.stats, caseEnv); 1264 } finally { 1265 caseEnv.info.scope.leave(); 1266 addVars(c.stats, switchEnv.info.scope); 1267 } 1268 } 1269 1270 result = null; 1271 } 1272 finally { 1273 switchEnv.info.scope.leave(); 1274 } 1275 } 1276 // where 1277 /** Add any variables defined in stats to the switch scope. */ 1278 private static void addVars(List<JCStatement> stats, Scope switchScope) { 1279 for (;stats.nonEmpty(); stats = stats.tail) { 1280 JCTree stat = stats.head; 1281 if (stat.hasTag(VARDEF)) 1282 switchScope.enter(((JCVariableDecl) stat).sym); 1283 } 1284 } 1285 // where 1286 /** Return the selected enumeration constant symbol, or null. */ 1287 private Symbol enumConstant(JCTree tree, Type enumType) { 1288 if (!tree.hasTag(IDENT)) { 1289 log.error(tree.pos(), "enum.label.must.be.unqualified.enum"); 1290 return syms.errSymbol; 1291 } 1292 JCIdent ident = (JCIdent)tree; 1293 Name name = ident.name; 1294 for (Scope.Entry e = enumType.tsym.members().lookup(name); 1295 e.scope != null; e = e.next()) { 1296 if (e.sym.kind == VAR) { 1297 Symbol s = ident.sym = e.sym; 1298 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated 1299 ident.type = s.type; 1300 return ((s.flags_field & Flags.ENUM) == 0) 1301 ? null : s; 1302 } 1303 } 1304 return null; 1305 } 1306 1307 public void visitSynchronized(JCSynchronized tree) { 1308 chk.checkRefType(tree.pos(), attribExpr(tree.lock, env)); 1309 attribStat(tree.body, env); 1310 result = null; 1311 } 1312 1313 public void visitTry(JCTry tree) { 1314 // Create a new local environment with a local 1315 Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup())); 1316 try { 1317 boolean isTryWithResource = tree.resources.nonEmpty(); 1318 // Create a nested environment for attributing the try block if needed 1319 Env<AttrContext> tryEnv = isTryWithResource ? 1320 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) : 1321 localEnv; 1322 try { 1323 // Attribute resource declarations 1324 for (JCTree resource : tree.resources) { 1325 CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) { 1326 @Override 1327 public void report(DiagnosticPosition pos, JCDiagnostic details) { 1328 chk.basicHandler.report(pos, diags.fragment("try.not.applicable.to.type", details)); 1329 } 1330 }; 1331 ResultInfo twrResult = new ResultInfo(VAL, syms.autoCloseableType, twrContext); 1332 if (resource.hasTag(VARDEF)) { 1333 attribStat(resource, tryEnv); 1334 twrResult.check(resource, resource.type); 1335 1336 //check that resource type cannot throw InterruptedException 1337 checkAutoCloseable(resource.pos(), localEnv, resource.type); 1338 1339 VarSymbol var = (VarSymbol)TreeInfo.symbolFor(resource); 1340 var.setData(ElementKind.RESOURCE_VARIABLE); 1341 } else { 1342 attribTree(resource, tryEnv, twrResult); 1343 } 1344 } 1345 // Attribute body 1346 attribStat(tree.body, tryEnv); 1347 } finally { 1348 if (isTryWithResource) 1349 tryEnv.info.scope.leave(); 1350 } 1351 1352 // Attribute catch clauses 1353 for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) { 1354 JCCatch c = l.head; 1355 Env<AttrContext> catchEnv = 1356 localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup())); 1357 try { 1358 Type ctype = attribStat(c.param, catchEnv); 1359 if (TreeInfo.isMultiCatch(c)) { 1360 //multi-catch parameter is implicitly marked as final 1361 c.param.sym.flags_field |= FINAL | UNION; 1362 } 1363 if (c.param.sym.kind == Kinds.VAR) { 1364 c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER); 1365 } 1366 chk.checkType(c.param.vartype.pos(), 1367 chk.checkClassType(c.param.vartype.pos(), ctype), 1368 syms.throwableType); 1369 attribStat(c.body, catchEnv); 1370 } finally { 1371 catchEnv.info.scope.leave(); 1372 } 1373 } 1374 1375 // Attribute finalizer 1376 if (tree.finalizer != null) attribStat(tree.finalizer, localEnv); 1377 result = null; 1378 } 1379 finally { 1380 localEnv.info.scope.leave(); 1381 } 1382 } 1383 1384 void checkAutoCloseable(DiagnosticPosition pos, Env<AttrContext> env, Type resource) { 1385 if (!resource.isErroneous() && 1386 types.asSuper(resource, syms.autoCloseableType.tsym) != null && 1387 !types.isSameType(resource, syms.autoCloseableType)) { // Don't emit warning for AutoCloseable itself 1388 Symbol close = syms.noSymbol; 1389 Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log); 1390 try { 1391 close = rs.resolveQualifiedMethod(pos, 1392 env, 1393 resource, 1394 names.close, 1395 List.<Type>nil(), 1396 List.<Type>nil()); 1397 } 1398 finally { 1399 log.popDiagnosticHandler(discardHandler); 1400 } 1401 if (close.kind == MTH && 1402 close.overrides(syms.autoCloseableClose, resource.tsym, types, true) && 1403 chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes()) && 1404 env.info.lint.isEnabled(LintCategory.TRY)) { 1405 log.warning(LintCategory.TRY, pos, "try.resource.throws.interrupted.exc", resource); 1406 } 1407 } 1408 } 1409 1410 public void visitConditional(JCConditional tree) { 1411 Type condtype = attribExpr(tree.cond, env, syms.booleanType); 1412 1413 tree.polyKind = (!allowPoly || 1414 pt().hasTag(NONE) && pt() != Type.recoveryType || 1415 isBooleanOrNumeric(env, tree)) ? 1416 PolyKind.STANDALONE : PolyKind.POLY; 1417 1418 if (tree.polyKind == PolyKind.POLY && resultInfo.pt.hasTag(VOID)) { 1419 //cannot get here (i.e. it means we are returning from void method - which is already an error) 1420 resultInfo.checkContext.report(tree, diags.fragment("conditional.target.cant.be.void")); 1421 result = tree.type = types.createErrorType(resultInfo.pt); 1422 return; 1423 } 1424 1425 ResultInfo condInfo = tree.polyKind == PolyKind.STANDALONE ? 1426 unknownExprInfo : 1427 resultInfo.dup(new Check.NestedCheckContext(resultInfo.checkContext) { 1428 //this will use enclosing check context to check compatibility of 1429 //subexpression against target type; if we are in a method check context, 1430 //depending on whether boxing is allowed, we could have incompatibilities 1431 @Override 1432 public void report(DiagnosticPosition pos, JCDiagnostic details) { 1433 enclosingContext.report(pos, diags.fragment("incompatible.type.in.conditional", details)); 1434 } 1435 }); 1436 1437 Type truetype = attribTree(tree.truepart, env, condInfo); 1438 Type falsetype = attribTree(tree.falsepart, env, condInfo); 1439 1440 Type owntype = (tree.polyKind == PolyKind.STANDALONE) ? condType(tree, truetype, falsetype) : pt(); 1441 if (condtype.constValue() != null && 1442 truetype.constValue() != null && 1443 falsetype.constValue() != null && 1444 !owntype.hasTag(NONE)) { 1445 //constant folding 1446 owntype = cfolder.coerce(condtype.isTrue() ? truetype : falsetype, owntype); 1447 } 1448 result = check(tree, owntype, VAL, resultInfo); 1449 } 1450 //where 1451 private boolean isBooleanOrNumeric(Env<AttrContext> env, JCExpression tree) { 1452 switch (tree.getTag()) { 1453 case LITERAL: return ((JCLiteral)tree).typetag.isSubRangeOf(DOUBLE) || 1454 ((JCLiteral)tree).typetag == BOOLEAN || 1455 ((JCLiteral)tree).typetag == BOT; 1456 case LAMBDA: case REFERENCE: return false; 1457 case PARENS: return isBooleanOrNumeric(env, ((JCParens)tree).expr); 1458 case CONDEXPR: 1459 JCConditional condTree = (JCConditional)tree; 1460 return isBooleanOrNumeric(env, condTree.truepart) && 1461 isBooleanOrNumeric(env, condTree.falsepart); 1462 case APPLY: 1463 JCMethodInvocation speculativeMethodTree = 1464 (JCMethodInvocation)deferredAttr.attribSpeculative(tree, env, unknownExprInfo); 1465 Type owntype = TreeInfo.symbol(speculativeMethodTree.meth).type.getReturnType(); 1466 return types.unboxedTypeOrType(owntype).isPrimitive(); 1467 case NEWCLASS: 1468 JCExpression className = 1469 removeClassParams.translate(((JCNewClass)tree).clazz); 1470 JCExpression speculativeNewClassTree = 1471 (JCExpression)deferredAttr.attribSpeculative(className, env, unknownTypeInfo); 1472 return types.unboxedTypeOrType(speculativeNewClassTree.type).isPrimitive(); 1473 default: 1474 Type speculativeType = deferredAttr.attribSpeculative(tree, env, unknownExprInfo).type; 1475 speculativeType = types.unboxedTypeOrType(speculativeType); 1476 return speculativeType.isPrimitive(); 1477 } 1478 } 1479 //where 1480 TreeTranslator removeClassParams = new TreeTranslator() { 1481 @Override 1482 public void visitTypeApply(JCTypeApply tree) { 1483 result = translate(tree.clazz); 1484 } 1485 }; 1486 1487 /** Compute the type of a conditional expression, after 1488 * checking that it exists. See JLS 15.25. Does not take into 1489 * account the special case where condition and both arms 1490 * are constants. 1491 * 1492 * @param pos The source position to be used for error 1493 * diagnostics. 1494 * @param thentype The type of the expression's then-part. 1495 * @param elsetype The type of the expression's else-part. 1496 */ 1497 private Type condType(DiagnosticPosition pos, 1498 Type thentype, Type elsetype) { 1499 // If same type, that is the result 1500 if (types.isSameType(thentype, elsetype)) 1501 return thentype.baseType(); 1502 1503 Type thenUnboxed = (!allowBoxing || thentype.isPrimitive()) 1504 ? thentype : types.unboxedType(thentype); 1505 Type elseUnboxed = (!allowBoxing || elsetype.isPrimitive()) 1506 ? elsetype : types.unboxedType(elsetype); 1507 1508 // Otherwise, if both arms can be converted to a numeric 1509 // type, return the least numeric type that fits both arms 1510 // (i.e. return larger of the two, or return int if one 1511 // arm is short, the other is char). 1512 if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) { 1513 // If one arm has an integer subrange type (i.e., byte, 1514 // short, or char), and the other is an integer constant 1515 // that fits into the subrange, return the subrange type. 1516 if (thenUnboxed.getTag().isStrictSubRangeOf(INT) && elseUnboxed.hasTag(INT) && 1517 types.isAssignable(elseUnboxed, thenUnboxed)) 1518 return thenUnboxed.baseType(); 1519 if (elseUnboxed.getTag().isStrictSubRangeOf(INT) && thenUnboxed.hasTag(INT) && 1520 types.isAssignable(thenUnboxed, elseUnboxed)) 1521 return elseUnboxed.baseType(); 1522 1523 for (TypeTag tag : TypeTag.values()) { 1524 if (tag.ordinal() >= TypeTag.getTypeTagCount()) break; 1525 Type candidate = syms.typeOfTag[tag.ordinal()]; 1526 if (candidate != null && 1527 candidate.isPrimitive() && 1528 types.isSubtype(thenUnboxed, candidate) && 1529 types.isSubtype(elseUnboxed, candidate)) 1530 return candidate; 1531 } 1532 } 1533 1534 // Those were all the cases that could result in a primitive 1535 if (allowBoxing) { 1536 if (thentype.isPrimitive()) 1537 thentype = types.boxedClass(thentype).type; 1538 if (elsetype.isPrimitive()) 1539 elsetype = types.boxedClass(elsetype).type; 1540 } 1541 1542 if (types.isSubtype(thentype, elsetype)) 1543 return elsetype.baseType(); 1544 if (types.isSubtype(elsetype, thentype)) 1545 return thentype.baseType(); 1546 1547 if (!allowBoxing || thentype.hasTag(VOID) || elsetype.hasTag(VOID)) { 1548 log.error(pos, "neither.conditional.subtype", 1549 thentype, elsetype); 1550 return thentype.baseType(); 1551 } 1552 1553 // both are known to be reference types. The result is 1554 // lub(thentype,elsetype). This cannot fail, as it will 1555 // always be possible to infer "Object" if nothing better. 1556 return types.lub(thentype.baseType(), elsetype.baseType()); 1557 } 1558 1559 public void visitIf(JCIf tree) { 1560 attribExpr(tree.cond, env, syms.booleanType); 1561 attribStat(tree.thenpart, env); 1562 if (tree.elsepart != null) 1563 attribStat(tree.elsepart, env); 1564 chk.checkEmptyIf(tree); 1565 result = null; 1566 } 1567 1568 public void visitExec(JCExpressionStatement tree) { 1569 //a fresh environment is required for 292 inference to work properly --- 1570 //see Infer.instantiatePolymorphicSignatureInstance() 1571 Env<AttrContext> localEnv = env.dup(tree); 1572 attribExpr(tree.expr, localEnv); 1573 result = null; 1574 } 1575 1576 public void visitBreak(JCBreak tree) { 1577 tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env); 1578 result = null; 1579 } 1580 1581 public void visitContinue(JCContinue tree) { 1582 tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env); 1583 result = null; 1584 } 1585 //where 1586 /** Return the target of a break or continue statement, if it exists, 1587 * report an error if not. 1588 * Note: The target of a labelled break or continue is the 1589 * (non-labelled) statement tree referred to by the label, 1590 * not the tree representing the labelled statement itself. 1591 * 1592 * @param pos The position to be used for error diagnostics 1593 * @param tag The tag of the jump statement. This is either 1594 * Tree.BREAK or Tree.CONTINUE. 1595 * @param label The label of the jump statement, or null if no 1596 * label is given. 1597 * @param env The environment current at the jump statement. 1598 */ 1599 private JCTree findJumpTarget(DiagnosticPosition pos, 1600 JCTree.Tag tag, 1601 Name label, 1602 Env<AttrContext> env) { 1603 // Search environments outwards from the point of jump. 1604 Env<AttrContext> env1 = env; 1605 LOOP: 1606 while (env1 != null) { 1607 switch (env1.tree.getTag()) { 1608 case LABELLED: 1609 JCLabeledStatement labelled = (JCLabeledStatement)env1.tree; 1610 if (label == labelled.label) { 1611 // If jump is a continue, check that target is a loop. 1612 if (tag == CONTINUE) { 1613 if (!labelled.body.hasTag(DOLOOP) && 1614 !labelled.body.hasTag(WHILELOOP) && 1615 !labelled.body.hasTag(FORLOOP) && 1616 !labelled.body.hasTag(FOREACHLOOP)) 1617 log.error(pos, "not.loop.label", label); 1618 // Found labelled statement target, now go inwards 1619 // to next non-labelled tree. 1620 return TreeInfo.referencedStatement(labelled); 1621 } else { 1622 return labelled; 1623 } 1624 } 1625 break; 1626 case DOLOOP: 1627 case WHILELOOP: 1628 case FORLOOP: 1629 case FOREACHLOOP: 1630 if (label == null) return env1.tree; 1631 break; 1632 case SWITCH: 1633 if (label == null && tag == BREAK) return env1.tree; 1634 break; 1635 case LAMBDA: 1636 case METHODDEF: 1637 case CLASSDEF: 1638 break LOOP; 1639 default: 1640 } 1641 env1 = env1.next; 1642 } 1643 if (label != null) 1644 log.error(pos, "undef.label", label); 1645 else if (tag == CONTINUE) 1646 log.error(pos, "cont.outside.loop"); 1647 else 1648 log.error(pos, "break.outside.switch.loop"); 1649 return null; 1650 } 1651 1652 public void visitReturn(JCReturn tree) { 1653 // Check that there is an enclosing method which is 1654 // nested within than the enclosing class. 1655 if (env.info.returnResult == null) { 1656 log.error(tree.pos(), "ret.outside.meth"); 1657 } else { 1658 // Attribute return expression, if it exists, and check that 1659 // it conforms to result type of enclosing method. 1660 if (tree.expr != null) { 1661 if (env.info.returnResult.pt.hasTag(VOID)) { 1662 env.info.returnResult.checkContext.report(tree.expr.pos(), 1663 diags.fragment("unexpected.ret.val")); 1664 } 1665 attribTree(tree.expr, env, env.info.returnResult); 1666 } else if (!env.info.returnResult.pt.hasTag(VOID)) { 1667 env.info.returnResult.checkContext.report(tree.pos(), 1668 diags.fragment("missing.ret.val")); 1669 } 1670 } 1671 result = null; 1672 } 1673 1674 public void visitThrow(JCThrow tree) { 1675 Type owntype = attribExpr(tree.expr, env, allowPoly ? Type.noType : syms.throwableType); 1676 if (allowPoly) { 1677 chk.checkType(tree, owntype, syms.throwableType); 1678 } 1679 result = null; 1680 } 1681 1682 public void visitAssert(JCAssert tree) { 1683 attribExpr(tree.cond, env, syms.booleanType); 1684 if (tree.detail != null) { 1685 chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env)); 1686 } 1687 result = null; 1688 } 1689 1690 /** Visitor method for method invocations. 1691 * NOTE: The method part of an application will have in its type field 1692 * the return type of the method, not the method's type itself! 1693 */ 1694 public void visitApply(JCMethodInvocation tree) { 1695 // The local environment of a method application is 1696 // a new environment nested in the current one. 1697 Env<AttrContext> localEnv = env.dup(tree, env.info.dup()); 1698 1699 // The types of the actual method arguments. 1700 List<Type> argtypes; 1701 1702 // The types of the actual method type arguments. 1703 List<Type> typeargtypes = null; 1704 1705 Name methName = TreeInfo.name(tree.meth); 1706 1707 boolean isConstructorCall = 1708 methName == names._this || methName == names._super; 1709 1710 if (isConstructorCall) { 1711 // We are seeing a ...this(...) or ...super(...) call. 1712 // Check that this is the first statement in a constructor. 1713 if (checkFirstConstructorStat(tree, env)) { 1714 1715 // Record the fact 1716 // that this is a constructor call (using isSelfCall). 1717 localEnv.info.isSelfCall = true; 1718 1719 // Attribute arguments, yielding list of argument types. 1720 argtypes = attribArgs(tree.args, localEnv); 1721 typeargtypes = attribTypes(tree.typeargs, localEnv); 1722 1723 // Variable `site' points to the class in which the called 1724 // constructor is defined. 1725 Type site = env.enclClass.sym.type; 1726 if (methName == names._super) { 1727 if (site == syms.objectType) { 1728 log.error(tree.meth.pos(), "no.superclass", site); 1729 site = types.createErrorType(syms.objectType); 1730 } else { 1731 site = types.supertype(site); 1732 } 1733 } 1734 1735 if (site.hasTag(CLASS)) { 1736 Type encl = site.getEnclosingType(); 1737 while (encl != null && encl.hasTag(TYPEVAR)) 1738 encl = encl.getUpperBound(); 1739 if (encl.hasTag(CLASS)) { 1740 // we are calling a nested class 1741 1742 if (tree.meth.hasTag(SELECT)) { 1743 JCTree qualifier = ((JCFieldAccess) tree.meth).selected; 1744 1745 // We are seeing a prefixed call, of the form 1746 // <expr>.super(...). 1747 // Check that the prefix expression conforms 1748 // to the outer instance type of the class. 1749 chk.checkRefType(qualifier.pos(), 1750 attribExpr(qualifier, localEnv, 1751 encl)); 1752 } else if (methName == names._super) { 1753 // qualifier omitted; check for existence 1754 // of an appropriate implicit qualifier. 1755 rs.resolveImplicitThis(tree.meth.pos(), 1756 localEnv, site, true); 1757 } 1758 } else if (tree.meth.hasTag(SELECT)) { 1759 log.error(tree.meth.pos(), "illegal.qual.not.icls", 1760 site.tsym); 1761 } 1762 1763 // if we're calling a java.lang.Enum constructor, 1764 // prefix the implicit String and int parameters 1765 if (site.tsym == syms.enumSym && allowEnums) 1766 argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType); 1767 1768 // Resolve the called constructor under the assumption 1769 // that we are referring to a superclass instance of the 1770 // current instance (JLS ???). 1771 boolean selectSuperPrev = localEnv.info.selectSuper; 1772 localEnv.info.selectSuper = true; 1773 localEnv.info.pendingResolutionPhase = null; 1774 Symbol sym = rs.resolveConstructor( 1775 tree.meth.pos(), localEnv, site, argtypes, typeargtypes); 1776 localEnv.info.selectSuper = selectSuperPrev; 1777 1778 // Set method symbol to resolved constructor... 1779 TreeInfo.setSymbol(tree.meth, sym); 1780 1781 // ...and check that it is legal in the current context. 1782 // (this will also set the tree's type) 1783 Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes); 1784 checkId(tree.meth, site, sym, localEnv, new ResultInfo(MTH, mpt)); 1785 } 1786 // Otherwise, `site' is an error type and we do nothing 1787 } 1788 result = tree.type = syms.voidType; 1789 } else { 1790 // Otherwise, we are seeing a regular method call. 1791 // Attribute the arguments, yielding list of argument types, ... 1792 argtypes = attribArgs(tree.args, localEnv); 1793 typeargtypes = attribAnyTypes(tree.typeargs, localEnv); 1794 1795 // ... and attribute the method using as a prototype a methodtype 1796 // whose formal argument types is exactly the list of actual 1797 // arguments (this will also set the method symbol). 1798 Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes); 1799 localEnv.info.pendingResolutionPhase = null; 1800 Type mtype = attribTree(tree.meth, localEnv, new ResultInfo(VAL, mpt, resultInfo.checkContext)); 1801 1802 // Compute the result type. 1803 Type restype = mtype.getReturnType(); 1804 if (restype.hasTag(WILDCARD)) 1805 throw new AssertionError(mtype); 1806 1807 Type qualifier = (tree.meth.hasTag(SELECT)) 1808 ? ((JCFieldAccess) tree.meth).selected.type 1809 : env.enclClass.sym.type; 1810 restype = adjustMethodReturnType(qualifier, methName, argtypes, restype); 1811 1812 chk.checkRefTypes(tree.typeargs, typeargtypes); 1813 1814 // Check that value of resulting type is admissible in the 1815 // current context. Also, capture the return type 1816 result = check(tree, capture(restype), VAL, resultInfo); 1817 1818 if (localEnv.info.lastResolveVarargs()) 1819 Assert.check(result.isErroneous() || tree.varargsElement != null); 1820 } 1821 chk.validate(tree.typeargs, localEnv); 1822 } 1823 //where 1824 Type adjustMethodReturnType(Type qualifierType, Name methodName, List<Type> argtypes, Type restype) { 1825 if (allowCovariantReturns && 1826 methodName == names.clone && 1827 types.isArray(qualifierType)) { 1828 // as a special case, array.clone() has a result that is 1829 // the same as static type of the array being cloned 1830 return qualifierType; 1831 } else if (allowGenerics && 1832 methodName == names.getClass && 1833 argtypes.isEmpty()) { 1834 // as a special case, x.getClass() has type Class<? extends |X|> 1835 return new ClassType(restype.getEnclosingType(), 1836 List.<Type>of(new WildcardType(types.erasure(qualifierType), 1837 BoundKind.EXTENDS, 1838 syms.boundClass)), 1839 restype.tsym); 1840 } else { 1841 return restype; 1842 } 1843 } 1844 1845 /** Check that given application node appears as first statement 1846 * in a constructor call. 1847 * @param tree The application node 1848 * @param env The environment current at the application. 1849 */ 1850 boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) { 1851 JCMethodDecl enclMethod = env.enclMethod; 1852 if (enclMethod != null && enclMethod.name == names.init) { 1853 JCBlock body = enclMethod.body; 1854 if (body.stats.head.hasTag(EXEC) && 1855 ((JCExpressionStatement) body.stats.head).expr == tree) 1856 return true; 1857 } 1858 log.error(tree.pos(),"call.must.be.first.stmt.in.ctor", 1859 TreeInfo.name(tree.meth)); 1860 return false; 1861 } 1862 1863 /** Obtain a method type with given argument types. 1864 */ 1865 Type newMethodTemplate(Type restype, List<Type> argtypes, List<Type> typeargtypes) { 1866 MethodType mt = new MethodType(argtypes, restype, List.<Type>nil(), syms.methodClass); 1867 return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt); 1868 } 1869 1870 public void visitNewClass(final JCNewClass tree) { 1871 Type owntype = types.createErrorType(tree.type); 1872 1873 // The local environment of a class creation is 1874 // a new environment nested in the current one. 1875 Env<AttrContext> localEnv = env.dup(tree, env.info.dup()); 1876 1877 // The anonymous inner class definition of the new expression, 1878 // if one is defined by it. 1879 JCClassDecl cdef = tree.def; 1880 1881 // If enclosing class is given, attribute it, and 1882 // complete class name to be fully qualified 1883 JCExpression clazz = tree.clazz; // Class field following new 1884 JCExpression clazzid; // Identifier in class field 1885 JCAnnotatedType annoclazzid; // Annotated type enclosing clazzid 1886 annoclazzid = null; 1887 1888 if (clazz.hasTag(TYPEAPPLY)) { 1889 clazzid = ((JCTypeApply) clazz).clazz; 1890 if (clazzid.hasTag(ANNOTATED_TYPE)) { 1891 annoclazzid = (JCAnnotatedType) clazzid; 1892 clazzid = annoclazzid.underlyingType; 1893 } 1894 } else { 1895 if (clazz.hasTag(ANNOTATED_TYPE)) { 1896 annoclazzid = (JCAnnotatedType) clazz; 1897 clazzid = annoclazzid.underlyingType; 1898 } else { 1899 clazzid = clazz; 1900 } 1901 } 1902 1903 JCExpression clazzid1 = clazzid; // The same in fully qualified form 1904 1905 if (tree.encl != null) { 1906 // We are seeing a qualified new, of the form 1907 // <expr>.new C <...> (...) ... 1908 // In this case, we let clazz stand for the name of the 1909 // allocated class C prefixed with the type of the qualifier 1910 // expression, so that we can 1911 // resolve it with standard techniques later. I.e., if 1912 // <expr> has type T, then <expr>.new C <...> (...) 1913 // yields a clazz T.C. 1914 Type encltype = chk.checkRefType(tree.encl.pos(), 1915 attribExpr(tree.encl, env)); 1916 // TODO 308: in <expr>.new C, do we also want to add the type annotations 1917 // from expr to the combined type, or not? Yes, do this. 1918 clazzid1 = make.at(clazz.pos).Select(make.Type(encltype), 1919 ((JCIdent) clazzid).name); 1920 1921 if (clazz.hasTag(ANNOTATED_TYPE)) { 1922 JCAnnotatedType annoType = (JCAnnotatedType) clazz; 1923 List<JCAnnotation> annos = annoType.annotations; 1924 1925 if (annoType.underlyingType.hasTag(TYPEAPPLY)) { 1926 clazzid1 = make.at(tree.pos). 1927 TypeApply(clazzid1, 1928 ((JCTypeApply) clazz).arguments); 1929 } 1930 1931 clazzid1 = make.at(tree.pos). 1932 AnnotatedType(annos, clazzid1); 1933 } else if (clazz.hasTag(TYPEAPPLY)) { 1934 clazzid1 = make.at(tree.pos). 1935 TypeApply(clazzid1, 1936 ((JCTypeApply) clazz).arguments); 1937 } 1938 1939 clazz = clazzid1; 1940 } 1941 1942 // Attribute clazz expression and store 1943 // symbol + type back into the attributed tree. 1944 Type clazztype = TreeInfo.isEnumInit(env.tree) ? 1945 attribIdentAsEnumType(env, (JCIdent)clazz) : 1946 attribType(clazz, env); 1947 1948 clazztype = chk.checkDiamond(tree, clazztype); 1949 chk.validate(clazz, localEnv); 1950 if (tree.encl != null) { 1951 // We have to work in this case to store 1952 // symbol + type back into the attributed tree. 1953 tree.clazz.type = clazztype; 1954 TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1)); 1955 clazzid.type = ((JCIdent) clazzid).sym.type; 1956 if (annoclazzid != null) { 1957 annoclazzid.type = clazzid.type; 1958 } 1959 if (!clazztype.isErroneous()) { 1960 if (cdef != null && clazztype.tsym.isInterface()) { 1961 log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new"); 1962 } else if (clazztype.tsym.isStatic()) { 1963 log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym); 1964 } 1965 } 1966 } else if (!clazztype.tsym.isInterface() && 1967 clazztype.getEnclosingType().hasTag(CLASS)) { 1968 // Check for the existence of an apropos outer instance 1969 rs.resolveImplicitThis(tree.pos(), env, clazztype); 1970 } 1971 1972 // Attribute constructor arguments. 1973 List<Type> argtypes = attribArgs(tree.args, localEnv); 1974 List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv); 1975 1976 // If we have made no mistakes in the class type... 1977 if (clazztype.hasTag(CLASS)) { 1978 // Enums may not be instantiated except implicitly 1979 if (allowEnums && 1980 (clazztype.tsym.flags_field&Flags.ENUM) != 0 && 1981 (!env.tree.hasTag(VARDEF) || 1982 (((JCVariableDecl) env.tree).mods.flags&Flags.ENUM) == 0 || 1983 ((JCVariableDecl) env.tree).init != tree)) 1984 log.error(tree.pos(), "enum.cant.be.instantiated"); 1985 // Check that class is not abstract 1986 if (cdef == null && 1987 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) { 1988 log.error(tree.pos(), "abstract.cant.be.instantiated", 1989 clazztype.tsym); 1990 } else if (cdef != null && clazztype.tsym.isInterface()) { 1991 // Check that no constructor arguments are given to 1992 // anonymous classes implementing an interface 1993 if (!argtypes.isEmpty()) 1994 log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args"); 1995 1996 if (!typeargtypes.isEmpty()) 1997 log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs"); 1998 1999 // Error recovery: pretend no arguments were supplied. 2000 argtypes = List.nil(); 2001 typeargtypes = List.nil(); 2002 } else if (TreeInfo.isDiamond(tree)) { 2003 ClassType site = new ClassType(clazztype.getEnclosingType(), 2004 clazztype.tsym.type.getTypeArguments(), 2005 clazztype.tsym); 2006 2007 Env<AttrContext> diamondEnv = localEnv.dup(tree); 2008 diamondEnv.info.selectSuper = cdef != null; 2009 diamondEnv.info.pendingResolutionPhase = null; 2010 2011 //if the type of the instance creation expression is a class type 2012 //apply method resolution inference (JLS 15.12.2.7). The return type 2013 //of the resolved constructor will be a partially instantiated type 2014 Symbol constructor = rs.resolveDiamond(tree.pos(), 2015 diamondEnv, 2016 site, 2017 argtypes, 2018 typeargtypes); 2019 tree.constructor = constructor.baseSymbol(); 2020 2021 final TypeSymbol csym = clazztype.tsym; 2022 ResultInfo diamondResult = new ResultInfo(MTH, newMethodTemplate(resultInfo.pt, argtypes, typeargtypes), new Check.NestedCheckContext(resultInfo.checkContext) { 2023 @Override 2024 public void report(DiagnosticPosition _unused, JCDiagnostic details) { 2025 enclosingContext.report(tree.clazz, 2026 diags.fragment("cant.apply.diamond.1", diags.fragment("diamond", csym), details)); 2027 } 2028 }); 2029 Type constructorType = tree.constructorType = types.createErrorType(clazztype); 2030 constructorType = checkId(tree, site, 2031 constructor, 2032 diamondEnv, 2033 diamondResult); 2034 2035 tree.clazz.type = types.createErrorType(clazztype); 2036 if (!constructorType.isErroneous()) { 2037 tree.clazz.type = clazztype = constructorType.getReturnType(); 2038 tree.constructorType = types.createMethodTypeWithReturn(constructorType, syms.voidType); 2039 } 2040 clazztype = chk.checkClassType(tree.clazz, tree.clazz.type, true); 2041 } 2042 2043 // Resolve the called constructor under the assumption 2044 // that we are referring to a superclass instance of the 2045 // current instance (JLS ???). 2046 else { 2047 //the following code alters some of the fields in the current 2048 //AttrContext - hence, the current context must be dup'ed in 2049 //order to avoid downstream failures 2050 Env<AttrContext> rsEnv = localEnv.dup(tree); 2051 rsEnv.info.selectSuper = cdef != null; 2052 rsEnv.info.pendingResolutionPhase = null; 2053 tree.constructor = rs.resolveConstructor( 2054 tree.pos(), rsEnv, clazztype, argtypes, typeargtypes); 2055 if (cdef == null) { //do not check twice! 2056 tree.constructorType = checkId(tree, 2057 clazztype, 2058 tree.constructor, 2059 rsEnv, 2060 new ResultInfo(MTH, newMethodTemplate(syms.voidType, argtypes, typeargtypes))); 2061 if (rsEnv.info.lastResolveVarargs()) 2062 Assert.check(tree.constructorType.isErroneous() || tree.varargsElement != null); 2063 } 2064 findDiamondIfNeeded(localEnv, tree, clazztype); 2065 } 2066 2067 if (cdef != null) { 2068 // We are seeing an anonymous class instance creation. 2069 // In this case, the class instance creation 2070 // expression 2071 // 2072 // E.new <typeargs1>C<typargs2>(args) { ... } 2073 // 2074 // is represented internally as 2075 // 2076 // E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } ) . 2077 // 2078 // This expression is then *transformed* as follows: 2079 // 2080 // (1) add a STATIC flag to the class definition 2081 // if the current environment is static 2082 // (2) add an extends or implements clause 2083 // (3) add a constructor. 2084 // 2085 // For instance, if C is a class, and ET is the type of E, 2086 // the expression 2087 // 2088 // E.new <typeargs1>C<typargs2>(args) { ... } 2089 // 2090 // is translated to (where X is a fresh name and typarams is the 2091 // parameter list of the super constructor): 2092 // 2093 // new <typeargs1>X(<*nullchk*>E, args) where 2094 // X extends C<typargs2> { 2095 // <typarams> X(ET e, args) { 2096 // e.<typeargs1>super(args) 2097 // } 2098 // ... 2099 // } 2100 if (Resolve.isStatic(env)) cdef.mods.flags |= STATIC; 2101 2102 if (clazztype.tsym.isInterface()) { 2103 cdef.implementing = List.of(clazz); 2104 } else { 2105 cdef.extending = clazz; 2106 } 2107 2108 attribStat(cdef, localEnv); 2109 2110 checkLambdaCandidate(tree, cdef.sym, clazztype); 2111 2112 // If an outer instance is given, 2113 // prefix it to the constructor arguments 2114 // and delete it from the new expression 2115 if (tree.encl != null && !clazztype.tsym.isInterface()) { 2116 tree.args = tree.args.prepend(makeNullCheck(tree.encl)); 2117 argtypes = argtypes.prepend(tree.encl.type); 2118 tree.encl = null; 2119 } 2120 2121 // Reassign clazztype and recompute constructor. 2122 clazztype = cdef.sym.type; 2123 Symbol sym = tree.constructor = rs.resolveConstructor( 2124 tree.pos(), localEnv, clazztype, argtypes, typeargtypes); 2125 Assert.check(sym.kind < AMBIGUOUS); 2126 tree.constructor = sym; 2127 tree.constructorType = checkId(tree, 2128 clazztype, 2129 tree.constructor, 2130 localEnv, 2131 new ResultInfo(VAL, newMethodTemplate(syms.voidType, argtypes, typeargtypes))); 2132 } 2133 2134 if (tree.constructor != null && tree.constructor.kind == MTH) 2135 owntype = clazztype; 2136 } 2137 result = check(tree, owntype, VAL, resultInfo); 2138 chk.validate(tree.typeargs, localEnv); 2139 } 2140 //where 2141 void findDiamondIfNeeded(Env<AttrContext> env, JCNewClass tree, Type clazztype) { 2142 if (tree.def == null && 2143 !clazztype.isErroneous() && 2144 clazztype.getTypeArguments().nonEmpty() && 2145 findDiamonds) { 2146 JCTypeApply ta = (JCTypeApply)tree.clazz; 2147 List<JCExpression> prevTypeargs = ta.arguments; 2148 try { 2149 //create a 'fake' diamond AST node by removing type-argument trees 2150 ta.arguments = List.nil(); 2151 ResultInfo findDiamondResult = new ResultInfo(VAL, 2152 resultInfo.checkContext.inferenceContext().free(resultInfo.pt) ? Type.noType : pt()); 2153 Type inferred = deferredAttr.attribSpeculative(tree, env, findDiamondResult).type; 2154 Type polyPt = allowPoly ? 2155 syms.objectType : 2156 clazztype; 2157 if (!inferred.isErroneous() && 2158 types.isAssignable(inferred, pt().hasTag(NONE) ? polyPt : pt(), types.noWarnings)) { 2159 String key = types.isSameType(clazztype, inferred) ? 2160 "diamond.redundant.args" : 2161 "diamond.redundant.args.1"; 2162 log.warning(tree.clazz.pos(), key, clazztype, inferred); 2163 } 2164 } finally { 2165 ta.arguments = prevTypeargs; 2166 } 2167 } 2168 } 2169 2170 private void checkLambdaCandidate(JCNewClass tree, ClassSymbol csym, Type clazztype) { 2171 if (allowLambda && 2172 identifyLambdaCandidate && 2173 clazztype.hasTag(CLASS) && 2174 !pt().hasTag(NONE) && 2175 types.isFunctionalInterface(clazztype.tsym)) { 2176 Symbol descriptor = types.findDescriptorSymbol(clazztype.tsym); 2177 int count = 0; 2178 boolean found = false; 2179 for (Symbol sym : csym.members().getElements()) { 2180 if ((sym.flags() & SYNTHETIC) != 0 || 2181 sym.isConstructor()) continue; 2182 count++; 2183 if (sym.kind != MTH || 2184 !sym.name.equals(descriptor.name)) continue; 2185 Type mtype = types.memberType(clazztype, sym); 2186 if (types.overrideEquivalent(mtype, types.memberType(clazztype, descriptor))) { 2187 found = true; 2188 } 2189 } 2190 if (found && count == 1) { 2191 log.note(tree.def, "potential.lambda.found"); 2192 } 2193 } 2194 } 2195 2196 /** Make an attributed null check tree. 2197 */ 2198 public JCExpression makeNullCheck(JCExpression arg) { 2199 // optimization: X.this is never null; skip null check 2200 Name name = TreeInfo.name(arg); 2201 if (name == names._this || name == names._super) return arg; 2202 2203 JCTree.Tag optag = NULLCHK; 2204 JCUnary tree = make.at(arg.pos).Unary(optag, arg); 2205 tree.operator = syms.nullcheck; 2206 tree.type = arg.type; 2207 return tree; 2208 } 2209 2210 public void visitNewArray(JCNewArray tree) { 2211 Type owntype = types.createErrorType(tree.type); 2212 Env<AttrContext> localEnv = env.dup(tree); 2213 Type elemtype; 2214 if (tree.elemtype != null) { 2215 elemtype = attribType(tree.elemtype, localEnv); 2216 chk.validate(tree.elemtype, localEnv); 2217 owntype = elemtype; 2218 for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) { 2219 attribExpr(l.head, localEnv, syms.intType); 2220 owntype = new ArrayType(owntype, syms.arrayClass); 2221 } 2222 } else { 2223 // we are seeing an untyped aggregate { ... } 2224 // this is allowed only if the prototype is an array 2225 if (pt().hasTag(ARRAY)) { 2226 elemtype = types.elemtype(pt()); 2227 } else { 2228 if (!pt().hasTag(ERROR)) { 2229 log.error(tree.pos(), "illegal.initializer.for.type", 2230 pt()); 2231 } 2232 elemtype = types.createErrorType(pt()); 2233 } 2234 } 2235 if (tree.elems != null) { 2236 attribExprs(tree.elems, localEnv, elemtype); 2237 owntype = new ArrayType(elemtype, syms.arrayClass); 2238 } 2239 if (!types.isReifiable(elemtype)) 2240 log.error(tree.pos(), "generic.array.creation"); 2241 result = check(tree, owntype, VAL, resultInfo); 2242 } 2243 2244 /* 2245 * A lambda expression can only be attributed when a target-type is available. 2246 * In addition, if the target-type is that of a functional interface whose 2247 * descriptor contains inference variables in argument position the lambda expression 2248 * is 'stuck' (see DeferredAttr). 2249 */ 2250 @Override 2251 public void visitLambda(final JCLambda that) { 2252 if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) { 2253 if (pt().hasTag(NONE)) { 2254 //lambda only allowed in assignment or method invocation/cast context 2255 log.error(that.pos(), "unexpected.lambda"); 2256 } 2257 result = that.type = types.createErrorType(pt()); 2258 return; 2259 } 2260 //create an environment for attribution of the lambda expression 2261 final Env<AttrContext> localEnv = lambdaEnv(that, env); 2262 boolean needsRecovery = 2263 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK; 2264 try { 2265 Type target = pt(); 2266 List<Type> explicitParamTypes = null; 2267 if (that.paramKind == JCLambda.ParameterKind.EXPLICIT) { 2268 //attribute lambda parameters 2269 attribStats(that.params, localEnv); 2270 explicitParamTypes = TreeInfo.types(that.params); 2271 target = infer.instantiateFunctionalInterface(that, target, explicitParamTypes, resultInfo.checkContext); 2272 } 2273 2274 Type lambdaType; 2275 if (pt() != Type.recoveryType) { 2276 target = checkIntersectionTarget(that, target, resultInfo.checkContext); 2277 lambdaType = types.findDescriptorType(target); 2278 chk.checkFunctionalInterface(that, target); 2279 } else { 2280 target = Type.recoveryType; 2281 lambdaType = fallbackDescriptorType(that); 2282 } 2283 2284 setFunctionalInfo(that, pt(), lambdaType, resultInfo.checkContext.inferenceContext()); 2285 2286 if (lambdaType.hasTag(FORALL)) { 2287 //lambda expression target desc cannot be a generic method 2288 resultInfo.checkContext.report(that, diags.fragment("invalid.generic.lambda.target", 2289 lambdaType, kindName(target.tsym), target.tsym)); 2290 result = that.type = types.createErrorType(pt()); 2291 return; 2292 } 2293 2294 if (that.paramKind == JCLambda.ParameterKind.IMPLICIT) { 2295 //add param type info in the AST 2296 List<Type> actuals = lambdaType.getParameterTypes(); 2297 List<JCVariableDecl> params = that.params; 2298 2299 boolean arityMismatch = false; 2300 2301 while (params.nonEmpty()) { 2302 if (actuals.isEmpty()) { 2303 //not enough actuals to perform lambda parameter inference 2304 arityMismatch = true; 2305 } 2306 //reset previously set info 2307 Type argType = arityMismatch ? 2308 syms.errType : 2309 actuals.head; 2310 params.head.vartype = make.Type(argType); 2311 params.head.sym = null; 2312 actuals = actuals.isEmpty() ? 2313 actuals : 2314 actuals.tail; 2315 params = params.tail; 2316 } 2317 2318 //attribute lambda parameters 2319 attribStats(that.params, localEnv); 2320 2321 if (arityMismatch) { 2322 resultInfo.checkContext.report(that, diags.fragment("incompatible.arg.types.in.lambda")); 2323 result = that.type = types.createErrorType(target); 2324 return; 2325 } 2326 } 2327 2328 //from this point on, no recovery is needed; if we are in assignment context 2329 //we will be able to attribute the whole lambda body, regardless of errors; 2330 //if we are in a 'check' method context, and the lambda is not compatible 2331 //with the target-type, it will be recovered anyway in Attr.checkId 2332 needsRecovery = false; 2333 2334 FunctionalReturnContext funcContext = that.getBodyKind() == JCLambda.BodyKind.EXPRESSION ? 2335 new ExpressionLambdaReturnContext((JCExpression)that.getBody(), resultInfo.checkContext) : 2336 new FunctionalReturnContext(resultInfo.checkContext); 2337 2338 ResultInfo bodyResultInfo = lambdaType.getReturnType() == Type.recoveryType ? 2339 recoveryInfo : 2340 new ResultInfo(VAL, lambdaType.getReturnType(), funcContext); 2341 localEnv.info.returnResult = bodyResultInfo; 2342 2343 if (that.getBodyKind() == JCLambda.BodyKind.EXPRESSION) { 2344 attribTree(that.getBody(), localEnv, bodyResultInfo); 2345 } else { 2346 JCBlock body = (JCBlock)that.body; 2347 attribStats(body.stats, localEnv); 2348 } 2349 2350 result = check(that, target, VAL, resultInfo); 2351 2352 boolean isSpeculativeRound = 2353 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE; 2354 2355 postAttr(that); 2356 flow.analyzeLambda(env, that, make, isSpeculativeRound); 2357 2358 checkLambdaCompatible(that, lambdaType, resultInfo.checkContext, isSpeculativeRound); 2359 2360 if (!isSpeculativeRound) { 2361 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), lambdaType, target); 2362 } 2363 result = check(that, target, VAL, resultInfo); 2364 } catch (Types.FunctionDescriptorLookupError ex) { 2365 JCDiagnostic cause = ex.getDiagnostic(); 2366 resultInfo.checkContext.report(that, cause); 2367 result = that.type = types.createErrorType(pt()); 2368 return; 2369 } finally { 2370 localEnv.info.scope.leave(); 2371 if (needsRecovery) { 2372 attribTree(that, env, recoveryInfo); 2373 } 2374 } 2375 } 2376 2377 private Type checkIntersectionTarget(DiagnosticPosition pos, Type pt, CheckContext checkContext) { 2378 if (pt != Type.recoveryType && pt.isCompound()) { 2379 IntersectionClassType ict = (IntersectionClassType)pt; 2380 List<Type> bounds = ict.allInterfaces ? 2381 ict.getComponents().tail : 2382 ict.getComponents(); 2383 types.findDescriptorType(bounds.head); //propagate exception outwards! 2384 for (Type bound : bounds.tail) { 2385 if (!types.isMarkerInterface(bound)) { 2386 checkContext.report(pos, diags.fragment("secondary.bound.must.be.marker.intf", bound)); 2387 } 2388 } 2389 //for now (translation doesn't support intersection types) 2390 return bounds.head; 2391 } else { 2392 return pt; 2393 } 2394 } 2395 //where 2396 private Type fallbackDescriptorType(JCExpression tree) { 2397 switch (tree.getTag()) { 2398 case LAMBDA: 2399 JCLambda lambda = (JCLambda)tree; 2400 List<Type> argtypes = List.nil(); 2401 for (JCVariableDecl param : lambda.params) { 2402 argtypes = param.vartype != null ? 2403 argtypes.append(param.vartype.type) : 2404 argtypes.append(syms.errType); 2405 } 2406 return new MethodType(argtypes, Type.recoveryType, List.<Type>nil(), syms.methodClass); 2407 case REFERENCE: 2408 return new MethodType(List.<Type>nil(), Type.recoveryType, List.<Type>nil(), syms.methodClass); 2409 default: 2410 Assert.error("Cannot get here!"); 2411 } 2412 return null; 2413 } 2414 2415 private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env, final InferenceContext inferenceContext, final Type... ts) { 2416 checkAccessibleTypes(pos, env, inferenceContext, List.from(ts)); 2417 } 2418 2419 private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env, final InferenceContext inferenceContext, final List<Type> ts) { 2420 if (inferenceContext.free(ts)) { 2421 inferenceContext.addFreeTypeListener(ts, new FreeTypeListener() { 2422 @Override 2423 public void typesInferred(InferenceContext inferenceContext) { 2424 checkAccessibleTypes(pos, env, inferenceContext, inferenceContext.asInstTypes(ts)); 2425 } 2426 }); 2427 } else { 2428 for (Type t : ts) { 2429 rs.checkAccessibleType(env, t); 2430 } 2431 } 2432 } 2433 2434 /** 2435 * Lambda/method reference have a special check context that ensures 2436 * that i.e. a lambda return type is compatible with the expected 2437 * type according to both the inherited context and the assignment 2438 * context. 2439 */ 2440 class FunctionalReturnContext extends Check.NestedCheckContext { 2441 2442 FunctionalReturnContext(CheckContext enclosingContext) { 2443 super(enclosingContext); 2444 } 2445 2446 @Override 2447 public boolean compatible(Type found, Type req, Warner warn) { 2448 //return type must be compatible in both current context and assignment context 2449 return chk.basicHandler.compatible(found, inferenceContext().asFree(req), warn); 2450 } 2451 2452 @Override 2453 public void report(DiagnosticPosition pos, JCDiagnostic details) { 2454 enclosingContext.report(pos, diags.fragment("incompatible.ret.type.in.lambda", details)); 2455 } 2456 } 2457 2458 class ExpressionLambdaReturnContext extends FunctionalReturnContext { 2459 2460 JCExpression expr; 2461 2462 ExpressionLambdaReturnContext(JCExpression expr, CheckContext enclosingContext) { 2463 super(enclosingContext); 2464 this.expr = expr; 2465 } 2466 2467 @Override 2468 public boolean compatible(Type found, Type req, Warner warn) { 2469 //a void return is compatible with an expression statement lambda 2470 return TreeInfo.isExpressionStatement(expr) && req.hasTag(VOID) || 2471 super.compatible(found, req, warn); 2472 } 2473 } 2474 2475 /** 2476 * Lambda compatibility. Check that given return types, thrown types, parameter types 2477 * are compatible with the expected functional interface descriptor. This means that: 2478 * (i) parameter types must be identical to those of the target descriptor; (ii) return 2479 * types must be compatible with the return type of the expected descriptor; 2480 * (iii) thrown types must be 'included' in the thrown types list of the expected 2481 * descriptor. 2482 */ 2483 private void checkLambdaCompatible(JCLambda tree, Type descriptor, CheckContext checkContext, boolean speculativeAttr) { 2484 Type returnType = checkContext.inferenceContext().asFree(descriptor.getReturnType()); 2485 2486 //return values have already been checked - but if lambda has no return 2487 //values, we must ensure that void/value compatibility is correct; 2488 //this amounts at checking that, if a lambda body can complete normally, 2489 //the descriptor's return type must be void 2490 if (tree.getBodyKind() == JCLambda.BodyKind.STATEMENT && tree.canCompleteNormally && 2491 !returnType.hasTag(VOID) && returnType != Type.recoveryType) { 2492 checkContext.report(tree, diags.fragment("incompatible.ret.type.in.lambda", 2493 diags.fragment("missing.ret.val", returnType))); 2494 } 2495 2496 List<Type> argTypes = checkContext.inferenceContext().asFree(descriptor.getParameterTypes()); 2497 if (!types.isSameTypes(argTypes, TreeInfo.types(tree.params))) { 2498 checkContext.report(tree, diags.fragment("incompatible.arg.types.in.lambda")); 2499 } 2500 2501 if (!speculativeAttr) { 2502 List<Type> thrownTypes = checkContext.inferenceContext().asFree(descriptor.getThrownTypes()); 2503 if (chk.unhandled(tree.inferredThrownTypes == null ? List.<Type>nil() : tree.inferredThrownTypes, thrownTypes).nonEmpty()) { 2504 log.error(tree, "incompatible.thrown.types.in.lambda", tree.inferredThrownTypes); 2505 } 2506 } 2507 } 2508 2509 private Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) { 2510 Env<AttrContext> lambdaEnv; 2511 Symbol owner = env.info.scope.owner; 2512 if (owner.kind == VAR && owner.owner.kind == TYP) { 2513 //field initializer 2514 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared())); 2515 lambdaEnv.info.scope.owner = 2516 new MethodSymbol(0, names.empty, null, 2517 env.info.scope.owner); 2518 } else { 2519 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dup())); 2520 } 2521 return lambdaEnv; 2522 } 2523 2524 @Override 2525 public void visitReference(final JCMemberReference that) { 2526 if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) { 2527 if (pt().hasTag(NONE)) { 2528 //method reference only allowed in assignment or method invocation/cast context 2529 log.error(that.pos(), "unexpected.mref"); 2530 } 2531 result = that.type = types.createErrorType(pt()); 2532 return; 2533 } 2534 final Env<AttrContext> localEnv = env.dup(that); 2535 try { 2536 //attribute member reference qualifier - if this is a constructor 2537 //reference, the expected kind must be a type 2538 Type exprType = attribTree(that.expr, env, memberReferenceQualifierResult(that)); 2539 2540 if (that.getMode() == JCMemberReference.ReferenceMode.NEW) { 2541 exprType = chk.checkConstructorRefType(that.expr, exprType); 2542 } 2543 2544 if (exprType.isErroneous()) { 2545 //if the qualifier expression contains problems, 2546 //give up attribution of method reference 2547 result = that.type = exprType; 2548 return; 2549 } 2550 2551 if (TreeInfo.isStaticSelector(that.expr, names) && 2552 (that.getMode() != ReferenceMode.NEW || !that.expr.type.isRaw())) { 2553 //if the qualifier is a type, validate it 2554 chk.validate(that.expr, env); 2555 } 2556 2557 //attrib type-arguments 2558 List<Type> typeargtypes = List.nil(); 2559 if (that.typeargs != null) { 2560 typeargtypes = attribTypes(that.typeargs, localEnv); 2561 } 2562 2563 Type target; 2564 Type desc; 2565 if (pt() != Type.recoveryType) { 2566 target = checkIntersectionTarget(that, pt(), resultInfo.checkContext); 2567 desc = types.findDescriptorType(target); 2568 chk.checkFunctionalInterface(that, target); 2569 } else { 2570 target = Type.recoveryType; 2571 desc = fallbackDescriptorType(that); 2572 } 2573 2574 setFunctionalInfo(that, pt(), desc, resultInfo.checkContext.inferenceContext()); 2575 List<Type> argtypes = desc.getParameterTypes(); 2576 2577 Pair<Symbol, Resolve.ReferenceLookupHelper> refResult = rs.resolveMemberReference(that.pos(), localEnv, that, 2578 that.expr.type, that.name, argtypes, typeargtypes, true); 2579 2580 Symbol refSym = refResult.fst; 2581 Resolve.ReferenceLookupHelper lookupHelper = refResult.snd; 2582 2583 if (refSym.kind != MTH) { 2584 boolean targetError; 2585 switch (refSym.kind) { 2586 case ABSENT_MTH: 2587 targetError = false; 2588 break; 2589 case WRONG_MTH: 2590 case WRONG_MTHS: 2591 case AMBIGUOUS: 2592 case HIDDEN: 2593 case STATICERR: 2594 case MISSING_ENCL: 2595 targetError = true; 2596 break; 2597 default: 2598 Assert.error("unexpected result kind " + refSym.kind); 2599 targetError = false; 2600 } 2601 2602 JCDiagnostic detailsDiag = ((Resolve.ResolveError)refSym).getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT, 2603 that, exprType.tsym, exprType, that.name, argtypes, typeargtypes); 2604 2605 JCDiagnostic.DiagnosticType diagKind = targetError ? 2606 JCDiagnostic.DiagnosticType.FRAGMENT : JCDiagnostic.DiagnosticType.ERROR; 2607 2608 JCDiagnostic diag = diags.create(diagKind, log.currentSource(), that, 2609 "invalid.mref", Kinds.kindName(that.getMode()), detailsDiag); 2610 2611 if (targetError && target == Type.recoveryType) { 2612 //a target error doesn't make sense during recovery stage 2613 //as we don't know what actual parameter types are 2614 result = that.type = target; 2615 return; 2616 } else { 2617 if (targetError) { 2618 resultInfo.checkContext.report(that, diag); 2619 } else { 2620 log.report(diag); 2621 } 2622 result = that.type = types.createErrorType(target); 2623 return; 2624 } 2625 } 2626 2627 that.sym = refSym.baseSymbol(); 2628 that.kind = lookupHelper.referenceKind(that.sym); 2629 that.ownerAccessible = rs.isAccessible(localEnv, that.sym.enclClass()); 2630 2631 if (desc.getReturnType() == Type.recoveryType) { 2632 // stop here 2633 result = that.type = target; 2634 return; 2635 } 2636 2637 if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) { 2638 2639 if (!that.kind.isUnbound() && 2640 that.getMode() == ReferenceMode.INVOKE && 2641 TreeInfo.isStaticSelector(that.expr, names) && 2642 !that.sym.isStatic()) { 2643 log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()), 2644 diags.fragment("non-static.cant.be.ref", Kinds.kindName(refSym), refSym)); 2645 result = that.type = types.createErrorType(target); 2646 return; 2647 } 2648 2649 if (that.kind.isUnbound() && 2650 that.getMode() == ReferenceMode.INVOKE && 2651 TreeInfo.isStaticSelector(that.expr, names) && 2652 that.sym.isStatic()) { 2653 log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()), 2654 diags.fragment("static.method.in.unbound.lookup", Kinds.kindName(refSym), refSym)); 2655 result = that.type = types.createErrorType(target); 2656 return; 2657 } 2658 2659 if (that.sym.isStatic() && TreeInfo.isStaticSelector(that.expr, names) && 2660 exprType.getTypeArguments().nonEmpty()) { 2661 //static ref with class type-args 2662 log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()), 2663 diags.fragment("static.mref.with.targs")); 2664 result = that.type = types.createErrorType(target); 2665 return; 2666 } 2667 2668 if (that.sym.isStatic() && !TreeInfo.isStaticSelector(that.expr, names) && 2669 !that.kind.isUnbound()) { 2670 //no static bound mrefs 2671 log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()), 2672 diags.fragment("static.bound.mref")); 2673 result = that.type = types.createErrorType(target); 2674 return; 2675 } 2676 2677 if (!refSym.isStatic() && that.kind == JCMemberReference.ReferenceKind.SUPER) { 2678 // Check that super-qualified symbols are not abstract (JLS) 2679 rs.checkNonAbstract(that.pos(), that.sym); 2680 } 2681 } 2682 2683 that.sym = refSym.baseSymbol(); 2684 that.kind = lookupHelper.referenceKind(that.sym); 2685 2686 ResultInfo checkInfo = 2687 resultInfo.dup(newMethodTemplate( 2688 desc.getReturnType().hasTag(VOID) ? Type.noType : desc.getReturnType(), 2689 lookupHelper.argtypes, 2690 typeargtypes)); 2691 2692 Type refType = checkId(that, lookupHelper.site, refSym, localEnv, checkInfo); 2693 2694 if (!refType.isErroneous()) { 2695 refType = types.createMethodTypeWithReturn(refType, 2696 adjustMethodReturnType(lookupHelper.site, that.name, checkInfo.pt.getParameterTypes(), refType.getReturnType())); 2697 } 2698 2699 //go ahead with standard method reference compatibility check - note that param check 2700 //is a no-op (as this has been taken care during method applicability) 2701 boolean isSpeculativeRound = 2702 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE; 2703 checkReferenceCompatible(that, desc, refType, resultInfo.checkContext, isSpeculativeRound); 2704 if (!isSpeculativeRound) { 2705 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), desc, target); 2706 } 2707 result = check(that, target, VAL, resultInfo); 2708 } catch (Types.FunctionDescriptorLookupError ex) { 2709 JCDiagnostic cause = ex.getDiagnostic(); 2710 resultInfo.checkContext.report(that, cause); 2711 result = that.type = types.createErrorType(pt()); 2712 return; 2713 } 2714 } 2715 //where 2716 ResultInfo memberReferenceQualifierResult(JCMemberReference tree) { 2717 //if this is a constructor reference, the expected kind must be a type 2718 return new ResultInfo(tree.getMode() == ReferenceMode.INVOKE ? VAL | TYP : TYP, Type.noType); 2719 } 2720 2721 2722 @SuppressWarnings("fallthrough") 2723 void checkReferenceCompatible(JCMemberReference tree, Type descriptor, Type refType, CheckContext checkContext, boolean speculativeAttr) { 2724 Type returnType = checkContext.inferenceContext().asFree(descriptor.getReturnType()); 2725 2726 Type resType; 2727 switch (tree.getMode()) { 2728 case NEW: 2729 if (!tree.expr.type.isRaw()) { 2730 resType = tree.expr.type; 2731 break; 2732 } 2733 default: 2734 resType = refType.getReturnType(); 2735 } 2736 2737 Type incompatibleReturnType = resType; 2738 2739 if (returnType.hasTag(VOID)) { 2740 incompatibleReturnType = null; 2741 } 2742 2743 if (!returnType.hasTag(VOID) && !resType.hasTag(VOID)) { 2744 if (resType.isErroneous() || 2745 new FunctionalReturnContext(checkContext).compatible(resType, returnType, types.noWarnings)) { 2746 incompatibleReturnType = null; 2747 } 2748 } 2749 2750 if (incompatibleReturnType != null) { 2751 checkContext.report(tree, diags.fragment("incompatible.ret.type.in.mref", 2752 diags.fragment("inconvertible.types", resType, descriptor.getReturnType()))); 2753 } 2754 2755 if (!speculativeAttr) { 2756 List<Type> thrownTypes = checkContext.inferenceContext().asFree(descriptor.getThrownTypes()); 2757 if (chk.unhandled(refType.getThrownTypes(), thrownTypes).nonEmpty()) { 2758 log.error(tree, "incompatible.thrown.types.in.mref", refType.getThrownTypes()); 2759 } 2760 } 2761 } 2762 2763 /** 2764 * Set functional type info on the underlying AST. Note: as the target descriptor 2765 * might contain inference variables, we might need to register an hook in the 2766 * current inference context. 2767 */ 2768 private void setFunctionalInfo(final JCFunctionalExpression fExpr, final Type pt, final Type descriptorType, InferenceContext inferenceContext) { 2769 if (inferenceContext.free(descriptorType)) { 2770 inferenceContext.addFreeTypeListener(List.of(pt, descriptorType), new FreeTypeListener() { 2771 public void typesInferred(InferenceContext inferenceContext) { 2772 setFunctionalInfo(fExpr, pt, inferenceContext.asInstType(descriptorType), inferenceContext); 2773 } 2774 }); 2775 } else { 2776 ListBuffer<TypeSymbol> targets = ListBuffer.lb(); 2777 if (pt.hasTag(CLASS)) { 2778 if (pt.isCompound()) { 2779 for (Type t : ((IntersectionClassType)pt()).interfaces_field) { 2780 targets.append(t.tsym); 2781 } 2782 } else { 2783 targets.append(pt.tsym); 2784 } 2785 } 2786 fExpr.targets = targets.toList(); 2787 fExpr.descriptorType = descriptorType; 2788 } 2789 } 2790 2791 public void visitParens(JCParens tree) { 2792 Type owntype = attribTree(tree.expr, env, resultInfo); 2793 result = check(tree, owntype, pkind(), resultInfo); 2794 Symbol sym = TreeInfo.symbol(tree); 2795 if (sym != null && (sym.kind&(TYP|PCK)) != 0) 2796 log.error(tree.pos(), "illegal.start.of.type"); 2797 } 2798 2799 public void visitAssign(JCAssign tree) { 2800 Type owntype = attribTree(tree.lhs, env.dup(tree), varInfo); 2801 Type capturedType = capture(owntype); 2802 attribExpr(tree.rhs, env, owntype); 2803 result = check(tree, capturedType, VAL, resultInfo); 2804 } 2805 2806 public void visitAssignop(JCAssignOp tree) { 2807 // Attribute arguments. 2808 Type owntype = attribTree(tree.lhs, env, varInfo); 2809 Type operand = attribExpr(tree.rhs, env); 2810 // Find operator. 2811 Symbol operator = tree.operator = rs.resolveBinaryOperator( 2812 tree.pos(), tree.getTag().noAssignOp(), env, 2813 owntype, operand); 2814 2815 if (operator.kind == MTH && 2816 !owntype.isErroneous() && 2817 !operand.isErroneous()) { 2818 chk.checkOperator(tree.pos(), 2819 (OperatorSymbol)operator, 2820 tree.getTag().noAssignOp(), 2821 owntype, 2822 operand); 2823 chk.checkDivZero(tree.rhs.pos(), operator, operand); 2824 chk.checkCastable(tree.rhs.pos(), 2825 operator.type.getReturnType(), 2826 owntype); 2827 } 2828 result = check(tree, owntype, VAL, resultInfo); 2829 } 2830 2831 public void visitUnary(JCUnary tree) { 2832 // Attribute arguments. 2833 Type argtype = (tree.getTag().isIncOrDecUnaryOp()) 2834 ? attribTree(tree.arg, env, varInfo) 2835 : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env)); 2836 2837 // Find operator. 2838 Symbol operator = tree.operator = 2839 rs.resolveUnaryOperator(tree.pos(), tree.getTag(), env, argtype); 2840 2841 Type owntype = types.createErrorType(tree.type); 2842 if (operator.kind == MTH && 2843 !argtype.isErroneous()) { 2844 owntype = (tree.getTag().isIncOrDecUnaryOp()) 2845 ? tree.arg.type 2846 : operator.type.getReturnType(); 2847 int opc = ((OperatorSymbol)operator).opcode; 2848 2849 // If the argument is constant, fold it. 2850 if (argtype.constValue() != null) { 2851 Type ctype = cfolder.fold1(opc, argtype); 2852 if (ctype != null) { 2853 owntype = cfolder.coerce(ctype, owntype); 2854 2855 // Remove constant types from arguments to 2856 // conserve space. The parser will fold concatenations 2857 // of string literals; the code here also 2858 // gets rid of intermediate results when some of the 2859 // operands are constant identifiers. 2860 if (tree.arg.type.tsym == syms.stringType.tsym) { 2861 tree.arg.type = syms.stringType; 2862 } 2863 } 2864 } 2865 } 2866 result = check(tree, owntype, VAL, resultInfo); 2867 } 2868 2869 public void visitBinary(JCBinary tree) { 2870 // Attribute arguments. 2871 Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env)); 2872 Type right = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.rhs, env)); 2873 2874 // Find operator. 2875 Symbol operator = tree.operator = 2876 rs.resolveBinaryOperator(tree.pos(), tree.getTag(), env, left, right); 2877 2878 Type owntype = types.createErrorType(tree.type); 2879 if (operator.kind == MTH && 2880 !left.isErroneous() && 2881 !right.isErroneous()) { 2882 owntype = operator.type.getReturnType(); 2883 int opc = chk.checkOperator(tree.lhs.pos(), 2884 (OperatorSymbol)operator, 2885 tree.getTag(), 2886 left, 2887 right); 2888 2889 // If both arguments are constants, fold them. 2890 if (left.constValue() != null && right.constValue() != null) { 2891 Type ctype = cfolder.fold2(opc, left, right); 2892 if (ctype != null) { 2893 owntype = cfolder.coerce(ctype, owntype); 2894 2895 // Remove constant types from arguments to 2896 // conserve space. The parser will fold concatenations 2897 // of string literals; the code here also 2898 // gets rid of intermediate results when some of the 2899 // operands are constant identifiers. 2900 if (tree.lhs.type.tsym == syms.stringType.tsym) { 2901 tree.lhs.type = syms.stringType; 2902 } 2903 if (tree.rhs.type.tsym == syms.stringType.tsym) { 2904 tree.rhs.type = syms.stringType; 2905 } 2906 } 2907 } 2908 2909 // Check that argument types of a reference ==, != are 2910 // castable to each other, (JLS???). 2911 if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) { 2912 if (!types.isCastable(left, right, new Warner(tree.pos()))) { 2913 log.error(tree.pos(), "incomparable.types", left, right); 2914 } 2915 } 2916 2917 chk.checkDivZero(tree.rhs.pos(), operator, right); 2918 } 2919 result = check(tree, owntype, VAL, resultInfo); 2920 } 2921 2922 public void visitTypeCast(final JCTypeCast tree) { 2923 Type clazztype = attribType(tree.clazz, env); 2924 chk.validate(tree.clazz, env, false); 2925 //a fresh environment is required for 292 inference to work properly --- 2926 //see Infer.instantiatePolymorphicSignatureInstance() 2927 Env<AttrContext> localEnv = env.dup(tree); 2928 //should we propagate the target type? 2929 final ResultInfo castInfo; 2930 final boolean isPoly = TreeInfo.isPoly(tree.expr, tree); 2931 if (isPoly) { 2932 //expression is a poly - we need to propagate target type info 2933 castInfo = new ResultInfo(VAL, clazztype, new Check.NestedCheckContext(resultInfo.checkContext) { 2934 @Override 2935 public boolean compatible(Type found, Type req, Warner warn) { 2936 return types.isCastable(found, req, warn); 2937 } 2938 }); 2939 } else { 2940 //standalone cast - target-type info is not propagated 2941 castInfo = unknownExprInfo; 2942 } 2943 Type exprtype = attribTree(tree.expr, localEnv, castInfo); 2944 Type owntype = isPoly ? clazztype : chk.checkCastable(tree.expr.pos(), exprtype, clazztype); 2945 if (exprtype.constValue() != null) 2946 owntype = cfolder.coerce(exprtype, owntype); 2947 result = check(tree, capture(owntype), VAL, resultInfo); 2948 if (!isPoly) 2949 chk.checkRedundantCast(localEnv, tree); 2950 } 2951 2952 public void visitTypeTest(JCInstanceOf tree) { 2953 Type exprtype = chk.checkNullOrRefType( 2954 tree.expr.pos(), attribExpr(tree.expr, env)); 2955 Type clazztype = chk.checkReifiableReferenceType( 2956 tree.clazz.pos(), attribType(tree.clazz, env)); 2957 chk.validate(tree.clazz, env, false); 2958 chk.checkCastable(tree.expr.pos(), exprtype, clazztype); 2959 result = check(tree, syms.booleanType, VAL, resultInfo); 2960 } 2961 2962 public void visitIndexed(JCArrayAccess tree) { 2963 Type owntype = types.createErrorType(tree.type); 2964 Type atype = attribExpr(tree.indexed, env); 2965 attribExpr(tree.index, env, syms.intType); 2966 if (types.isArray(atype)) 2967 owntype = types.elemtype(atype); 2968 else if (!atype.hasTag(ERROR)) 2969 log.error(tree.pos(), "array.req.but.found", atype); 2970 if ((pkind() & VAR) == 0) owntype = capture(owntype); 2971 result = check(tree, owntype, VAR, resultInfo); 2972 } 2973 2974 public void visitIdent(JCIdent tree) { 2975 Symbol sym; 2976 2977 // Find symbol 2978 if (pt().hasTag(METHOD) || pt().hasTag(FORALL)) { 2979 // If we are looking for a method, the prototype `pt' will be a 2980 // method type with the type of the call's arguments as parameters. 2981 env.info.pendingResolutionPhase = null; 2982 sym = rs.resolveMethod(tree.pos(), env, tree.name, pt().getParameterTypes(), pt().getTypeArguments()); 2983 } else if (tree.sym != null && tree.sym.kind != VAR) { 2984 sym = tree.sym; 2985 } else { 2986 sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind()); 2987 } 2988 tree.sym = sym; 2989 2990 // (1) Also find the environment current for the class where 2991 // sym is defined (`symEnv'). 2992 // Only for pre-tiger versions (1.4 and earlier): 2993 // (2) Also determine whether we access symbol out of an anonymous 2994 // class in a this or super call. This is illegal for instance 2995 // members since such classes don't carry a this$n link. 2996 // (`noOuterThisPath'). 2997 Env<AttrContext> symEnv = env; 2998 boolean noOuterThisPath = false; 2999 if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class 3000 (sym.kind & (VAR | MTH | TYP)) != 0 && 3001 sym.owner.kind == TYP && 3002 tree.name != names._this && tree.name != names._super) { 3003 3004 // Find environment in which identifier is defined. 3005 while (symEnv.outer != null && 3006 !sym.isMemberOf(symEnv.enclClass.sym, types)) { 3007 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0) 3008 noOuterThisPath = !allowAnonOuterThis; 3009 symEnv = symEnv.outer; 3010 } 3011 } 3012 3013 // If symbol is a variable, ... 3014 if (sym.kind == VAR) { 3015 VarSymbol v = (VarSymbol)sym; 3016 3017 // ..., evaluate its initializer, if it has one, and check for 3018 // illegal forward reference. 3019 checkInit(tree, env, v, false); 3020 3021 // If we are expecting a variable (as opposed to a value), check 3022 // that the variable is assignable in the current environment. 3023 if (pkind() == VAR) 3024 checkAssignable(tree.pos(), v, null, env); 3025 } 3026 3027 // In a constructor body, 3028 // if symbol is a field or instance method, check that it is 3029 // not accessed before the supertype constructor is called. 3030 if ((symEnv.info.isSelfCall || noOuterThisPath) && 3031 (sym.kind & (VAR | MTH)) != 0 && 3032 sym.owner.kind == TYP && 3033 (sym.flags() & STATIC) == 0) { 3034 chk.earlyRefError(tree.pos(), sym.kind == VAR ? sym : thisSym(tree.pos(), env)); 3035 } 3036 Env<AttrContext> env1 = env; 3037 if (sym.kind != ERR && sym.kind != TYP && sym.owner != null && sym.owner != env1.enclClass.sym) { 3038 // If the found symbol is inaccessible, then it is 3039 // accessed through an enclosing instance. Locate this 3040 // enclosing instance: 3041 while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym)) 3042 env1 = env1.outer; 3043 } 3044 result = checkId(tree, env1.enclClass.sym.type, sym, env, resultInfo); 3045 } 3046 3047 public void visitSelect(JCFieldAccess tree) { 3048 // Determine the expected kind of the qualifier expression. 3049 int skind = 0; 3050 if (tree.name == names._this || tree.name == names._super || 3051 tree.name == names._class) 3052 { 3053 skind = TYP; 3054 } else { 3055 if ((pkind() & PCK) != 0) skind = skind | PCK; 3056 if ((pkind() & TYP) != 0) skind = skind | TYP | PCK; 3057 if ((pkind() & (VAL | MTH)) != 0) skind = skind | VAL | TYP; 3058 } 3059 3060 // Attribute the qualifier expression, and determine its symbol (if any). 3061 Type site = attribTree(tree.selected, env, new ResultInfo(skind, Infer.anyPoly)); 3062 if ((pkind() & (PCK | TYP)) == 0) 3063 site = capture(site); // Capture field access 3064 3065 // don't allow T.class T[].class, etc 3066 if (skind == TYP) { 3067 Type elt = site; 3068 while (elt.hasTag(ARRAY)) 3069 elt = ((ArrayType)elt).elemtype; 3070 if (elt.hasTag(TYPEVAR)) { 3071 log.error(tree.pos(), "type.var.cant.be.deref"); 3072 result = types.createErrorType(tree.type); 3073 return; 3074 } 3075 } 3076 3077 // If qualifier symbol is a type or `super', assert `selectSuper' 3078 // for the selection. This is relevant for determining whether 3079 // protected symbols are accessible. 3080 Symbol sitesym = TreeInfo.symbol(tree.selected); 3081 boolean selectSuperPrev = env.info.selectSuper; 3082 env.info.selectSuper = 3083 sitesym != null && 3084 sitesym.name == names._super; 3085 3086 // Determine the symbol represented by the selection. 3087 env.info.pendingResolutionPhase = null; 3088 Symbol sym = selectSym(tree, sitesym, site, env, resultInfo); 3089 if (sym.exists() && !isType(sym) && (pkind() & (PCK | TYP)) != 0) { 3090 site = capture(site); 3091 sym = selectSym(tree, sitesym, site, env, resultInfo); 3092 } 3093 boolean varArgs = env.info.lastResolveVarargs(); 3094 tree.sym = sym; 3095 3096 if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) { 3097 while (site.hasTag(TYPEVAR)) site = site.getUpperBound(); 3098 site = capture(site); 3099 } 3100 3101 // If that symbol is a variable, ... 3102 if (sym.kind == VAR) { 3103 VarSymbol v = (VarSymbol)sym; 3104 3105 // ..., evaluate its initializer, if it has one, and check for 3106 // illegal forward reference. 3107 checkInit(tree, env, v, true); 3108 3109 // If we are expecting a variable (as opposed to a value), check 3110 // that the variable is assignable in the current environment. 3111 if (pkind() == VAR) 3112 checkAssignable(tree.pos(), v, tree.selected, env); 3113 } 3114 3115 if (sitesym != null && 3116 sitesym.kind == VAR && 3117 ((VarSymbol)sitesym).isResourceVariable() && 3118 sym.kind == MTH && 3119 sym.name.equals(names.close) && 3120 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) && 3121 env.info.lint.isEnabled(LintCategory.TRY)) { 3122 log.warning(LintCategory.TRY, tree, "try.explicit.close.call"); 3123 } 3124 3125 // Disallow selecting a type from an expression 3126 if (isType(sym) && (sitesym==null || (sitesym.kind&(TYP|PCK)) == 0)) { 3127 tree.type = check(tree.selected, pt(), 3128 sitesym == null ? VAL : sitesym.kind, new ResultInfo(TYP|PCK, pt())); 3129 } 3130 3131 if (isType(sitesym)) { 3132 if (sym.name == names._this) { 3133 // If `C' is the currently compiled class, check that 3134 // C.this' does not appear in a call to a super(...) 3135 if (env.info.isSelfCall && 3136 site.tsym == env.enclClass.sym) { 3137 chk.earlyRefError(tree.pos(), sym); 3138 } 3139 } else { 3140 // Check if type-qualified fields or methods are static (JLS) 3141 if ((sym.flags() & STATIC) == 0 && 3142 !env.next.tree.hasTag(REFERENCE) && 3143 sym.name != names._super && 3144 (sym.kind == VAR || sym.kind == MTH)) { 3145 rs.accessBase(rs.new StaticError(sym), 3146 tree.pos(), site, sym.name, true); 3147 } 3148 } 3149 } else if (sym.kind != ERR && (sym.flags() & STATIC) != 0 && sym.name != names._class) { 3150 // If the qualified item is not a type and the selected item is static, report 3151 // a warning. Make allowance for the class of an array type e.g. Object[].class) 3152 chk.warnStatic(tree, "static.not.qualified.by.type", Kinds.kindName(sym.kind), sym.owner); 3153 } 3154 3155 // If we are selecting an instance member via a `super', ... 3156 if (env.info.selectSuper && (sym.flags() & STATIC) == 0) { 3157 3158 // Check that super-qualified symbols are not abstract (JLS) 3159 rs.checkNonAbstract(tree.pos(), sym); 3160 3161 if (site.isRaw()) { 3162 // Determine argument types for site. 3163 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym); 3164 if (site1 != null) site = site1; 3165 } 3166 } 3167 3168 env.info.selectSuper = selectSuperPrev; 3169 result = checkId(tree, site, sym, env, resultInfo); 3170 } 3171 //where 3172 /** Determine symbol referenced by a Select expression, 3173 * 3174 * @param tree The select tree. 3175 * @param site The type of the selected expression, 3176 * @param env The current environment. 3177 * @param resultInfo The current result. 3178 */ 3179 private Symbol selectSym(JCFieldAccess tree, 3180 Symbol location, 3181 Type site, 3182 Env<AttrContext> env, 3183 ResultInfo resultInfo) { 3184 DiagnosticPosition pos = tree.pos(); 3185 Name name = tree.name; 3186 switch (site.getTag()) { 3187 case PACKAGE: 3188 return rs.accessBase( 3189 rs.findIdentInPackage(env, site.tsym, name, resultInfo.pkind), 3190 pos, location, site, name, true); 3191 case ARRAY: 3192 case CLASS: 3193 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) { 3194 return rs.resolveQualifiedMethod( 3195 pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments()); 3196 } else if (name == names._this || name == names._super) { 3197 return rs.resolveSelf(pos, env, site.tsym, name); 3198 } else if (name == names._class) { 3199 // In this case, we have already made sure in 3200 // visitSelect that qualifier expression is a type. 3201 Type t = syms.classType; 3202 List<Type> typeargs = allowGenerics 3203 ? List.of(types.erasure(site)) 3204 : List.<Type>nil(); 3205 t = new ClassType(t.getEnclosingType(), typeargs, t.tsym); 3206 return new VarSymbol( 3207 STATIC | PUBLIC | FINAL, names._class, t, site.tsym); 3208 } else { 3209 // We are seeing a plain identifier as selector. 3210 Symbol sym = rs.findIdentInType(env, site, name, resultInfo.pkind); 3211 if ((resultInfo.pkind & ERRONEOUS) == 0) 3212 sym = rs.accessBase(sym, pos, location, site, name, true); 3213 return sym; 3214 } 3215 case WILDCARD: 3216 throw new AssertionError(tree); 3217 case TYPEVAR: 3218 // Normally, site.getUpperBound() shouldn't be null. 3219 // It should only happen during memberEnter/attribBase 3220 // when determining the super type which *must* beac 3221 // done before attributing the type variables. In 3222 // other words, we are seeing this illegal program: 3223 // class B<T> extends A<T.foo> {} 3224 Symbol sym = (site.getUpperBound() != null) 3225 ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo) 3226 : null; 3227 if (sym == null) { 3228 log.error(pos, "type.var.cant.be.deref"); 3229 return syms.errSymbol; 3230 } else { 3231 Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ? 3232 rs.new AccessError(env, site, sym) : 3233 sym; 3234 rs.accessBase(sym2, pos, location, site, name, true); 3235 return sym; 3236 } 3237 case ERROR: 3238 // preserve identifier names through errors 3239 return types.createErrorType(name, site.tsym, site).tsym; 3240 default: 3241 // The qualifier expression is of a primitive type -- only 3242 // .class is allowed for these. 3243 if (name == names._class) { 3244 // In this case, we have already made sure in Select that 3245 // qualifier expression is a type. 3246 Type t = syms.classType; 3247 Type arg = types.boxedClass(site).type; 3248 t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym); 3249 return new VarSymbol( 3250 STATIC | PUBLIC | FINAL, names._class, t, site.tsym); 3251 } else { 3252 log.error(pos, "cant.deref", site); 3253 return syms.errSymbol; 3254 } 3255 } 3256 } 3257 3258 /** Determine type of identifier or select expression and check that 3259 * (1) the referenced symbol is not deprecated 3260 * (2) the symbol's type is safe (@see checkSafe) 3261 * (3) if symbol is a variable, check that its type and kind are 3262 * compatible with the prototype and protokind. 3263 * (4) if symbol is an instance field of a raw type, 3264 * which is being assigned to, issue an unchecked warning if its 3265 * type changes under erasure. 3266 * (5) if symbol is an instance method of a raw type, issue an 3267 * unchecked warning if its argument types change under erasure. 3268 * If checks succeed: 3269 * If symbol is a constant, return its constant type 3270 * else if symbol is a method, return its result type 3271 * otherwise return its type. 3272 * Otherwise return errType. 3273 * 3274 * @param tree The syntax tree representing the identifier 3275 * @param site If this is a select, the type of the selected 3276 * expression, otherwise the type of the current class. 3277 * @param sym The symbol representing the identifier. 3278 * @param env The current environment. 3279 * @param resultInfo The expected result 3280 */ 3281 Type checkId(JCTree tree, 3282 Type site, 3283 Symbol sym, 3284 Env<AttrContext> env, 3285 ResultInfo resultInfo) { 3286 return (resultInfo.pt.hasTag(FORALL) || resultInfo.pt.hasTag(METHOD)) ? 3287 checkMethodId(tree, site, sym, env, resultInfo) : 3288 checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo); 3289 } 3290 3291 Type checkMethodId(JCTree tree, 3292 Type site, 3293 Symbol sym, 3294 Env<AttrContext> env, 3295 ResultInfo resultInfo) { 3296 boolean isPolymorhicSignature = 3297 sym.kind == MTH && ((MethodSymbol)sym.baseSymbol()).isSignaturePolymorphic(types); 3298 return isPolymorhicSignature ? 3299 checkSigPolyMethodId(tree, site, sym, env, resultInfo) : 3300 checkMethodIdInternal(tree, site, sym, env, resultInfo); 3301 } 3302 3303 Type checkSigPolyMethodId(JCTree tree, 3304 Type site, 3305 Symbol sym, 3306 Env<AttrContext> env, 3307 ResultInfo resultInfo) { 3308 //recover original symbol for signature polymorphic methods 3309 checkMethodIdInternal(tree, site, sym.baseSymbol(), env, resultInfo); 3310 env.info.pendingResolutionPhase = Resolve.MethodResolutionPhase.BASIC; 3311 return sym.type; 3312 } 3313 3314 Type checkMethodIdInternal(JCTree tree, 3315 Type site, 3316 Symbol sym, 3317 Env<AttrContext> env, 3318 ResultInfo resultInfo) { 3319 Type pt = resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, sym, env.info.pendingResolutionPhase)); 3320 Type owntype = checkIdInternal(tree, site, sym, pt, env, resultInfo); 3321 resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase)); 3322 return owntype; 3323 } 3324 3325 Type checkIdInternal(JCTree tree, 3326 Type site, 3327 Symbol sym, 3328 Type pt, 3329 Env<AttrContext> env, 3330 ResultInfo resultInfo) { 3331 if (pt.isErroneous()) { 3332 return types.createErrorType(site); 3333 } 3334 Type owntype; // The computed type of this identifier occurrence. 3335 switch (sym.kind) { 3336 case TYP: 3337 // For types, the computed type equals the symbol's type, 3338 // except for two situations: 3339 owntype = sym.type; 3340 if (owntype.hasTag(CLASS)) { 3341 chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym); 3342 Type ownOuter = owntype.getEnclosingType(); 3343 3344 // (a) If the symbol's type is parameterized, erase it 3345 // because no type parameters were given. 3346 // We recover generic outer type later in visitTypeApply. 3347 if (owntype.tsym.type.getTypeArguments().nonEmpty()) { 3348 owntype = types.erasure(owntype); 3349 } 3350 3351 // (b) If the symbol's type is an inner class, then 3352 // we have to interpret its outer type as a superclass 3353 // of the site type. Example: 3354 // 3355 // class Tree<A> { class Visitor { ... } } 3356 // class PointTree extends Tree<Point> { ... } 3357 // ...PointTree.Visitor... 3358 // 3359 // Then the type of the last expression above is 3360 // Tree<Point>.Visitor. 3361 else if (ownOuter.hasTag(CLASS) && site != ownOuter) { 3362 Type normOuter = site; 3363 if (normOuter.hasTag(CLASS)) { 3364 normOuter = types.asEnclosingSuper(site, ownOuter.tsym); 3365 if (site.getKind() == TypeKind.ANNOTATED) { 3366 // Propagate any type annotations. 3367 // TODO: should asEnclosingSuper do this? 3368 // Note that the type annotations in site will be updated 3369 // by annotateType. Therefore, modify site instead 3370 // of creating a new AnnotatedType. 3371 ((AnnotatedType)site).underlyingType = normOuter; 3372 normOuter = site; 3373 } 3374 } 3375 if (normOuter == null) // perhaps from an import 3376 normOuter = types.erasure(ownOuter); 3377 if (normOuter != ownOuter) 3378 owntype = new ClassType( 3379 normOuter, List.<Type>nil(), owntype.tsym); 3380 } 3381 } 3382 break; 3383 case VAR: 3384 VarSymbol v = (VarSymbol)sym; 3385 // Test (4): if symbol is an instance field of a raw type, 3386 // which is being assigned to, issue an unchecked warning if 3387 // its type changes under erasure. 3388 if (allowGenerics && 3389 resultInfo.pkind == VAR && 3390 v.owner.kind == TYP && 3391 (v.flags() & STATIC) == 0 && 3392 (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) { 3393 Type s = types.asOuterSuper(site, v.owner); 3394 if (s != null && 3395 s.isRaw() && 3396 !types.isSameType(v.type, v.erasure(types))) { 3397 chk.warnUnchecked(tree.pos(), 3398 "unchecked.assign.to.var", 3399 v, s); 3400 } 3401 } 3402 // The computed type of a variable is the type of the 3403 // variable symbol, taken as a member of the site type. 3404 owntype = (sym.owner.kind == TYP && 3405 sym.name != names._this && sym.name != names._super) 3406 ? types.memberType(site, sym) 3407 : sym.type; 3408 3409 // If the variable is a constant, record constant value in 3410 // computed type. 3411 if (v.getConstValue() != null && isStaticReference(tree)) 3412 owntype = owntype.constType(v.getConstValue()); 3413 3414 if (resultInfo.pkind == VAL) { 3415 owntype = capture(owntype); // capture "names as expressions" 3416 } 3417 break; 3418 case MTH: { 3419 owntype = checkMethod(site, sym, 3420 new ResultInfo(VAL, resultInfo.pt.getReturnType(), resultInfo.checkContext), 3421 env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(), 3422 resultInfo.pt.getTypeArguments()); 3423 break; 3424 } 3425 case PCK: case ERR: 3426 owntype = sym.type; 3427 break; 3428 default: 3429 throw new AssertionError("unexpected kind: " + sym.kind + 3430 " in tree " + tree); 3431 } 3432 3433 // Test (1): emit a `deprecation' warning if symbol is deprecated. 3434 // (for constructors, the error was given when the constructor was 3435 // resolved) 3436 3437 if (sym.name != names.init) { 3438 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym); 3439 chk.checkSunAPI(tree.pos(), sym); 3440 chk.checkProfile(tree.pos(), sym); 3441 } 3442 3443 // Test (3): if symbol is a variable, check that its type and 3444 // kind are compatible with the prototype and protokind. 3445 return check(tree, owntype, sym.kind, resultInfo); 3446 } 3447 3448 /** Check that variable is initialized and evaluate the variable's 3449 * initializer, if not yet done. Also check that variable is not 3450 * referenced before it is defined. 3451 * @param tree The tree making up the variable reference. 3452 * @param env The current environment. 3453 * @param v The variable's symbol. 3454 */ 3455 private void checkInit(JCTree tree, 3456 Env<AttrContext> env, 3457 VarSymbol v, 3458 boolean onlyWarning) { 3459 // System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " + 3460 // tree.pos + " " + v.pos + " " + 3461 // Resolve.isStatic(env));//DEBUG 3462 3463 // A forward reference is diagnosed if the declaration position 3464 // of the variable is greater than the current tree position 3465 // and the tree and variable definition occur in the same class 3466 // definition. Note that writes don't count as references. 3467 // This check applies only to class and instance 3468 // variables. Local variables follow different scope rules, 3469 // and are subject to definite assignment checking. 3470 if ((env.info.enclVar == v || v.pos > tree.pos) && 3471 v.owner.kind == TYP && 3472 canOwnInitializer(owner(env)) && 3473 v.owner == env.info.scope.owner.enclClass() && 3474 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) && 3475 (!env.tree.hasTag(ASSIGN) || 3476 TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) { 3477 String suffix = (env.info.enclVar == v) ? 3478 "self.ref" : "forward.ref"; 3479 if (!onlyWarning || isStaticEnumField(v)) { 3480 log.error(tree.pos(), "illegal." + suffix); 3481 } else if (useBeforeDeclarationWarning) { 3482 log.warning(tree.pos(), suffix, v); 3483 } 3484 } 3485 3486 v.getConstValue(); // ensure initializer is evaluated 3487 3488 checkEnumInitializer(tree, env, v); 3489 } 3490 3491 /** 3492 * Check for illegal references to static members of enum. In 3493 * an enum type, constructors and initializers may not 3494 * reference its static members unless they are constant. 3495 * 3496 * @param tree The tree making up the variable reference. 3497 * @param env The current environment. 3498 * @param v The variable's symbol. 3499 * @jls section 8.9 Enums 3500 */ 3501 private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) { 3502 // JLS: 3503 // 3504 // "It is a compile-time error to reference a static field 3505 // of an enum type that is not a compile-time constant 3506 // (15.28) from constructors, instance initializer blocks, 3507 // or instance variable initializer expressions of that 3508 // type. It is a compile-time error for the constructors, 3509 // instance initializer blocks, or instance variable 3510 // initializer expressions of an enum constant e to refer 3511 // to itself or to an enum constant of the same type that 3512 // is declared to the right of e." 3513 if (isStaticEnumField(v)) { 3514 ClassSymbol enclClass = env.info.scope.owner.enclClass(); 3515 3516 if (enclClass == null || enclClass.owner == null) 3517 return; 3518 3519 // See if the enclosing class is the enum (or a 3520 // subclass thereof) declaring v. If not, this 3521 // reference is OK. 3522 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type)) 3523 return; 3524 3525 // If the reference isn't from an initializer, then 3526 // the reference is OK. 3527 if (!Resolve.isInitializer(env)) 3528 return; 3529 3530 log.error(tree.pos(), "illegal.enum.static.ref"); 3531 } 3532 } 3533 3534 /** Is the given symbol a static, non-constant field of an Enum? 3535 * Note: enum literals should not be regarded as such 3536 */ 3537 private boolean isStaticEnumField(VarSymbol v) { 3538 return Flags.isEnum(v.owner) && 3539 Flags.isStatic(v) && 3540 !Flags.isConstant(v) && 3541 v.name != names._class; 3542 } 3543 3544 /** Can the given symbol be the owner of code which forms part 3545 * if class initialization? This is the case if the symbol is 3546 * a type or field, or if the symbol is the synthetic method. 3547 * owning a block. 3548 */ 3549 private boolean canOwnInitializer(Symbol sym) { 3550 return 3551 (sym.kind & (VAR | TYP)) != 0 || 3552 (sym.kind == MTH && (sym.flags() & BLOCK) != 0); 3553 } 3554 3555 Warner noteWarner = new Warner(); 3556 3557 /** 3558 * Check that method arguments conform to its instantiation. 3559 **/ 3560 public Type checkMethod(Type site, 3561 Symbol sym, 3562 ResultInfo resultInfo, 3563 Env<AttrContext> env, 3564 final List<JCExpression> argtrees, 3565 List<Type> argtypes, 3566 List<Type> typeargtypes) { 3567 // Test (5): if symbol is an instance method of a raw type, issue 3568 // an unchecked warning if its argument types change under erasure. 3569 if (allowGenerics && 3570 (sym.flags() & STATIC) == 0 && 3571 (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) { 3572 Type s = types.asOuterSuper(site, sym.owner); 3573 if (s != null && s.isRaw() && 3574 !types.isSameTypes(sym.type.getParameterTypes(), 3575 sym.erasure(types).getParameterTypes())) { 3576 chk.warnUnchecked(env.tree.pos(), 3577 "unchecked.call.mbr.of.raw.type", 3578 sym, s); 3579 } 3580 } 3581 3582 if (env.info.defaultSuperCallSite != null) { 3583 for (Type sup : types.interfaces(env.enclClass.type).prepend(types.supertype((env.enclClass.type)))) { 3584 if (!sup.tsym.isSubClass(sym.enclClass(), types) || 3585 types.isSameType(sup, env.info.defaultSuperCallSite)) continue; 3586 List<MethodSymbol> icand_sup = 3587 types.interfaceCandidates(sup, (MethodSymbol)sym); 3588 if (icand_sup.nonEmpty() && 3589 icand_sup.head != sym && 3590 icand_sup.head.overrides(sym, icand_sup.head.enclClass(), types, true)) { 3591 log.error(env.tree.pos(), "illegal.default.super.call", env.info.defaultSuperCallSite, 3592 diags.fragment("overridden.default", sym, sup)); 3593 break; 3594 } 3595 } 3596 env.info.defaultSuperCallSite = null; 3597 } 3598 3599 if (sym.isStatic() && site.isInterface() && env.tree.hasTag(APPLY)) { 3600 JCMethodInvocation app = (JCMethodInvocation)env.tree; 3601 if (app.meth.hasTag(SELECT) && 3602 !TreeInfo.isStaticSelector(((JCFieldAccess)app.meth).selected, names)) { 3603 log.error(env.tree.pos(), "illegal.static.intf.meth.call", site); 3604 } 3605 } 3606 3607 // Compute the identifier's instantiated type. 3608 // For methods, we need to compute the instance type by 3609 // Resolve.instantiate from the symbol's type as well as 3610 // any type arguments and value arguments. 3611 noteWarner.clear(); 3612 try { 3613 Type owntype = rs.checkMethod( 3614 env, 3615 site, 3616 sym, 3617 resultInfo, 3618 argtypes, 3619 typeargtypes, 3620 noteWarner); 3621 3622 return chk.checkMethod(owntype, sym, env, argtrees, argtypes, env.info.lastResolveVarargs(), 3623 noteWarner.hasNonSilentLint(LintCategory.UNCHECKED)); 3624 } catch (Infer.InferenceException ex) { 3625 //invalid target type - propagate exception outwards or report error 3626 //depending on the current check context 3627 resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic()); 3628 return types.createErrorType(site); 3629 } catch (Resolve.InapplicableMethodException ex) { 3630 Assert.error(ex.getDiagnostic().getMessage(Locale.getDefault())); 3631 return null; 3632 } 3633 } 3634 3635 public void visitLiteral(JCLiteral tree) { 3636 result = check( 3637 tree, litType(tree.typetag).constType(tree.value), VAL, resultInfo); 3638 } 3639 //where 3640 /** Return the type of a literal with given type tag. 3641 */ 3642 Type litType(TypeTag tag) { 3643 return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()]; 3644 } 3645 3646 public void visitTypeIdent(JCPrimitiveTypeTree tree) { 3647 result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], TYP, resultInfo); 3648 } 3649 3650 public void visitTypeArray(JCArrayTypeTree tree) { 3651 Type etype = attribType(tree.elemtype, env); 3652 Type type = new ArrayType(etype, syms.arrayClass); 3653 result = check(tree, type, TYP, resultInfo); 3654 } 3655 3656 /** Visitor method for parameterized types. 3657 * Bound checking is left until later, since types are attributed 3658 * before supertype structure is completely known 3659 */ 3660 public void visitTypeApply(JCTypeApply tree) { 3661 Type owntype = types.createErrorType(tree.type); 3662 3663 // Attribute functor part of application and make sure it's a class. 3664 Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env)); 3665 3666 // Attribute type parameters 3667 List<Type> actuals = attribTypes(tree.arguments, env); 3668 3669 if (clazztype.hasTag(CLASS)) { 3670 List<Type> formals = clazztype.tsym.type.getTypeArguments(); 3671 if (actuals.isEmpty()) //diamond 3672 actuals = formals; 3673 3674 if (actuals.length() == formals.length()) { 3675 List<Type> a = actuals; 3676 List<Type> f = formals; 3677 while (a.nonEmpty()) { 3678 a.head = a.head.withTypeVar(f.head); 3679 a = a.tail; 3680 f = f.tail; 3681 } 3682 // Compute the proper generic outer 3683 Type clazzOuter = clazztype.getEnclosingType(); 3684 if (clazzOuter.hasTag(CLASS)) { 3685 Type site; 3686 JCExpression clazz = TreeInfo.typeIn(tree.clazz); 3687 if (clazz.hasTag(IDENT)) { 3688 site = env.enclClass.sym.type; 3689 } else if (clazz.hasTag(SELECT)) { 3690 site = ((JCFieldAccess) clazz).selected.type; 3691 } else throw new AssertionError(""+tree); 3692 if (clazzOuter.hasTag(CLASS) && site != clazzOuter) { 3693 if (site.hasTag(CLASS)) 3694 site = types.asOuterSuper(site, clazzOuter.tsym); 3695 if (site == null) 3696 site = types.erasure(clazzOuter); 3697 clazzOuter = site; 3698 } 3699 } 3700 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym); 3701 } else { 3702 if (formals.length() != 0) { 3703 log.error(tree.pos(), "wrong.number.type.args", 3704 Integer.toString(formals.length())); 3705 } else { 3706 log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym); 3707 } 3708 owntype = types.createErrorType(tree.type); 3709 } 3710 } 3711 result = check(tree, owntype, TYP, resultInfo); 3712 } 3713 3714 public void visitTypeUnion(JCTypeUnion tree) { 3715 ListBuffer<Type> multicatchTypes = ListBuffer.lb(); 3716 ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed 3717 for (JCExpression typeTree : tree.alternatives) { 3718 Type ctype = attribType(typeTree, env); 3719 ctype = chk.checkType(typeTree.pos(), 3720 chk.checkClassType(typeTree.pos(), ctype), 3721 syms.throwableType); 3722 if (!ctype.isErroneous()) { 3723 //check that alternatives of a union type are pairwise 3724 //unrelated w.r.t. subtyping 3725 if (chk.intersects(ctype, multicatchTypes.toList())) { 3726 for (Type t : multicatchTypes) { 3727 boolean sub = types.isSubtype(ctype, t); 3728 boolean sup = types.isSubtype(t, ctype); 3729 if (sub || sup) { 3730 //assume 'a' <: 'b' 3731 Type a = sub ? ctype : t; 3732 Type b = sub ? t : ctype; 3733 log.error(typeTree.pos(), "multicatch.types.must.be.disjoint", a, b); 3734 } 3735 } 3736 } 3737 multicatchTypes.append(ctype); 3738 if (all_multicatchTypes != null) 3739 all_multicatchTypes.append(ctype); 3740 } else { 3741 if (all_multicatchTypes == null) { 3742 all_multicatchTypes = ListBuffer.lb(); 3743 all_multicatchTypes.appendList(multicatchTypes); 3744 } 3745 all_multicatchTypes.append(ctype); 3746 } 3747 } 3748 Type t = check(tree, types.lub(multicatchTypes.toList()), TYP, resultInfo); 3749 if (t.hasTag(CLASS)) { 3750 List<Type> alternatives = 3751 ((all_multicatchTypes == null) ? multicatchTypes : all_multicatchTypes).toList(); 3752 t = new UnionClassType((ClassType) t, alternatives); 3753 } 3754 tree.type = result = t; 3755 } 3756 3757 public void visitTypeIntersection(JCTypeIntersection tree) { 3758 attribTypes(tree.bounds, env); 3759 tree.type = result = checkIntersection(tree, tree.bounds); 3760 } 3761 3762 public void visitTypeParameter(JCTypeParameter tree) { 3763 TypeVar typeVar = (TypeVar) tree.type; 3764 3765 if (tree.annotations != null && tree.annotations.nonEmpty()) { 3766 AnnotatedType antype = new AnnotatedType(typeVar); 3767 annotateType(antype, tree.annotations); 3768 tree.type = antype; 3769 } 3770 3771 if (!typeVar.bound.isErroneous()) { 3772 //fixup type-parameter bound computed in 'attribTypeVariables' 3773 typeVar.bound = checkIntersection(tree, tree.bounds); 3774 } 3775 } 3776 3777 Type checkIntersection(JCTree tree, List<JCExpression> bounds) { 3778 Set<Type> boundSet = new HashSet<Type>(); 3779 if (bounds.nonEmpty()) { 3780 // accept class or interface or typevar as first bound. 3781 bounds.head.type = checkBase(bounds.head.type, bounds.head, env, false, false, false); 3782 boundSet.add(types.erasure(bounds.head.type)); 3783 if (bounds.head.type.isErroneous()) { 3784 return bounds.head.type; 3785 } 3786 else if (bounds.head.type.hasTag(TYPEVAR)) { 3787 // if first bound was a typevar, do not accept further bounds. 3788 if (bounds.tail.nonEmpty()) { 3789 log.error(bounds.tail.head.pos(), 3790 "type.var.may.not.be.followed.by.other.bounds"); 3791 return bounds.head.type; 3792 } 3793 } else { 3794 // if first bound was a class or interface, accept only interfaces 3795 // as further bounds. 3796 for (JCExpression bound : bounds.tail) { 3797 bound.type = checkBase(bound.type, bound, env, false, true, false); 3798 if (bound.type.isErroneous()) { 3799 bounds = List.of(bound); 3800 } 3801 else if (bound.type.hasTag(CLASS)) { 3802 chk.checkNotRepeated(bound.pos(), types.erasure(bound.type), boundSet); 3803 } 3804 } 3805 } 3806 } 3807 3808 if (bounds.length() == 0) { 3809 return syms.objectType; 3810 } else if (bounds.length() == 1) { 3811 return bounds.head.type; 3812 } else { 3813 Type owntype = types.makeCompoundType(TreeInfo.types(bounds)); 3814 if (tree.hasTag(TYPEINTERSECTION)) { 3815 ((IntersectionClassType)owntype).intersectionKind = 3816 IntersectionClassType.IntersectionKind.EXPLICIT; 3817 } 3818 // ... the variable's bound is a class type flagged COMPOUND 3819 // (see comment for TypeVar.bound). 3820 // In this case, generate a class tree that represents the 3821 // bound class, ... 3822 JCExpression extending; 3823 List<JCExpression> implementing; 3824 if (!bounds.head.type.isInterface()) { 3825 extending = bounds.head; 3826 implementing = bounds.tail; 3827 } else { 3828 extending = null; 3829 implementing = bounds; 3830 } 3831 JCClassDecl cd = make.at(tree).ClassDef( 3832 make.Modifiers(PUBLIC | ABSTRACT), 3833 names.empty, List.<JCTypeParameter>nil(), 3834 extending, implementing, List.<JCTree>nil()); 3835 3836 ClassSymbol c = (ClassSymbol)owntype.tsym; 3837 Assert.check((c.flags() & COMPOUND) != 0); 3838 cd.sym = c; 3839 c.sourcefile = env.toplevel.sourcefile; 3840 3841 // ... and attribute the bound class 3842 c.flags_field |= UNATTRIBUTED; 3843 Env<AttrContext> cenv = enter.classEnv(cd, env); 3844 enter.typeEnvs.put(c, cenv); 3845 attribClass(c); 3846 return owntype; 3847 } 3848 } 3849 3850 public void visitWildcard(JCWildcard tree) { 3851 //- System.err.println("visitWildcard("+tree+");");//DEBUG 3852 Type type = (tree.kind.kind == BoundKind.UNBOUND) 3853 ? syms.objectType 3854 : attribType(tree.inner, env); 3855 result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type), 3856 tree.kind.kind, 3857 syms.boundClass), 3858 TYP, resultInfo); 3859 } 3860 3861 public void visitAnnotation(JCAnnotation tree) { 3862 log.error(tree.pos(), "annotation.not.valid.for.type", pt()); 3863 result = tree.type = syms.errType; 3864 } 3865 3866 public void visitAnnotatedType(JCAnnotatedType tree) { 3867 Type underlyingType = attribType(tree.getUnderlyingType(), env); 3868 this.attribAnnotationTypes(tree.annotations, env); 3869 AnnotatedType antype = new AnnotatedType(underlyingType); 3870 annotateType(antype, tree.annotations); 3871 result = tree.type = antype; 3872 } 3873 3874 /** 3875 * Apply the annotations to the particular type. 3876 */ 3877 public void annotateType(final AnnotatedType type, final List<JCAnnotation> annotations) { 3878 if (annotations.isEmpty()) 3879 return; 3880 annotate.typeAnnotation(new Annotate.Annotator() { 3881 @Override 3882 public String toString() { 3883 return "annotate " + annotations + " onto " + type; 3884 } 3885 @Override 3886 public void enterAnnotation() { 3887 List<Attribute.TypeCompound> compounds = fromAnnotations(annotations); 3888 type.typeAnnotations = compounds; 3889 } 3890 }); 3891 } 3892 3893 private static List<Attribute.TypeCompound> fromAnnotations(List<JCAnnotation> annotations) { 3894 if (annotations.isEmpty()) 3895 return List.nil(); 3896 3897 ListBuffer<Attribute.TypeCompound> buf = ListBuffer.lb(); 3898 for (JCAnnotation anno : annotations) { 3899 buf.append((Attribute.TypeCompound) anno.attribute); 3900 } 3901 return buf.toList(); 3902 } 3903 3904 public void visitErroneous(JCErroneous tree) { 3905 if (tree.errs != null) 3906 for (JCTree err : tree.errs) 3907 attribTree(err, env, new ResultInfo(ERR, pt())); 3908 result = tree.type = syms.errType; 3909 } 3910 3911 /** Default visitor method for all other trees. 3912 */ 3913 public void visitTree(JCTree tree) { 3914 throw new AssertionError(); 3915 } 3916 3917 /** 3918 * Attribute an env for either a top level tree or class declaration. 3919 */ 3920 public void attrib(Env<AttrContext> env) { 3921 if (env.tree.hasTag(TOPLEVEL)) 3922 attribTopLevel(env); 3923 else 3924 attribClass(env.tree.pos(), env.enclClass.sym); 3925 } 3926 3927 /** 3928 * Attribute a top level tree. These trees are encountered when the 3929 * package declaration has annotations. 3930 */ 3931 public void attribTopLevel(Env<AttrContext> env) { 3932 JCCompilationUnit toplevel = env.toplevel; 3933 try { 3934 annotate.flush(); 3935 chk.validateAnnotations(toplevel.packageAnnotations, toplevel.packge); 3936 } catch (CompletionFailure ex) { 3937 chk.completionError(toplevel.pos(), ex); 3938 } 3939 } 3940 3941 /** Main method: attribute class definition associated with given class symbol. 3942 * reporting completion failures at the given position. 3943 * @param pos The source position at which completion errors are to be 3944 * reported. 3945 * @param c The class symbol whose definition will be attributed. 3946 */ 3947 public void attribClass(DiagnosticPosition pos, ClassSymbol c) { 3948 try { 3949 annotate.flush(); 3950 attribClass(c); 3951 } catch (CompletionFailure ex) { 3952 chk.completionError(pos, ex); 3953 } 3954 } 3955 3956 /** Attribute class definition associated with given class symbol. 3957 * @param c The class symbol whose definition will be attributed. 3958 */ 3959 void attribClass(ClassSymbol c) throws CompletionFailure { 3960 if (c.type.hasTag(ERROR)) return; 3961 3962 // Check for cycles in the inheritance graph, which can arise from 3963 // ill-formed class files. 3964 chk.checkNonCyclic(null, c.type); 3965 3966 Type st = types.supertype(c.type); 3967 if ((c.flags_field & Flags.COMPOUND) == 0) { 3968 // First, attribute superclass. 3969 if (st.hasTag(CLASS)) 3970 attribClass((ClassSymbol)st.tsym); 3971 3972 // Next attribute owner, if it is a class. 3973 if (c.owner.kind == TYP && c.owner.type.hasTag(CLASS)) 3974 attribClass((ClassSymbol)c.owner); 3975 } 3976 3977 // The previous operations might have attributed the current class 3978 // if there was a cycle. So we test first whether the class is still 3979 // UNATTRIBUTED. 3980 if ((c.flags_field & UNATTRIBUTED) != 0) { 3981 c.flags_field &= ~UNATTRIBUTED; 3982 3983 // Get environment current at the point of class definition. 3984 Env<AttrContext> env = enter.typeEnvs.get(c); 3985 3986 // The info.lint field in the envs stored in enter.typeEnvs is deliberately uninitialized, 3987 // because the annotations were not available at the time the env was created. Therefore, 3988 // we look up the environment chain for the first enclosing environment for which the 3989 // lint value is set. Typically, this is the parent env, but might be further if there 3990 // are any envs created as a result of TypeParameter nodes. 3991 Env<AttrContext> lintEnv = env; 3992 while (lintEnv.info.lint == null) 3993 lintEnv = lintEnv.next; 3994 3995 // Having found the enclosing lint value, we can initialize the lint value for this class 3996 env.info.lint = lintEnv.info.lint.augment(c.annotations, c.flags()); 3997 3998 Lint prevLint = chk.setLint(env.info.lint); 3999 JavaFileObject prev = log.useSource(c.sourcefile); 4000 ResultInfo prevReturnRes = env.info.returnResult; 4001 4002 try { 4003 env.info.returnResult = null; 4004 // java.lang.Enum may not be subclassed by a non-enum 4005 if (st.tsym == syms.enumSym && 4006 ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0)) 4007 log.error(env.tree.pos(), "enum.no.subclassing"); 4008 4009 // Enums may not be extended by source-level classes 4010 if (st.tsym != null && 4011 ((st.tsym.flags_field & Flags.ENUM) != 0) && 4012 ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0)) { 4013 log.error(env.tree.pos(), "enum.types.not.extensible"); 4014 } 4015 attribClassBody(env, c); 4016 4017 chk.checkDeprecatedAnnotation(env.tree.pos(), c); 4018 chk.checkClassOverrideEqualsAndHashIfNeeded(env.tree.pos(), c); 4019 } finally { 4020 env.info.returnResult = prevReturnRes; 4021 log.useSource(prev); 4022 chk.setLint(prevLint); 4023 } 4024 4025 } 4026 } 4027 4028 public void visitImport(JCImport tree) { 4029 // nothing to do 4030 } 4031 4032 /** Finish the attribution of a class. */ 4033 private void attribClassBody(Env<AttrContext> env, ClassSymbol c) { 4034 JCClassDecl tree = (JCClassDecl)env.tree; 4035 Assert.check(c == tree.sym); 4036 4037 // Validate annotations 4038 chk.validateAnnotations(tree.mods.annotations, c); 4039 4040 // Validate type parameters, supertype and interfaces. 4041 attribStats(tree.typarams, env); 4042 if (!c.isAnonymous()) { 4043 //already checked if anonymous 4044 chk.validate(tree.typarams, env); 4045 chk.validate(tree.extending, env); 4046 chk.validate(tree.implementing, env); 4047 } 4048 4049 // If this is a non-abstract class, check that it has no abstract 4050 // methods or unimplemented methods of an implemented interface. 4051 if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) { 4052 if (!relax) 4053 chk.checkAllDefined(tree.pos(), c); 4054 } 4055 4056 if ((c.flags() & ANNOTATION) != 0) { 4057 if (tree.implementing.nonEmpty()) 4058 log.error(tree.implementing.head.pos(), 4059 "cant.extend.intf.annotation"); 4060 if (tree.typarams.nonEmpty()) 4061 log.error(tree.typarams.head.pos(), 4062 "intf.annotation.cant.have.type.params"); 4063 4064 // If this annotation has a @Repeatable, validate 4065 Attribute.Compound repeatable = c.attribute(syms.repeatableType.tsym); 4066 if (repeatable != null) { 4067 // get diagnostic position for error reporting 4068 DiagnosticPosition cbPos = getDiagnosticPosition(tree, repeatable.type); 4069 Assert.checkNonNull(cbPos); 4070 4071 chk.validateRepeatable(c, repeatable, cbPos); 4072 } 4073 } else { 4074 // Check that all extended classes and interfaces 4075 // are compatible (i.e. no two define methods with same arguments 4076 // yet different return types). (JLS 8.4.6.3) 4077 chk.checkCompatibleSupertypes(tree.pos(), c.type); 4078 if (allowDefaultMethods) { 4079 chk.checkDefaultMethodClashes(tree.pos(), c.type); 4080 } 4081 } 4082 4083 // Check that class does not import the same parameterized interface 4084 // with two different argument lists. 4085 chk.checkClassBounds(tree.pos(), c.type); 4086 4087 tree.type = c.type; 4088 4089 for (List<JCTypeParameter> l = tree.typarams; 4090 l.nonEmpty(); l = l.tail) { 4091 Assert.checkNonNull(env.info.scope.lookup(l.head.name).scope); 4092 } 4093 4094 // Check that a generic class doesn't extend Throwable 4095 if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType)) 4096 log.error(tree.extending.pos(), "generic.throwable"); 4097 4098 // Check that all methods which implement some 4099 // method conform to the method they implement. 4100 chk.checkImplementations(tree); 4101 4102 //check that a resource implementing AutoCloseable cannot throw InterruptedException 4103 checkAutoCloseable(tree.pos(), env, c.type); 4104 4105 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) { 4106 // Attribute declaration 4107 attribStat(l.head, env); 4108 // Check that declarations in inner classes are not static (JLS 8.1.2) 4109 // Make an exception for static constants. 4110 if (c.owner.kind != PCK && 4111 ((c.flags() & STATIC) == 0 || c.name == names.empty) && 4112 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) { 4113 Symbol sym = null; 4114 if (l.head.hasTag(VARDEF)) sym = ((JCVariableDecl) l.head).sym; 4115 if (sym == null || 4116 sym.kind != VAR || 4117 ((VarSymbol) sym).getConstValue() == null) 4118 log.error(l.head.pos(), "icls.cant.have.static.decl", c); 4119 } 4120 } 4121 4122 // Check for cycles among non-initial constructors. 4123 chk.checkCyclicConstructors(tree); 4124 4125 // Check for cycles among annotation elements. 4126 chk.checkNonCyclicElements(tree); 4127 4128 // Check for proper use of serialVersionUID 4129 if (env.info.lint.isEnabled(LintCategory.SERIAL) && 4130 isSerializable(c) && 4131 (c.flags() & Flags.ENUM) == 0 && 4132 (c.flags() & ABSTRACT) == 0) { 4133 checkSerialVersionUID(tree, c); 4134 } 4135 4136 // Correctly organize the postions of the type annotations 4137 TypeAnnotations.organizeTypeAnnotationsBodies(this.syms, this.names, this.log, tree); 4138 4139 // Check type annotations applicability rules 4140 validateTypeAnnotations(tree); 4141 } 4142 // where 4143 /** get a diagnostic position for an attribute of Type t, or null if attribute missing */ 4144 private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) { 4145 for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) { 4146 if (types.isSameType(al.head.annotationType.type, t)) 4147 return al.head.pos(); 4148 } 4149 4150 return null; 4151 } 4152 4153 /** check if a class is a subtype of Serializable, if that is available. */ 4154 private boolean isSerializable(ClassSymbol c) { 4155 try { 4156 syms.serializableType.complete(); 4157 } 4158 catch (CompletionFailure e) { 4159 return false; 4160 } 4161 return types.isSubtype(c.type, syms.serializableType); 4162 } 4163 4164 /** Check that an appropriate serialVersionUID member is defined. */ 4165 private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) { 4166 4167 // check for presence of serialVersionUID 4168 Scope.Entry e = c.members().lookup(names.serialVersionUID); 4169 while (e.scope != null && e.sym.kind != VAR) e = e.next(); 4170 if (e.scope == null) { 4171 log.warning(LintCategory.SERIAL, 4172 tree.pos(), "missing.SVUID", c); 4173 return; 4174 } 4175 4176 // check that it is static final 4177 VarSymbol svuid = (VarSymbol)e.sym; 4178 if ((svuid.flags() & (STATIC | FINAL)) != 4179 (STATIC | FINAL)) 4180 log.warning(LintCategory.SERIAL, 4181 TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c); 4182 4183 // check that it is long 4184 else if (!svuid.type.hasTag(LONG)) 4185 log.warning(LintCategory.SERIAL, 4186 TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c); 4187 4188 // check constant 4189 else if (svuid.getConstValue() == null) 4190 log.warning(LintCategory.SERIAL, 4191 TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c); 4192 } 4193 4194 private Type capture(Type type) { 4195 //do not capture free types 4196 return resultInfo.checkContext.inferenceContext().free(type) ? 4197 type : types.capture(type); 4198 } 4199 4200 private void validateTypeAnnotations(JCTree tree) { 4201 tree.accept(typeAnnotationsValidator); 4202 } 4203 //where 4204 private final JCTree.Visitor typeAnnotationsValidator = 4205 new TreeScanner() { 4206 public void visitAnnotation(JCAnnotation tree) { 4207 if (tree.hasTag(TYPE_ANNOTATION)) { 4208 // TODO: It seems to WMD as if the annotation in 4209 // parameters, in particular also the recvparam, are never 4210 // of type JCTypeAnnotation and therefore never checked! 4211 // Luckily this check doesn't really do anything that isn't 4212 // also done elsewhere. 4213 chk.validateTypeAnnotation(tree, false); 4214 } 4215 super.visitAnnotation(tree); 4216 } 4217 public void visitTypeParameter(JCTypeParameter tree) { 4218 chk.validateTypeAnnotations(tree.annotations, true); 4219 scan(tree.bounds); 4220 // Don't call super. 4221 // This is needed because above we call validateTypeAnnotation with 4222 // false, which would forbid annotations on type parameters. 4223 // super.visitTypeParameter(tree); 4224 } 4225 public void visitMethodDef(JCMethodDecl tree) { 4226 // Static methods cannot have receiver type annotations. 4227 // In test case FailOver15.java, the nested method getString has 4228 // a null sym, because an unknown class is instantiated. 4229 // I would say it's safe to skip. 4230 if (tree.sym != null && (tree.sym.flags() & Flags.STATIC) != 0) { 4231 if (tree.recvparam != null) { 4232 // TODO: better error message. Is the pos good? 4233 log.error(tree.recvparam.pos(), "annotation.type.not.applicable"); 4234 } 4235 } 4236 if (tree.restype != null && tree.restype.type != null) { 4237 validateAnnotatedType(tree.restype, tree.restype.type); 4238 } 4239 super.visitMethodDef(tree); 4240 } 4241 public void visitVarDef(final JCVariableDecl tree) { 4242 if (tree.sym != null && tree.sym.type != null) 4243 validateAnnotatedType(tree, tree.sym.type); 4244 super.visitVarDef(tree); 4245 } 4246 public void visitTypeCast(JCTypeCast tree) { 4247 if (tree.clazz != null && tree.clazz.type != null) 4248 validateAnnotatedType(tree.clazz, tree.clazz.type); 4249 super.visitTypeCast(tree); 4250 } 4251 public void visitTypeTest(JCInstanceOf tree) { 4252 if (tree.clazz != null && tree.clazz.type != null) 4253 validateAnnotatedType(tree.clazz, tree.clazz.type); 4254 super.visitTypeTest(tree); 4255 } 4256 // TODO: what else do we need? 4257 // public void visitNewClass(JCNewClass tree) { 4258 // public void visitNewArray(JCNewArray tree) { 4259 4260 /* I would want to model this after 4261 * com.sun.tools.javac.comp.Check.Validator.visitSelectInternal(JCFieldAccess) 4262 * and override visitSelect and visitTypeApply. 4263 * However, we only set the annotated type in the top-level type 4264 * of the symbol. 4265 * Therefore, we need to override each individual location where a type 4266 * can occur. 4267 */ 4268 private void validateAnnotatedType(final JCTree errtree, final Type type) { 4269 if (type.getEnclosingType() != null && 4270 type != type.getEnclosingType()) { 4271 validateEnclosingAnnotatedType(errtree, type.getEnclosingType()); 4272 } 4273 for (Type targ : type.getTypeArguments()) { 4274 validateAnnotatedType(errtree, targ); 4275 } 4276 } 4277 private void validateEnclosingAnnotatedType(final JCTree errtree, final Type type) { 4278 validateAnnotatedType(errtree, type); 4279 if (type.tsym != null && 4280 type.tsym.isStatic() && 4281 type.getAnnotations().nonEmpty()) { 4282 // Enclosing static classes cannot have type annotations. 4283 log.error(errtree.pos(), "cant.annotate.static.class"); 4284 } 4285 } 4286 }; 4287 4288 // <editor-fold desc="post-attribution visitor"> 4289 4290 /** 4291 * Handle missing types/symbols in an AST. This routine is useful when 4292 * the compiler has encountered some errors (which might have ended up 4293 * terminating attribution abruptly); if the compiler is used in fail-over 4294 * mode (e.g. by an IDE) and the AST contains semantic errors, this routine 4295 * prevents NPE to be progagated during subsequent compilation steps. 4296 */ 4297 public void postAttr(JCTree tree) { 4298 new PostAttrAnalyzer().scan(tree); 4299 } 4300 4301 class PostAttrAnalyzer extends TreeScanner { 4302 4303 private void initTypeIfNeeded(JCTree that) { 4304 if (that.type == null) { 4305 that.type = syms.unknownType; 4306 } 4307 } 4308 4309 @Override 4310 public void scan(JCTree tree) { 4311 if (tree == null) return; 4312 if (tree instanceof JCExpression) { 4313 initTypeIfNeeded(tree); 4314 } 4315 super.scan(tree); 4316 } 4317 4318 @Override 4319 public void visitIdent(JCIdent that) { 4320 if (that.sym == null) { 4321 that.sym = syms.unknownSymbol; 4322 } 4323 } 4324 4325 @Override 4326 public void visitSelect(JCFieldAccess that) { 4327 if (that.sym == null) { 4328 that.sym = syms.unknownSymbol; 4329 } 4330 super.visitSelect(that); 4331 } 4332 4333 @Override 4334 public void visitClassDef(JCClassDecl that) { 4335 initTypeIfNeeded(that); 4336 if (that.sym == null) { 4337 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol); 4338 } 4339 super.visitClassDef(that); 4340 } 4341 4342 @Override 4343 public void visitMethodDef(JCMethodDecl that) { 4344 initTypeIfNeeded(that); 4345 if (that.sym == null) { 4346 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol); 4347 } 4348 super.visitMethodDef(that); 4349 } 4350 4351 @Override 4352 public void visitVarDef(JCVariableDecl that) { 4353 initTypeIfNeeded(that); 4354 if (that.sym == null) { 4355 that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol); 4356 that.sym.adr = 0; 4357 } 4358 super.visitVarDef(that); 4359 } 4360 4361 @Override 4362 public void visitNewClass(JCNewClass that) { 4363 if (that.constructor == null) { 4364 that.constructor = new MethodSymbol(0, names.init, syms.unknownType, syms.noSymbol); 4365 } 4366 if (that.constructorType == null) { 4367 that.constructorType = syms.unknownType; 4368 } 4369 super.visitNewClass(that); 4370 } 4371 4372 @Override 4373 public void visitAssignop(JCAssignOp that) { 4374 if (that.operator == null) 4375 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol); 4376 super.visitAssignop(that); 4377 } 4378 4379 @Override 4380 public void visitBinary(JCBinary that) { 4381 if (that.operator == null) 4382 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol); 4383 super.visitBinary(that); 4384 } 4385 4386 @Override 4387 public void visitUnary(JCUnary that) { 4388 if (that.operator == null) 4389 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol); 4390 super.visitUnary(that); 4391 } 4392 4393 @Override 4394 public void visitLambda(JCLambda that) { 4395 super.visitLambda(that); 4396 if (that.descriptorType == null) { 4397 that.descriptorType = syms.unknownType; 4398 } 4399 if (that.targets == null) { 4400 that.targets = List.nil(); 4401 } 4402 } 4403 4404 @Override 4405 public void visitReference(JCMemberReference that) { 4406 super.visitReference(that); 4407 if (that.sym == null) { 4408 that.sym = new MethodSymbol(0, names.empty, syms.unknownType, syms.noSymbol); 4409 } 4410 if (that.descriptorType == null) { 4411 that.descriptorType = syms.unknownType; 4412 } 4413 if (that.targets == null) { 4414 that.targets = List.nil(); 4415 } 4416 } 4417 } 4418 // </editor-fold> 4419 }