1 /* 2 * Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package com.sun.tools.javac.comp; 27 28 import java.util.*; 29 import java.util.Set; 30 31 import javax.lang.model.element.ElementKind; 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.InferenceContext.FreeTypeListener; 47 import com.sun.tools.javac.jvm.*; 48 import com.sun.tools.javac.jvm.Target; 49 import com.sun.tools.javac.tree.*; 50 import com.sun.tools.javac.tree.JCTree.*; 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, types)); 248 check(tree, inferenceContext.asInstType(found, types), 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 Type itype = attribExpr(initializer, env, type); 770 if (itype.constValue() != null) 771 return coerce(itype, type).constValue(); 772 else 773 return null; 774 } finally { 775 env.info.lint = prevLint; 776 log.useSource(prevSource); 777 } 778 } 779 780 /** Attribute type reference in an `extends' or `implements' clause. 781 * Supertypes of anonymous inner classes are usually already attributed. 782 * 783 * @param tree The tree making up the type reference. 784 * @param env The environment current at the reference. 785 * @param classExpected true if only a class is expected here. 786 * @param interfaceExpected true if only an interface is expected here. 787 */ 788 Type attribBase(JCTree tree, 789 Env<AttrContext> env, 790 boolean classExpected, 791 boolean interfaceExpected, 792 boolean checkExtensible) { 793 Type t = tree.type != null ? 794 tree.type : 795 attribType(tree, env); 796 return checkBase(t, tree, env, classExpected, interfaceExpected, checkExtensible); 797 } 798 Type checkBase(Type t, 799 JCTree tree, 800 Env<AttrContext> env, 801 boolean classExpected, 802 boolean interfaceExpected, 803 boolean checkExtensible) { 804 if (t.isErroneous()) 805 return t; 806 if (t.hasTag(TYPEVAR) && !classExpected && !interfaceExpected) { 807 // check that type variable is already visible 808 if (t.getUpperBound() == null) { 809 log.error(tree.pos(), "illegal.forward.ref"); 810 return types.createErrorType(t); 811 } 812 } else { 813 t = chk.checkClassType(tree.pos(), t, checkExtensible|!allowGenerics); 814 } 815 if (interfaceExpected && (t.tsym.flags() & INTERFACE) == 0) { 816 log.error(tree.pos(), "intf.expected.here"); 817 // return errType is necessary since otherwise there might 818 // be undetected cycles which cause attribution to loop 819 return types.createErrorType(t); 820 } else if (checkExtensible && 821 classExpected && 822 (t.tsym.flags() & INTERFACE) != 0) { 823 log.error(tree.pos(), "no.intf.expected.here"); 824 return types.createErrorType(t); 825 } 826 if (checkExtensible && 827 ((t.tsym.flags() & FINAL) != 0)) { 828 log.error(tree.pos(), 829 "cant.inherit.from.final", t.tsym); 830 } 831 chk.checkNonCyclic(tree.pos(), t); 832 return t; 833 } 834 835 Type attribIdentAsEnumType(Env<AttrContext> env, JCIdent id) { 836 Assert.check((env.enclClass.sym.flags() & ENUM) != 0); 837 id.type = env.info.scope.owner.type; 838 id.sym = env.info.scope.owner; 839 return id.type; 840 } 841 842 public void visitClassDef(JCClassDecl tree) { 843 // Local classes have not been entered yet, so we need to do it now: 844 if ((env.info.scope.owner.kind & (VAR | MTH)) != 0) 845 enter.classEnter(tree, env); 846 847 ClassSymbol c = tree.sym; 848 if (c == null) { 849 // exit in case something drastic went wrong during enter. 850 result = null; 851 } else { 852 // make sure class has been completed: 853 c.complete(); 854 855 // If this class appears as an anonymous class 856 // in a superclass constructor call where 857 // no explicit outer instance is given, 858 // disable implicit outer instance from being passed. 859 // (This would be an illegal access to "this before super"). 860 if (env.info.isSelfCall && 861 env.tree.hasTag(NEWCLASS) && 862 ((JCNewClass) env.tree).encl == null) 863 { 864 c.flags_field |= NOOUTERTHIS; 865 } 866 attribClass(tree.pos(), c); 867 result = tree.type = c.type; 868 } 869 } 870 871 public void visitMethodDef(JCMethodDecl tree) { 872 MethodSymbol m = tree.sym; 873 boolean isDefaultMethod = (m.flags() & DEFAULT) != 0; 874 875 Lint lint = env.info.lint.augment(m.annotations, m.flags()); 876 Lint prevLint = chk.setLint(lint); 877 MethodSymbol prevMethod = chk.setMethod(m); 878 try { 879 deferredLintHandler.flush(tree.pos()); 880 chk.checkDeprecatedAnnotation(tree.pos(), m); 881 882 // Create a new environment with local scope 883 // for attributing the method. 884 Env<AttrContext> localEnv = memberEnter.methodEnv(tree, env); 885 localEnv.info.lint = lint; 886 887 attribStats(tree.typarams, localEnv); 888 889 // If we override any other methods, check that we do so properly. 890 // JLS ??? 891 if (m.isStatic()) { 892 chk.checkHideClashes(tree.pos(), env.enclClass.type, m); 893 } else { 894 chk.checkOverrideClashes(tree.pos(), env.enclClass.type, m); 895 } 896 chk.checkOverride(tree, m); 897 898 if (isDefaultMethod && types.overridesObjectMethod(m.enclClass(), m)) { 899 log.error(tree, "default.overrides.object.member", m.name, Kinds.kindName(m.location()), m.location()); 900 } 901 902 // Enter all type parameters into the local method scope. 903 for (List<JCTypeParameter> l = tree.typarams; l.nonEmpty(); l = l.tail) 904 localEnv.info.scope.enterIfAbsent(l.head.type.tsym); 905 906 ClassSymbol owner = env.enclClass.sym; 907 if ((owner.flags() & ANNOTATION) != 0 && 908 tree.params.nonEmpty()) 909 log.error(tree.params.head.pos(), 910 "intf.annotation.members.cant.have.params"); 911 912 // Attribute all value parameters. 913 for (List<JCVariableDecl> l = tree.params; l.nonEmpty(); l = l.tail) { 914 attribStat(l.head, localEnv); 915 } 916 917 chk.checkVarargsMethodDecl(localEnv, tree); 918 919 // Check that type parameters are well-formed. 920 chk.validate(tree.typarams, localEnv); 921 922 // Check that result type is well-formed. 923 chk.validate(tree.restype, localEnv); 924 925 // annotation method checks 926 if ((owner.flags() & ANNOTATION) != 0) { 927 // annotation method cannot have throws clause 928 if (tree.thrown.nonEmpty()) { 929 log.error(tree.thrown.head.pos(), 930 "throws.not.allowed.in.intf.annotation"); 931 } 932 // annotation method cannot declare type-parameters 933 if (tree.typarams.nonEmpty()) { 934 log.error(tree.typarams.head.pos(), 935 "intf.annotation.members.cant.have.type.params"); 936 } 937 // validate annotation method's return type (could be an annotation type) 938 chk.validateAnnotationType(tree.restype); 939 // ensure that annotation method does not clash with members of Object/Annotation 940 chk.validateAnnotationMethod(tree.pos(), m); 941 942 if (tree.defaultValue != null) { 943 // if default value is an annotation, check it is a well-formed 944 // annotation value (e.g. no duplicate values, no missing values, etc.) 945 chk.validateAnnotationTree(tree.defaultValue); 946 } 947 } 948 949 for (List<JCExpression> l = tree.thrown; l.nonEmpty(); l = l.tail) 950 chk.checkType(l.head.pos(), l.head.type, syms.throwableType); 951 952 if (tree.body == null) { 953 // Empty bodies are only allowed for 954 // abstract, native, or interface methods, or for methods 955 // in a retrofit signature class. 956 if (isDefaultMethod || ((owner.flags() & INTERFACE) == 0 && 957 (tree.mods.flags & (ABSTRACT | NATIVE)) == 0) && 958 !relax) 959 log.error(tree.pos(), "missing.meth.body.or.decl.abstract"); 960 if (tree.defaultValue != null) { 961 if ((owner.flags() & ANNOTATION) == 0) 962 log.error(tree.pos(), 963 "default.allowed.in.intf.annotation.member"); 964 } 965 } else if ((tree.sym.flags() & ABSTRACT) != 0 && !isDefaultMethod) { 966 if ((owner.flags() & INTERFACE) != 0) { 967 log.error(tree.body.pos(), "intf.meth.cant.have.body"); 968 } else { 969 log.error(tree.pos(), "abstract.meth.cant.have.body"); 970 } 971 } else if ((tree.mods.flags & NATIVE) != 0) { 972 log.error(tree.pos(), "native.meth.cant.have.body"); 973 } else { 974 // Add an implicit super() call unless an explicit call to 975 // super(...) or this(...) is given 976 // or we are compiling class java.lang.Object. 977 if (tree.name == names.init && owner.type != syms.objectType) { 978 JCBlock body = tree.body; 979 if (body.stats.isEmpty() || 980 !TreeInfo.isSelfCall(body.stats.head)) { 981 body.stats = body.stats. 982 prepend(memberEnter.SuperCall(make.at(body.pos), 983 List.<Type>nil(), 984 List.<JCVariableDecl>nil(), 985 false)); 986 } else if ((env.enclClass.sym.flags() & ENUM) != 0 && 987 (tree.mods.flags & GENERATEDCONSTR) == 0 && 988 TreeInfo.isSuperCall(body.stats.head)) { 989 // enum constructors are not allowed to call super 990 // directly, so make sure there aren't any super calls 991 // in enum constructors, except in the compiler 992 // generated one. 993 log.error(tree.body.stats.head.pos(), 994 "call.to.super.not.allowed.in.enum.ctor", 995 env.enclClass.sym); 996 } 997 } 998 999 // Attribute method body. 1000 attribStat(tree.body, localEnv); 1001 } 1002 localEnv.info.scope.leave(); 1003 result = tree.type = m.type; 1004 chk.validateAnnotations(tree.mods.annotations, m); 1005 } 1006 finally { 1007 chk.setLint(prevLint); 1008 chk.setMethod(prevMethod); 1009 } 1010 } 1011 1012 public void visitVarDef(JCVariableDecl tree) { 1013 // Local variables have not been entered yet, so we need to do it now: 1014 if (env.info.scope.owner.kind == MTH) { 1015 if (tree.sym != null) { 1016 // parameters have already been entered 1017 env.info.scope.enter(tree.sym); 1018 } else { 1019 memberEnter.memberEnter(tree, env); 1020 annotate.flush(); 1021 } 1022 } 1023 1024 VarSymbol v = tree.sym; 1025 Lint lint = env.info.lint.augment(v.annotations, v.flags()); 1026 Lint prevLint = chk.setLint(lint); 1027 1028 // Check that the variable's declared type is well-formed. 1029 chk.validate(tree.vartype, env); 1030 deferredLintHandler.flush(tree.pos()); 1031 1032 try { 1033 chk.checkDeprecatedAnnotation(tree.pos(), v); 1034 1035 if (tree.init != null) { 1036 if ((v.flags_field & FINAL) != 0 && 1037 !tree.init.hasTag(NEWCLASS) && 1038 !tree.init.hasTag(LAMBDA) && 1039 !tree.init.hasTag(REFERENCE)) { 1040 // In this case, `v' is final. Ensure that it's initializer is 1041 // evaluated. 1042 v.getConstValue(); // ensure initializer is evaluated 1043 } else { 1044 // Attribute initializer in a new environment 1045 // with the declared variable as owner. 1046 // Check that initializer conforms to variable's declared type. 1047 Env<AttrContext> initEnv = memberEnter.initEnv(tree, env); 1048 initEnv.info.lint = lint; 1049 // In order to catch self-references, we set the variable's 1050 // declaration position to maximal possible value, effectively 1051 // marking the variable as undefined. 1052 initEnv.info.enclVar = v; 1053 attribExpr(tree.init, initEnv, v.type); 1054 } 1055 } 1056 result = tree.type = v.type; 1057 chk.validateAnnotations(tree.mods.annotations, v); 1058 } 1059 finally { 1060 chk.setLint(prevLint); 1061 } 1062 } 1063 1064 public void visitSkip(JCSkip tree) { 1065 result = null; 1066 } 1067 1068 public void visitBlock(JCBlock tree) { 1069 if (env.info.scope.owner.kind == TYP) { 1070 // Block is a static or instance initializer; 1071 // let the owner of the environment be a freshly 1072 // created BLOCK-method. 1073 Env<AttrContext> localEnv = 1074 env.dup(tree, env.info.dup(env.info.scope.dupUnshared())); 1075 localEnv.info.scope.owner = 1076 new MethodSymbol(tree.flags | BLOCK, names.empty, null, 1077 env.info.scope.owner); 1078 if ((tree.flags & STATIC) != 0) localEnv.info.staticLevel++; 1079 attribStats(tree.stats, localEnv); 1080 } else { 1081 // Create a new local environment with a local scope. 1082 Env<AttrContext> localEnv = 1083 env.dup(tree, env.info.dup(env.info.scope.dup())); 1084 try { 1085 attribStats(tree.stats, localEnv); 1086 } finally { 1087 localEnv.info.scope.leave(); 1088 } 1089 } 1090 result = null; 1091 } 1092 1093 public void visitDoLoop(JCDoWhileLoop tree) { 1094 attribStat(tree.body, env.dup(tree)); 1095 attribExpr(tree.cond, env, syms.booleanType); 1096 result = null; 1097 } 1098 1099 public void visitWhileLoop(JCWhileLoop tree) { 1100 attribExpr(tree.cond, env, syms.booleanType); 1101 attribStat(tree.body, env.dup(tree)); 1102 result = null; 1103 } 1104 1105 public void visitForLoop(JCForLoop tree) { 1106 Env<AttrContext> loopEnv = 1107 env.dup(env.tree, env.info.dup(env.info.scope.dup())); 1108 try { 1109 attribStats(tree.init, loopEnv); 1110 if (tree.cond != null) attribExpr(tree.cond, loopEnv, syms.booleanType); 1111 loopEnv.tree = tree; // before, we were not in loop! 1112 attribStats(tree.step, loopEnv); 1113 attribStat(tree.body, loopEnv); 1114 result = null; 1115 } 1116 finally { 1117 loopEnv.info.scope.leave(); 1118 } 1119 } 1120 1121 public void visitForeachLoop(JCEnhancedForLoop tree) { 1122 Env<AttrContext> loopEnv = 1123 env.dup(env.tree, env.info.dup(env.info.scope.dup())); 1124 try { 1125 attribStat(tree.var, loopEnv); 1126 Type exprType = types.upperBound(attribExpr(tree.expr, loopEnv)); 1127 chk.checkNonVoid(tree.pos(), exprType); 1128 Type elemtype = types.elemtype(exprType); // perhaps expr is an array? 1129 if (elemtype == null) { 1130 // or perhaps expr implements Iterable<T>? 1131 Type base = types.asSuper(exprType, syms.iterableType.tsym); 1132 if (base == null) { 1133 log.error(tree.expr.pos(), 1134 "foreach.not.applicable.to.type", 1135 exprType, 1136 diags.fragment("type.req.array.or.iterable")); 1137 elemtype = types.createErrorType(exprType); 1138 } else { 1139 List<Type> iterableParams = base.allparams(); 1140 elemtype = iterableParams.isEmpty() 1141 ? syms.objectType 1142 : types.upperBound(iterableParams.head); 1143 } 1144 } 1145 chk.checkType(tree.expr.pos(), elemtype, tree.var.sym.type); 1146 loopEnv.tree = tree; // before, we were not in loop! 1147 attribStat(tree.body, loopEnv); 1148 result = null; 1149 } 1150 finally { 1151 loopEnv.info.scope.leave(); 1152 } 1153 } 1154 1155 public void visitLabelled(JCLabeledStatement tree) { 1156 // Check that label is not used in an enclosing statement 1157 Env<AttrContext> env1 = env; 1158 while (env1 != null && !env1.tree.hasTag(CLASSDEF)) { 1159 if (env1.tree.hasTag(LABELLED) && 1160 ((JCLabeledStatement) env1.tree).label == tree.label) { 1161 log.error(tree.pos(), "label.already.in.use", 1162 tree.label); 1163 break; 1164 } 1165 env1 = env1.next; 1166 } 1167 1168 attribStat(tree.body, env.dup(tree)); 1169 result = null; 1170 } 1171 1172 public void visitSwitch(JCSwitch tree) { 1173 Type seltype = attribExpr(tree.selector, env); 1174 1175 Env<AttrContext> switchEnv = 1176 env.dup(tree, env.info.dup(env.info.scope.dup())); 1177 1178 try { 1179 1180 boolean enumSwitch = 1181 allowEnums && 1182 (seltype.tsym.flags() & Flags.ENUM) != 0; 1183 boolean stringSwitch = false; 1184 if (types.isSameType(seltype, syms.stringType)) { 1185 if (allowStringsInSwitch) { 1186 stringSwitch = true; 1187 } else { 1188 log.error(tree.selector.pos(), "string.switch.not.supported.in.source", sourceName); 1189 } 1190 } 1191 if (!enumSwitch && !stringSwitch) 1192 seltype = chk.checkType(tree.selector.pos(), seltype, syms.intType); 1193 1194 // Attribute all cases and 1195 // check that there are no duplicate case labels or default clauses. 1196 Set<Object> labels = new HashSet<Object>(); // The set of case labels. 1197 boolean hasDefault = false; // Is there a default label? 1198 for (List<JCCase> l = tree.cases; l.nonEmpty(); l = l.tail) { 1199 JCCase c = l.head; 1200 Env<AttrContext> caseEnv = 1201 switchEnv.dup(c, env.info.dup(switchEnv.info.scope.dup())); 1202 try { 1203 if (c.pat != null) { 1204 if (enumSwitch) { 1205 Symbol sym = enumConstant(c.pat, seltype); 1206 if (sym == null) { 1207 log.error(c.pat.pos(), "enum.label.must.be.unqualified.enum"); 1208 } else if (!labels.add(sym)) { 1209 log.error(c.pos(), "duplicate.case.label"); 1210 } 1211 } else { 1212 Type pattype = attribExpr(c.pat, switchEnv, seltype); 1213 if (!pattype.hasTag(ERROR)) { 1214 if (pattype.constValue() == null) { 1215 log.error(c.pat.pos(), 1216 (stringSwitch ? "string.const.req" : "const.expr.req")); 1217 } else if (labels.contains(pattype.constValue())) { 1218 log.error(c.pos(), "duplicate.case.label"); 1219 } else { 1220 labels.add(pattype.constValue()); 1221 } 1222 } 1223 } 1224 } else if (hasDefault) { 1225 log.error(c.pos(), "duplicate.default.label"); 1226 } else { 1227 hasDefault = true; 1228 } 1229 attribStats(c.stats, caseEnv); 1230 } finally { 1231 caseEnv.info.scope.leave(); 1232 addVars(c.stats, switchEnv.info.scope); 1233 } 1234 } 1235 1236 result = null; 1237 } 1238 finally { 1239 switchEnv.info.scope.leave(); 1240 } 1241 } 1242 // where 1243 /** Add any variables defined in stats to the switch scope. */ 1244 private static void addVars(List<JCStatement> stats, Scope switchScope) { 1245 for (;stats.nonEmpty(); stats = stats.tail) { 1246 JCTree stat = stats.head; 1247 if (stat.hasTag(VARDEF)) 1248 switchScope.enter(((JCVariableDecl) stat).sym); 1249 } 1250 } 1251 // where 1252 /** Return the selected enumeration constant symbol, or null. */ 1253 private Symbol enumConstant(JCTree tree, Type enumType) { 1254 if (!tree.hasTag(IDENT)) { 1255 log.error(tree.pos(), "enum.label.must.be.unqualified.enum"); 1256 return syms.errSymbol; 1257 } 1258 JCIdent ident = (JCIdent)tree; 1259 Name name = ident.name; 1260 for (Scope.Entry e = enumType.tsym.members().lookup(name); 1261 e.scope != null; e = e.next()) { 1262 if (e.sym.kind == VAR) { 1263 Symbol s = ident.sym = e.sym; 1264 ((VarSymbol)s).getConstValue(); // ensure initializer is evaluated 1265 ident.type = s.type; 1266 return ((s.flags_field & Flags.ENUM) == 0) 1267 ? null : s; 1268 } 1269 } 1270 return null; 1271 } 1272 1273 public void visitSynchronized(JCSynchronized tree) { 1274 chk.checkRefType(tree.pos(), attribExpr(tree.lock, env)); 1275 attribStat(tree.body, env); 1276 result = null; 1277 } 1278 1279 public void visitTry(JCTry tree) { 1280 // Create a new local environment with a local 1281 Env<AttrContext> localEnv = env.dup(tree, env.info.dup(env.info.scope.dup())); 1282 try { 1283 boolean isTryWithResource = tree.resources.nonEmpty(); 1284 // Create a nested environment for attributing the try block if needed 1285 Env<AttrContext> tryEnv = isTryWithResource ? 1286 env.dup(tree, localEnv.info.dup(localEnv.info.scope.dup())) : 1287 localEnv; 1288 try { 1289 // Attribute resource declarations 1290 for (JCTree resource : tree.resources) { 1291 CheckContext twrContext = new Check.NestedCheckContext(resultInfo.checkContext) { 1292 @Override 1293 public void report(DiagnosticPosition pos, JCDiagnostic details) { 1294 chk.basicHandler.report(pos, diags.fragment("try.not.applicable.to.type", details)); 1295 } 1296 }; 1297 ResultInfo twrResult = new ResultInfo(VAL, syms.autoCloseableType, twrContext); 1298 if (resource.hasTag(VARDEF)) { 1299 attribStat(resource, tryEnv); 1300 twrResult.check(resource, resource.type); 1301 1302 //check that resource type cannot throw InterruptedException 1303 checkAutoCloseable(resource.pos(), localEnv, resource.type); 1304 1305 VarSymbol var = (VarSymbol)TreeInfo.symbolFor(resource); 1306 var.setData(ElementKind.RESOURCE_VARIABLE); 1307 } else { 1308 attribTree(resource, tryEnv, twrResult); 1309 } 1310 } 1311 // Attribute body 1312 attribStat(tree.body, tryEnv); 1313 } finally { 1314 if (isTryWithResource) 1315 tryEnv.info.scope.leave(); 1316 } 1317 1318 // Attribute catch clauses 1319 for (List<JCCatch> l = tree.catchers; l.nonEmpty(); l = l.tail) { 1320 JCCatch c = l.head; 1321 Env<AttrContext> catchEnv = 1322 localEnv.dup(c, localEnv.info.dup(localEnv.info.scope.dup())); 1323 try { 1324 Type ctype = attribStat(c.param, catchEnv); 1325 if (TreeInfo.isMultiCatch(c)) { 1326 //multi-catch parameter is implicitly marked as final 1327 c.param.sym.flags_field |= FINAL | UNION; 1328 } 1329 if (c.param.sym.kind == Kinds.VAR) { 1330 c.param.sym.setData(ElementKind.EXCEPTION_PARAMETER); 1331 } 1332 chk.checkType(c.param.vartype.pos(), 1333 chk.checkClassType(c.param.vartype.pos(), ctype), 1334 syms.throwableType); 1335 attribStat(c.body, catchEnv); 1336 } finally { 1337 catchEnv.info.scope.leave(); 1338 } 1339 } 1340 1341 // Attribute finalizer 1342 if (tree.finalizer != null) attribStat(tree.finalizer, localEnv); 1343 result = null; 1344 } 1345 finally { 1346 localEnv.info.scope.leave(); 1347 } 1348 } 1349 1350 void checkAutoCloseable(DiagnosticPosition pos, Env<AttrContext> env, Type resource) { 1351 if (!resource.isErroneous() && 1352 types.asSuper(resource, syms.autoCloseableType.tsym) != null && 1353 !types.isSameType(resource, syms.autoCloseableType)) { // Don't emit warning for AutoCloseable itself 1354 Symbol close = syms.noSymbol; 1355 Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log); 1356 try { 1357 close = rs.resolveQualifiedMethod(pos, 1358 env, 1359 resource, 1360 names.close, 1361 List.<Type>nil(), 1362 List.<Type>nil()); 1363 } 1364 finally { 1365 log.popDiagnosticHandler(discardHandler); 1366 } 1367 if (close.kind == MTH && 1368 close.overrides(syms.autoCloseableClose, resource.tsym, types, true) && 1369 chk.isHandled(syms.interruptedExceptionType, types.memberType(resource, close).getThrownTypes()) && 1370 env.info.lint.isEnabled(LintCategory.TRY)) { 1371 log.warning(LintCategory.TRY, pos, "try.resource.throws.interrupted.exc", resource); 1372 } 1373 } 1374 } 1375 1376 public void visitConditional(JCConditional tree) { 1377 Type condtype = attribExpr(tree.cond, env, syms.booleanType); 1378 1379 boolean standaloneConditional = !allowPoly || 1380 pt().hasTag(NONE) && pt() != Type.recoveryType || 1381 isBooleanOrNumeric(env, tree); 1382 1383 if (!standaloneConditional && resultInfo.pt.hasTag(VOID)) { 1384 //cannot get here (i.e. it means we are returning from void method - which is already an error) 1385 resultInfo.checkContext.report(tree, diags.fragment("conditional.target.cant.be.void")); 1386 result = tree.type = types.createErrorType(resultInfo.pt); 1387 return; 1388 } 1389 1390 ResultInfo condInfo = standaloneConditional ? 1391 unknownExprInfo : 1392 resultInfo.dup(new Check.NestedCheckContext(resultInfo.checkContext) { 1393 //this will use enclosing check context to check compatibility of 1394 //subexpression against target type; if we are in a method check context, 1395 //depending on whether boxing is allowed, we could have incompatibilities 1396 @Override 1397 public void report(DiagnosticPosition pos, JCDiagnostic details) { 1398 enclosingContext.report(pos, diags.fragment("incompatible.type.in.conditional", details)); 1399 } 1400 }); 1401 1402 Type truetype = attribTree(tree.truepart, env, condInfo); 1403 Type falsetype = attribTree(tree.falsepart, env, condInfo); 1404 1405 Type owntype = standaloneConditional ? condType(tree, truetype, falsetype) : pt(); 1406 if (condtype.constValue() != null && 1407 truetype.constValue() != null && 1408 falsetype.constValue() != null && 1409 !owntype.hasTag(NONE)) { 1410 //constant folding 1411 owntype = cfolder.coerce(condtype.isTrue() ? truetype : falsetype, owntype); 1412 } 1413 result = check(tree, owntype, VAL, resultInfo); 1414 } 1415 //where 1416 private boolean isBooleanOrNumeric(Env<AttrContext> env, JCExpression tree) { 1417 switch (tree.getTag()) { 1418 case LITERAL: return ((JCLiteral)tree).typetag.isSubRangeOf(DOUBLE) || 1419 ((JCLiteral)tree).typetag == BOOLEAN || 1420 ((JCLiteral)tree).typetag == BOT; 1421 case LAMBDA: case REFERENCE: return false; 1422 case PARENS: return isBooleanOrNumeric(env, ((JCParens)tree).expr); 1423 case CONDEXPR: 1424 JCConditional condTree = (JCConditional)tree; 1425 return isBooleanOrNumeric(env, condTree.truepart) && 1426 isBooleanOrNumeric(env, condTree.falsepart); 1427 default: 1428 Type speculativeType = deferredAttr.attribSpeculative(tree, env, unknownExprInfo).type; 1429 speculativeType = types.unboxedTypeOrType(speculativeType); 1430 return speculativeType.isPrimitive(); 1431 } 1432 } 1433 1434 /** Compute the type of a conditional expression, after 1435 * checking that it exists. See JLS 15.25. Does not take into 1436 * account the special case where condition and both arms 1437 * are constants. 1438 * 1439 * @param pos The source position to be used for error 1440 * diagnostics. 1441 * @param thentype The type of the expression's then-part. 1442 * @param elsetype The type of the expression's else-part. 1443 */ 1444 private Type condType(DiagnosticPosition pos, 1445 Type thentype, Type elsetype) { 1446 // If same type, that is the result 1447 if (types.isSameType(thentype, elsetype)) 1448 return thentype.baseType(); 1449 1450 Type thenUnboxed = (!allowBoxing || thentype.isPrimitive()) 1451 ? thentype : types.unboxedType(thentype); 1452 Type elseUnboxed = (!allowBoxing || elsetype.isPrimitive()) 1453 ? elsetype : types.unboxedType(elsetype); 1454 1455 // Otherwise, if both arms can be converted to a numeric 1456 // type, return the least numeric type that fits both arms 1457 // (i.e. return larger of the two, or return int if one 1458 // arm is short, the other is char). 1459 if (thenUnboxed.isPrimitive() && elseUnboxed.isPrimitive()) { 1460 // If one arm has an integer subrange type (i.e., byte, 1461 // short, or char), and the other is an integer constant 1462 // that fits into the subrange, return the subrange type. 1463 if (thenUnboxed.getTag().isStrictSubRangeOf(INT) && elseUnboxed.hasTag(INT) && 1464 types.isAssignable(elseUnboxed, thenUnboxed)) 1465 return thenUnboxed.baseType(); 1466 if (elseUnboxed.getTag().isStrictSubRangeOf(INT) && thenUnboxed.hasTag(INT) && 1467 types.isAssignable(thenUnboxed, elseUnboxed)) 1468 return elseUnboxed.baseType(); 1469 1470 for (TypeTag tag : TypeTag.values()) { 1471 if (tag.ordinal() >= TypeTag.getTypeTagCount()) break; 1472 Type candidate = syms.typeOfTag[tag.ordinal()]; 1473 if (candidate != null && 1474 candidate.isPrimitive() && 1475 types.isSubtype(thenUnboxed, candidate) && 1476 types.isSubtype(elseUnboxed, candidate)) 1477 return candidate; 1478 } 1479 } 1480 1481 // Those were all the cases that could result in a primitive 1482 if (allowBoxing) { 1483 if (thentype.isPrimitive()) 1484 thentype = types.boxedClass(thentype).type; 1485 if (elsetype.isPrimitive()) 1486 elsetype = types.boxedClass(elsetype).type; 1487 } 1488 1489 if (types.isSubtype(thentype, elsetype)) 1490 return elsetype.baseType(); 1491 if (types.isSubtype(elsetype, thentype)) 1492 return thentype.baseType(); 1493 1494 if (!allowBoxing || thentype.hasTag(VOID) || elsetype.hasTag(VOID)) { 1495 log.error(pos, "neither.conditional.subtype", 1496 thentype, elsetype); 1497 return thentype.baseType(); 1498 } 1499 1500 // both are known to be reference types. The result is 1501 // lub(thentype,elsetype). This cannot fail, as it will 1502 // always be possible to infer "Object" if nothing better. 1503 return types.lub(thentype.baseType(), elsetype.baseType()); 1504 } 1505 1506 public void visitIf(JCIf tree) { 1507 attribExpr(tree.cond, env, syms.booleanType); 1508 attribStat(tree.thenpart, env); 1509 if (tree.elsepart != null) 1510 attribStat(tree.elsepart, env); 1511 chk.checkEmptyIf(tree); 1512 result = null; 1513 } 1514 1515 public void visitExec(JCExpressionStatement tree) { 1516 //a fresh environment is required for 292 inference to work properly --- 1517 //see Infer.instantiatePolymorphicSignatureInstance() 1518 Env<AttrContext> localEnv = env.dup(tree); 1519 attribExpr(tree.expr, localEnv); 1520 result = null; 1521 } 1522 1523 public void visitBreak(JCBreak tree) { 1524 tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env); 1525 result = null; 1526 } 1527 1528 public void visitContinue(JCContinue tree) { 1529 tree.target = findJumpTarget(tree.pos(), tree.getTag(), tree.label, env); 1530 result = null; 1531 } 1532 //where 1533 /** Return the target of a break or continue statement, if it exists, 1534 * report an error if not. 1535 * Note: The target of a labelled break or continue is the 1536 * (non-labelled) statement tree referred to by the label, 1537 * not the tree representing the labelled statement itself. 1538 * 1539 * @param pos The position to be used for error diagnostics 1540 * @param tag The tag of the jump statement. This is either 1541 * Tree.BREAK or Tree.CONTINUE. 1542 * @param label The label of the jump statement, or null if no 1543 * label is given. 1544 * @param env The environment current at the jump statement. 1545 */ 1546 private JCTree findJumpTarget(DiagnosticPosition pos, 1547 JCTree.Tag tag, 1548 Name label, 1549 Env<AttrContext> env) { 1550 // Search environments outwards from the point of jump. 1551 Env<AttrContext> env1 = env; 1552 LOOP: 1553 while (env1 != null) { 1554 switch (env1.tree.getTag()) { 1555 case LABELLED: 1556 JCLabeledStatement labelled = (JCLabeledStatement)env1.tree; 1557 if (label == labelled.label) { 1558 // If jump is a continue, check that target is a loop. 1559 if (tag == CONTINUE) { 1560 if (!labelled.body.hasTag(DOLOOP) && 1561 !labelled.body.hasTag(WHILELOOP) && 1562 !labelled.body.hasTag(FORLOOP) && 1563 !labelled.body.hasTag(FOREACHLOOP)) 1564 log.error(pos, "not.loop.label", label); 1565 // Found labelled statement target, now go inwards 1566 // to next non-labelled tree. 1567 return TreeInfo.referencedStatement(labelled); 1568 } else { 1569 return labelled; 1570 } 1571 } 1572 break; 1573 case DOLOOP: 1574 case WHILELOOP: 1575 case FORLOOP: 1576 case FOREACHLOOP: 1577 if (label == null) return env1.tree; 1578 break; 1579 case SWITCH: 1580 if (label == null && tag == BREAK) return env1.tree; 1581 break; 1582 case LAMBDA: 1583 case METHODDEF: 1584 case CLASSDEF: 1585 break LOOP; 1586 default: 1587 } 1588 env1 = env1.next; 1589 } 1590 if (label != null) 1591 log.error(pos, "undef.label", label); 1592 else if (tag == CONTINUE) 1593 log.error(pos, "cont.outside.loop"); 1594 else 1595 log.error(pos, "break.outside.switch.loop"); 1596 return null; 1597 } 1598 1599 public void visitReturn(JCReturn tree) { 1600 // Check that there is an enclosing method which is 1601 // nested within than the enclosing class. 1602 if (env.info.returnResult == null) { 1603 log.error(tree.pos(), "ret.outside.meth"); 1604 } else { 1605 // Attribute return expression, if it exists, and check that 1606 // it conforms to result type of enclosing method. 1607 if (tree.expr != null) { 1608 if (env.info.returnResult.pt.hasTag(VOID)) { 1609 env.info.returnResult.checkContext.report(tree.expr.pos(), 1610 diags.fragment("unexpected.ret.val")); 1611 } 1612 attribTree(tree.expr, env, env.info.returnResult); 1613 } else if (!env.info.returnResult.pt.hasTag(VOID)) { 1614 env.info.returnResult.checkContext.report(tree.pos(), 1615 diags.fragment("missing.ret.val")); 1616 } 1617 } 1618 result = null; 1619 } 1620 1621 public void visitThrow(JCThrow tree) { 1622 Type owntype = attribExpr(tree.expr, env, allowPoly ? Type.noType : syms.throwableType); 1623 if (allowPoly) { 1624 chk.checkType(tree, owntype, syms.throwableType); 1625 } 1626 result = null; 1627 } 1628 1629 public void visitAssert(JCAssert tree) { 1630 attribExpr(tree.cond, env, syms.booleanType); 1631 if (tree.detail != null) { 1632 chk.checkNonVoid(tree.detail.pos(), attribExpr(tree.detail, env)); 1633 } 1634 result = null; 1635 } 1636 1637 /** Visitor method for method invocations. 1638 * NOTE: The method part of an application will have in its type field 1639 * the return type of the method, not the method's type itself! 1640 */ 1641 public void visitApply(JCMethodInvocation tree) { 1642 // The local environment of a method application is 1643 // a new environment nested in the current one. 1644 Env<AttrContext> localEnv = env.dup(tree, env.info.dup()); 1645 1646 // The types of the actual method arguments. 1647 List<Type> argtypes; 1648 1649 // The types of the actual method type arguments. 1650 List<Type> typeargtypes = null; 1651 1652 Name methName = TreeInfo.name(tree.meth); 1653 1654 boolean isConstructorCall = 1655 methName == names._this || methName == names._super; 1656 1657 if (isConstructorCall) { 1658 // We are seeing a ...this(...) or ...super(...) call. 1659 // Check that this is the first statement in a constructor. 1660 if (checkFirstConstructorStat(tree, env)) { 1661 1662 // Record the fact 1663 // that this is a constructor call (using isSelfCall). 1664 localEnv.info.isSelfCall = true; 1665 1666 // Attribute arguments, yielding list of argument types. 1667 argtypes = attribArgs(tree.args, localEnv); 1668 typeargtypes = attribTypes(tree.typeargs, localEnv); 1669 1670 // Variable `site' points to the class in which the called 1671 // constructor is defined. 1672 Type site = env.enclClass.sym.type; 1673 if (methName == names._super) { 1674 if (site == syms.objectType) { 1675 log.error(tree.meth.pos(), "no.superclass", site); 1676 site = types.createErrorType(syms.objectType); 1677 } else { 1678 site = types.supertype(site); 1679 } 1680 } 1681 1682 if (site.hasTag(CLASS)) { 1683 Type encl = site.getEnclosingType(); 1684 while (encl != null && encl.hasTag(TYPEVAR)) 1685 encl = encl.getUpperBound(); 1686 if (encl.hasTag(CLASS)) { 1687 // we are calling a nested class 1688 1689 if (tree.meth.hasTag(SELECT)) { 1690 JCTree qualifier = ((JCFieldAccess) tree.meth).selected; 1691 1692 // We are seeing a prefixed call, of the form 1693 // <expr>.super(...). 1694 // Check that the prefix expression conforms 1695 // to the outer instance type of the class. 1696 chk.checkRefType(qualifier.pos(), 1697 attribExpr(qualifier, localEnv, 1698 encl)); 1699 } else if (methName == names._super) { 1700 // qualifier omitted; check for existence 1701 // of an appropriate implicit qualifier. 1702 rs.resolveImplicitThis(tree.meth.pos(), 1703 localEnv, site, true); 1704 } 1705 } else if (tree.meth.hasTag(SELECT)) { 1706 log.error(tree.meth.pos(), "illegal.qual.not.icls", 1707 site.tsym); 1708 } 1709 1710 // if we're calling a java.lang.Enum constructor, 1711 // prefix the implicit String and int parameters 1712 if (site.tsym == syms.enumSym && allowEnums) 1713 argtypes = argtypes.prepend(syms.intType).prepend(syms.stringType); 1714 1715 // Resolve the called constructor under the assumption 1716 // that we are referring to a superclass instance of the 1717 // current instance (JLS ???). 1718 boolean selectSuperPrev = localEnv.info.selectSuper; 1719 localEnv.info.selectSuper = true; 1720 localEnv.info.pendingResolutionPhase = null; 1721 Symbol sym = rs.resolveConstructor( 1722 tree.meth.pos(), localEnv, site, argtypes, typeargtypes); 1723 localEnv.info.selectSuper = selectSuperPrev; 1724 1725 // Set method symbol to resolved constructor... 1726 TreeInfo.setSymbol(tree.meth, sym); 1727 1728 // ...and check that it is legal in the current context. 1729 // (this will also set the tree's type) 1730 Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes); 1731 checkId(tree.meth, site, sym, localEnv, new ResultInfo(MTH, mpt)); 1732 } 1733 // Otherwise, `site' is an error type and we do nothing 1734 } 1735 result = tree.type = syms.voidType; 1736 } else { 1737 // Otherwise, we are seeing a regular method call. 1738 // Attribute the arguments, yielding list of argument types, ... 1739 argtypes = attribArgs(tree.args, localEnv); 1740 typeargtypes = attribAnyTypes(tree.typeargs, localEnv); 1741 1742 // ... and attribute the method using as a prototype a methodtype 1743 // whose formal argument types is exactly the list of actual 1744 // arguments (this will also set the method symbol). 1745 Type mpt = newMethodTemplate(resultInfo.pt, argtypes, typeargtypes); 1746 localEnv.info.pendingResolutionPhase = null; 1747 Type mtype = attribTree(tree.meth, localEnv, new ResultInfo(VAL, mpt, resultInfo.checkContext)); 1748 1749 // Compute the result type. 1750 Type restype = mtype.getReturnType(); 1751 if (restype.hasTag(WILDCARD)) 1752 throw new AssertionError(mtype); 1753 1754 Type qualifier = (tree.meth.hasTag(SELECT)) 1755 ? ((JCFieldAccess) tree.meth).selected.type 1756 : env.enclClass.sym.type; 1757 restype = adjustMethodReturnType(qualifier, methName, argtypes, restype); 1758 1759 chk.checkRefTypes(tree.typeargs, typeargtypes); 1760 1761 // Check that value of resulting type is admissible in the 1762 // current context. Also, capture the return type 1763 result = check(tree, capture(restype), VAL, resultInfo); 1764 1765 if (localEnv.info.lastResolveVarargs()) 1766 Assert.check(result.isErroneous() || tree.varargsElement != null); 1767 } 1768 chk.validate(tree.typeargs, localEnv); 1769 } 1770 //where 1771 Type adjustMethodReturnType(Type qualifierType, Name methodName, List<Type> argtypes, Type restype) { 1772 if (allowCovariantReturns && 1773 methodName == names.clone && 1774 types.isArray(qualifierType)) { 1775 // as a special case, array.clone() has a result that is 1776 // the same as static type of the array being cloned 1777 return qualifierType; 1778 } else if (allowGenerics && 1779 methodName == names.getClass && 1780 argtypes.isEmpty()) { 1781 // as a special case, x.getClass() has type Class<? extends |X|> 1782 return new ClassType(restype.getEnclosingType(), 1783 List.<Type>of(new WildcardType(types.erasure(qualifierType), 1784 BoundKind.EXTENDS, 1785 syms.boundClass)), 1786 restype.tsym); 1787 } else { 1788 return restype; 1789 } 1790 } 1791 1792 /** Check that given application node appears as first statement 1793 * in a constructor call. 1794 * @param tree The application node 1795 * @param env The environment current at the application. 1796 */ 1797 boolean checkFirstConstructorStat(JCMethodInvocation tree, Env<AttrContext> env) { 1798 JCMethodDecl enclMethod = env.enclMethod; 1799 if (enclMethod != null && enclMethod.name == names.init) { 1800 JCBlock body = enclMethod.body; 1801 if (body.stats.head.hasTag(EXEC) && 1802 ((JCExpressionStatement) body.stats.head).expr == tree) 1803 return true; 1804 } 1805 log.error(tree.pos(),"call.must.be.first.stmt.in.ctor", 1806 TreeInfo.name(tree.meth)); 1807 return false; 1808 } 1809 1810 /** Obtain a method type with given argument types. 1811 */ 1812 Type newMethodTemplate(Type restype, List<Type> argtypes, List<Type> typeargtypes) { 1813 MethodType mt = new MethodType(argtypes, restype, List.<Type>nil(), syms.methodClass); 1814 return (typeargtypes == null) ? mt : (Type)new ForAll(typeargtypes, mt); 1815 } 1816 1817 public void visitNewClass(final JCNewClass tree) { 1818 Type owntype = types.createErrorType(tree.type); 1819 1820 // The local environment of a class creation is 1821 // a new environment nested in the current one. 1822 Env<AttrContext> localEnv = env.dup(tree, env.info.dup()); 1823 1824 // The anonymous inner class definition of the new expression, 1825 // if one is defined by it. 1826 JCClassDecl cdef = tree.def; 1827 1828 // If enclosing class is given, attribute it, and 1829 // complete class name to be fully qualified 1830 JCExpression clazz = tree.clazz; // Class field following new 1831 JCExpression clazzid = // Identifier in class field 1832 (clazz.hasTag(TYPEAPPLY)) 1833 ? ((JCTypeApply) clazz).clazz 1834 : clazz; 1835 1836 JCExpression clazzid1 = clazzid; // The same in fully qualified form 1837 1838 if (tree.encl != null) { 1839 // We are seeing a qualified new, of the form 1840 // <expr>.new C <...> (...) ... 1841 // In this case, we let clazz stand for the name of the 1842 // allocated class C prefixed with the type of the qualifier 1843 // expression, so that we can 1844 // resolve it with standard techniques later. I.e., if 1845 // <expr> has type T, then <expr>.new C <...> (...) 1846 // yields a clazz T.C. 1847 Type encltype = chk.checkRefType(tree.encl.pos(), 1848 attribExpr(tree.encl, env)); 1849 clazzid1 = make.at(clazz.pos).Select(make.Type(encltype), 1850 ((JCIdent) clazzid).name); 1851 if (clazz.hasTag(TYPEAPPLY)) 1852 clazz = make.at(tree.pos). 1853 TypeApply(clazzid1, 1854 ((JCTypeApply) clazz).arguments); 1855 else 1856 clazz = clazzid1; 1857 } 1858 1859 // Attribute clazz expression and store 1860 // symbol + type back into the attributed tree. 1861 Type clazztype = TreeInfo.isEnumInit(env.tree) ? 1862 attribIdentAsEnumType(env, (JCIdent)clazz) : 1863 attribType(clazz, env); 1864 1865 clazztype = chk.checkDiamond(tree, clazztype); 1866 chk.validate(clazz, localEnv); 1867 if (tree.encl != null) { 1868 // We have to work in this case to store 1869 // symbol + type back into the attributed tree. 1870 tree.clazz.type = clazztype; 1871 TreeInfo.setSymbol(clazzid, TreeInfo.symbol(clazzid1)); 1872 clazzid.type = ((JCIdent) clazzid).sym.type; 1873 if (!clazztype.isErroneous()) { 1874 if (cdef != null && clazztype.tsym.isInterface()) { 1875 log.error(tree.encl.pos(), "anon.class.impl.intf.no.qual.for.new"); 1876 } else if (clazztype.tsym.isStatic()) { 1877 log.error(tree.encl.pos(), "qualified.new.of.static.class", clazztype.tsym); 1878 } 1879 } 1880 } else if (!clazztype.tsym.isInterface() && 1881 clazztype.getEnclosingType().hasTag(CLASS)) { 1882 // Check for the existence of an apropos outer instance 1883 rs.resolveImplicitThis(tree.pos(), env, clazztype); 1884 } 1885 1886 // Attribute constructor arguments. 1887 List<Type> argtypes = attribArgs(tree.args, localEnv); 1888 List<Type> typeargtypes = attribTypes(tree.typeargs, localEnv); 1889 1890 // If we have made no mistakes in the class type... 1891 if (clazztype.hasTag(CLASS)) { 1892 // Enums may not be instantiated except implicitly 1893 if (allowEnums && 1894 (clazztype.tsym.flags_field&Flags.ENUM) != 0 && 1895 (!env.tree.hasTag(VARDEF) || 1896 (((JCVariableDecl) env.tree).mods.flags&Flags.ENUM) == 0 || 1897 ((JCVariableDecl) env.tree).init != tree)) 1898 log.error(tree.pos(), "enum.cant.be.instantiated"); 1899 // Check that class is not abstract 1900 if (cdef == null && 1901 (clazztype.tsym.flags() & (ABSTRACT | INTERFACE)) != 0) { 1902 log.error(tree.pos(), "abstract.cant.be.instantiated", 1903 clazztype.tsym); 1904 } else if (cdef != null && clazztype.tsym.isInterface()) { 1905 // Check that no constructor arguments are given to 1906 // anonymous classes implementing an interface 1907 if (!argtypes.isEmpty()) 1908 log.error(tree.args.head.pos(), "anon.class.impl.intf.no.args"); 1909 1910 if (!typeargtypes.isEmpty()) 1911 log.error(tree.typeargs.head.pos(), "anon.class.impl.intf.no.typeargs"); 1912 1913 // Error recovery: pretend no arguments were supplied. 1914 argtypes = List.nil(); 1915 typeargtypes = List.nil(); 1916 } else if (TreeInfo.isDiamond(tree)) { 1917 ClassType site = new ClassType(clazztype.getEnclosingType(), 1918 clazztype.tsym.type.getTypeArguments(), 1919 clazztype.tsym); 1920 1921 Env<AttrContext> diamondEnv = localEnv.dup(tree); 1922 diamondEnv.info.selectSuper = cdef != null; 1923 diamondEnv.info.pendingResolutionPhase = null; 1924 1925 //if the type of the instance creation expression is a class type 1926 //apply method resolution inference (JLS 15.12.2.7). The return type 1927 //of the resolved constructor will be a partially instantiated type 1928 Symbol constructor = rs.resolveDiamond(tree.pos(), 1929 diamondEnv, 1930 site, 1931 argtypes, 1932 typeargtypes); 1933 tree.constructor = constructor.baseSymbol(); 1934 1935 final TypeSymbol csym = clazztype.tsym; 1936 ResultInfo diamondResult = new ResultInfo(MTH, newMethodTemplate(resultInfo.pt, argtypes, typeargtypes), new Check.NestedCheckContext(resultInfo.checkContext) { 1937 @Override 1938 public void report(DiagnosticPosition _unused, JCDiagnostic details) { 1939 enclosingContext.report(tree.clazz, 1940 diags.fragment("cant.apply.diamond.1", diags.fragment("diamond", csym), details)); 1941 } 1942 }); 1943 Type constructorType = tree.constructorType = types.createErrorType(clazztype); 1944 constructorType = checkId(tree, site, 1945 constructor, 1946 diamondEnv, 1947 diamondResult); 1948 1949 tree.clazz.type = types.createErrorType(clazztype); 1950 if (!constructorType.isErroneous()) { 1951 tree.clazz.type = clazztype = constructorType.getReturnType(); 1952 tree.constructorType = types.createMethodTypeWithReturn(constructorType, syms.voidType); 1953 } 1954 clazztype = chk.checkClassType(tree.clazz, tree.clazz.type, true); 1955 } 1956 1957 // Resolve the called constructor under the assumption 1958 // that we are referring to a superclass instance of the 1959 // current instance (JLS ???). 1960 else { 1961 //the following code alters some of the fields in the current 1962 //AttrContext - hence, the current context must be dup'ed in 1963 //order to avoid downstream failures 1964 Env<AttrContext> rsEnv = localEnv.dup(tree); 1965 rsEnv.info.selectSuper = cdef != null; 1966 rsEnv.info.pendingResolutionPhase = null; 1967 tree.constructor = rs.resolveConstructor( 1968 tree.pos(), rsEnv, clazztype, argtypes, typeargtypes); 1969 if (cdef == null) { //do not check twice! 1970 tree.constructorType = checkId(tree, 1971 clazztype, 1972 tree.constructor, 1973 rsEnv, 1974 new ResultInfo(MTH, newMethodTemplate(syms.voidType, argtypes, typeargtypes))); 1975 if (rsEnv.info.lastResolveVarargs()) 1976 Assert.check(tree.constructorType.isErroneous() || tree.varargsElement != null); 1977 } 1978 findDiamondIfNeeded(localEnv, tree, clazztype); 1979 } 1980 1981 if (cdef != null) { 1982 // We are seeing an anonymous class instance creation. 1983 // In this case, the class instance creation 1984 // expression 1985 // 1986 // E.new <typeargs1>C<typargs2>(args) { ... } 1987 // 1988 // is represented internally as 1989 // 1990 // E . new <typeargs1>C<typargs2>(args) ( class <empty-name> { ... } ) . 1991 // 1992 // This expression is then *transformed* as follows: 1993 // 1994 // (1) add a STATIC flag to the class definition 1995 // if the current environment is static 1996 // (2) add an extends or implements clause 1997 // (3) add a constructor. 1998 // 1999 // For instance, if C is a class, and ET is the type of E, 2000 // the expression 2001 // 2002 // E.new <typeargs1>C<typargs2>(args) { ... } 2003 // 2004 // is translated to (where X is a fresh name and typarams is the 2005 // parameter list of the super constructor): 2006 // 2007 // new <typeargs1>X(<*nullchk*>E, args) where 2008 // X extends C<typargs2> { 2009 // <typarams> X(ET e, args) { 2010 // e.<typeargs1>super(args) 2011 // } 2012 // ... 2013 // } 2014 if (Resolve.isStatic(env)) cdef.mods.flags |= STATIC; 2015 2016 if (clazztype.tsym.isInterface()) { 2017 cdef.implementing = List.of(clazz); 2018 } else { 2019 cdef.extending = clazz; 2020 } 2021 2022 attribStat(cdef, localEnv); 2023 2024 checkLambdaCandidate(tree, cdef.sym, clazztype); 2025 2026 // If an outer instance is given, 2027 // prefix it to the constructor arguments 2028 // and delete it from the new expression 2029 if (tree.encl != null && !clazztype.tsym.isInterface()) { 2030 tree.args = tree.args.prepend(makeNullCheck(tree.encl)); 2031 argtypes = argtypes.prepend(tree.encl.type); 2032 tree.encl = null; 2033 } 2034 2035 // Reassign clazztype and recompute constructor. 2036 clazztype = cdef.sym.type; 2037 Symbol sym = tree.constructor = rs.resolveConstructor( 2038 tree.pos(), localEnv, clazztype, argtypes, typeargtypes); 2039 Assert.check(sym.kind < AMBIGUOUS); 2040 tree.constructor = sym; 2041 tree.constructorType = checkId(tree, 2042 clazztype, 2043 tree.constructor, 2044 localEnv, 2045 new ResultInfo(VAL, newMethodTemplate(syms.voidType, argtypes, typeargtypes))); 2046 } 2047 2048 if (tree.constructor != null && tree.constructor.kind == MTH) 2049 owntype = clazztype; 2050 } 2051 result = check(tree, owntype, VAL, resultInfo); 2052 chk.validate(tree.typeargs, localEnv); 2053 } 2054 //where 2055 void findDiamondIfNeeded(Env<AttrContext> env, JCNewClass tree, Type clazztype) { 2056 if (tree.def == null && 2057 !clazztype.isErroneous() && 2058 clazztype.getTypeArguments().nonEmpty() && 2059 findDiamonds) { 2060 JCTypeApply ta = (JCTypeApply)tree.clazz; 2061 List<JCExpression> prevTypeargs = ta.arguments; 2062 try { 2063 //create a 'fake' diamond AST node by removing type-argument trees 2064 ta.arguments = List.nil(); 2065 ResultInfo findDiamondResult = new ResultInfo(VAL, 2066 resultInfo.checkContext.inferenceContext().free(resultInfo.pt) ? Type.noType : pt()); 2067 Type inferred = deferredAttr.attribSpeculative(tree, env, findDiamondResult).type; 2068 if (!inferred.isErroneous() && 2069 types.isAssignable(inferred, pt().hasTag(NONE) ? syms.objectType : pt(), types.noWarnings)) { 2070 String key = types.isSameType(clazztype, inferred) ? 2071 "diamond.redundant.args" : 2072 "diamond.redundant.args.1"; 2073 log.warning(tree.clazz.pos(), key, clazztype, inferred); 2074 } 2075 } finally { 2076 ta.arguments = prevTypeargs; 2077 } 2078 } 2079 } 2080 2081 private void checkLambdaCandidate(JCNewClass tree, ClassSymbol csym, Type clazztype) { 2082 if (allowLambda && 2083 identifyLambdaCandidate && 2084 clazztype.hasTag(CLASS) && 2085 !pt().hasTag(NONE) && 2086 types.isFunctionalInterface(clazztype.tsym)) { 2087 Symbol descriptor = types.findDescriptorSymbol(clazztype.tsym); 2088 int count = 0; 2089 boolean found = false; 2090 for (Symbol sym : csym.members().getElements()) { 2091 if ((sym.flags() & SYNTHETIC) != 0 || 2092 sym.isConstructor()) continue; 2093 count++; 2094 if (sym.kind != MTH || 2095 !sym.name.equals(descriptor.name)) continue; 2096 Type mtype = types.memberType(clazztype, sym); 2097 if (types.overrideEquivalent(mtype, types.memberType(clazztype, descriptor))) { 2098 found = true; 2099 } 2100 } 2101 if (found && count == 1) { 2102 log.note(tree.def, "potential.lambda.found"); 2103 } 2104 } 2105 } 2106 2107 /** Make an attributed null check tree. 2108 */ 2109 public JCExpression makeNullCheck(JCExpression arg) { 2110 // optimization: X.this is never null; skip null check 2111 Name name = TreeInfo.name(arg); 2112 if (name == names._this || name == names._super) return arg; 2113 2114 JCTree.Tag optag = NULLCHK; 2115 JCUnary tree = make.at(arg.pos).Unary(optag, arg); 2116 tree.operator = syms.nullcheck; 2117 tree.type = arg.type; 2118 return tree; 2119 } 2120 2121 public void visitNewArray(JCNewArray tree) { 2122 Type owntype = types.createErrorType(tree.type); 2123 Env<AttrContext> localEnv = env.dup(tree); 2124 Type elemtype; 2125 if (tree.elemtype != null) { 2126 elemtype = attribType(tree.elemtype, localEnv); 2127 chk.validate(tree.elemtype, localEnv); 2128 owntype = elemtype; 2129 for (List<JCExpression> l = tree.dims; l.nonEmpty(); l = l.tail) { 2130 attribExpr(l.head, localEnv, syms.intType); 2131 owntype = new ArrayType(owntype, syms.arrayClass); 2132 } 2133 } else { 2134 // we are seeing an untyped aggregate { ... } 2135 // this is allowed only if the prototype is an array 2136 if (pt().hasTag(ARRAY)) { 2137 elemtype = types.elemtype(pt()); 2138 } else { 2139 if (!pt().hasTag(ERROR)) { 2140 log.error(tree.pos(), "illegal.initializer.for.type", 2141 pt()); 2142 } 2143 elemtype = types.createErrorType(pt()); 2144 } 2145 } 2146 if (tree.elems != null) { 2147 attribExprs(tree.elems, localEnv, elemtype); 2148 owntype = new ArrayType(elemtype, syms.arrayClass); 2149 } 2150 if (!types.isReifiable(elemtype)) 2151 log.error(tree.pos(), "generic.array.creation"); 2152 result = check(tree, owntype, VAL, resultInfo); 2153 } 2154 2155 /* 2156 * A lambda expression can only be attributed when a target-type is available. 2157 * In addition, if the target-type is that of a functional interface whose 2158 * descriptor contains inference variables in argument position the lambda expression 2159 * is 'stuck' (see DeferredAttr). 2160 */ 2161 @Override 2162 public void visitLambda(final JCLambda that) { 2163 if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) { 2164 if (pt().hasTag(NONE)) { 2165 //lambda only allowed in assignment or method invocation/cast context 2166 log.error(that.pos(), "unexpected.lambda"); 2167 } 2168 result = that.type = types.createErrorType(pt()); 2169 return; 2170 } 2171 //create an environment for attribution of the lambda expression 2172 final Env<AttrContext> localEnv = lambdaEnv(that, env); 2173 boolean needsRecovery = 2174 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.CHECK; 2175 try { 2176 List<Type> explicitParamTypes = null; 2177 if (TreeInfo.isExplicitLambda(that)) { 2178 //attribute lambda parameters 2179 attribStats(that.params, localEnv); 2180 explicitParamTypes = TreeInfo.types(that.params); 2181 } 2182 2183 Type target; 2184 Type lambdaType; 2185 if (pt() != Type.recoveryType) { 2186 target = infer.instantiateFunctionalInterface(that, checkIntersectionTarget(that, resultInfo), explicitParamTypes, resultInfo.checkContext); 2187 lambdaType = types.findDescriptorType(target); 2188 chk.checkFunctionalInterface(that, target); 2189 } else { 2190 target = Type.recoveryType; 2191 lambdaType = fallbackDescriptorType(that); 2192 } 2193 2194 if (lambdaType.hasTag(FORALL)) { 2195 //lambda expression target desc cannot be a generic method 2196 resultInfo.checkContext.report(that, diags.fragment("invalid.generic.lambda.target", 2197 lambdaType, kindName(target.tsym), target.tsym)); 2198 result = that.type = types.createErrorType(pt()); 2199 return; 2200 } 2201 2202 if (!TreeInfo.isExplicitLambda(that)) { 2203 //add param type info in the AST 2204 List<Type> actuals = lambdaType.getParameterTypes(); 2205 List<JCVariableDecl> params = that.params; 2206 2207 boolean arityMismatch = false; 2208 2209 while (params.nonEmpty()) { 2210 if (actuals.isEmpty()) { 2211 //not enough actuals to perform lambda parameter inference 2212 arityMismatch = true; 2213 } 2214 //reset previously set info 2215 Type argType = arityMismatch ? 2216 syms.errType : 2217 actuals.head; 2218 params.head.vartype = make.Type(argType); 2219 params.head.sym = null; 2220 actuals = actuals.isEmpty() ? 2221 actuals : 2222 actuals.tail; 2223 params = params.tail; 2224 } 2225 2226 //attribute lambda parameters 2227 attribStats(that.params, localEnv); 2228 2229 if (arityMismatch) { 2230 resultInfo.checkContext.report(that, diags.fragment("incompatible.arg.types.in.lambda")); 2231 result = that.type = types.createErrorType(target); 2232 return; 2233 } 2234 } 2235 2236 //from this point on, no recovery is needed; if we are in assignment context 2237 //we will be able to attribute the whole lambda body, regardless of errors; 2238 //if we are in a 'check' method context, and the lambda is not compatible 2239 //with the target-type, it will be recovered anyway in Attr.checkId 2240 needsRecovery = false; 2241 2242 FunctionalReturnContext funcContext = that.getBodyKind() == JCLambda.BodyKind.EXPRESSION ? 2243 new ExpressionLambdaReturnContext((JCExpression)that.getBody(), resultInfo.checkContext) : 2244 new FunctionalReturnContext(resultInfo.checkContext); 2245 2246 ResultInfo bodyResultInfo = lambdaType.getReturnType() == Type.recoveryType ? 2247 recoveryInfo : 2248 new ResultInfo(VAL, lambdaType.getReturnType(), funcContext); 2249 localEnv.info.returnResult = bodyResultInfo; 2250 2251 if (that.getBodyKind() == JCLambda.BodyKind.EXPRESSION) { 2252 attribTree(that.getBody(), localEnv, bodyResultInfo); 2253 } else { 2254 JCBlock body = (JCBlock)that.body; 2255 attribStats(body.stats, localEnv); 2256 } 2257 2258 result = check(that, target, VAL, resultInfo); 2259 2260 boolean isSpeculativeRound = 2261 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE; 2262 2263 postAttr(that); 2264 flow.analyzeLambda(env, that, make, isSpeculativeRound); 2265 2266 checkLambdaCompatible(that, lambdaType, resultInfo.checkContext, isSpeculativeRound); 2267 2268 if (!isSpeculativeRound) { 2269 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), lambdaType, target); 2270 } 2271 result = check(that, target, VAL, resultInfo); 2272 } catch (Types.FunctionDescriptorLookupError ex) { 2273 JCDiagnostic cause = ex.getDiagnostic(); 2274 resultInfo.checkContext.report(that, cause); 2275 result = that.type = types.createErrorType(pt()); 2276 return; 2277 } finally { 2278 localEnv.info.scope.leave(); 2279 if (needsRecovery) { 2280 attribTree(that, env, recoveryInfo); 2281 } 2282 } 2283 } 2284 2285 private Type checkIntersectionTarget(DiagnosticPosition pos, ResultInfo resultInfo) { 2286 Type pt = resultInfo.pt; 2287 if (pt != Type.recoveryType && pt.isCompound()) { 2288 IntersectionClassType ict = (IntersectionClassType)pt; 2289 List<Type> bounds = ict.allInterfaces ? 2290 ict.getComponents().tail : 2291 ict.getComponents(); 2292 types.findDescriptorType(bounds.head); //propagate exception outwards! 2293 for (Type bound : bounds.tail) { 2294 if (!types.isMarkerInterface(bound)) { 2295 resultInfo.checkContext.report(pos, diags.fragment("secondary.bound.must.be.marker.intf", bound)); 2296 } 2297 } 2298 //for now (translation doesn't support intersection types) 2299 return bounds.head; 2300 } else { 2301 return pt; 2302 } 2303 } 2304 //where 2305 private Type fallbackDescriptorType(JCExpression tree) { 2306 switch (tree.getTag()) { 2307 case LAMBDA: 2308 JCLambda lambda = (JCLambda)tree; 2309 List<Type> argtypes = List.nil(); 2310 for (JCVariableDecl param : lambda.params) { 2311 argtypes = param.vartype != null ? 2312 argtypes.append(param.vartype.type) : 2313 argtypes.append(syms.errType); 2314 } 2315 return new MethodType(argtypes, Type.recoveryType, List.<Type>nil(), syms.methodClass); 2316 case REFERENCE: 2317 return new MethodType(List.<Type>nil(), Type.recoveryType, List.<Type>nil(), syms.methodClass); 2318 default: 2319 Assert.error("Cannot get here!"); 2320 } 2321 return null; 2322 } 2323 2324 private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env, final InferenceContext inferenceContext, final Type... ts) { 2325 checkAccessibleTypes(pos, env, inferenceContext, List.from(ts)); 2326 } 2327 2328 private void checkAccessibleTypes(final DiagnosticPosition pos, final Env<AttrContext> env, final InferenceContext inferenceContext, final List<Type> ts) { 2329 if (inferenceContext.free(ts)) { 2330 inferenceContext.addFreeTypeListener(ts, new FreeTypeListener() { 2331 @Override 2332 public void typesInferred(InferenceContext inferenceContext) { 2333 checkAccessibleTypes(pos, env, inferenceContext, inferenceContext.asInstTypes(ts, types)); 2334 } 2335 }); 2336 } else { 2337 for (Type t : ts) { 2338 rs.checkAccessibleType(env, t); 2339 } 2340 } 2341 } 2342 2343 /** 2344 * Lambda/method reference have a special check context that ensures 2345 * that i.e. a lambda return type is compatible with the expected 2346 * type according to both the inherited context and the assignment 2347 * context. 2348 */ 2349 class FunctionalReturnContext extends Check.NestedCheckContext { 2350 2351 FunctionalReturnContext(CheckContext enclosingContext) { 2352 super(enclosingContext); 2353 } 2354 2355 @Override 2356 public boolean compatible(Type found, Type req, Warner warn) { 2357 //return type must be compatible in both current context and assignment context 2358 return types.isAssignable(found, inferenceContext().asFree(req, types), warn) && 2359 super.compatible(found, req, warn); 2360 } 2361 @Override 2362 public void report(DiagnosticPosition pos, JCDiagnostic details) { 2363 enclosingContext.report(pos, diags.fragment("incompatible.ret.type.in.lambda", details)); 2364 } 2365 } 2366 2367 class ExpressionLambdaReturnContext extends FunctionalReturnContext { 2368 2369 JCExpression expr; 2370 2371 ExpressionLambdaReturnContext(JCExpression expr, CheckContext enclosingContext) { 2372 super(enclosingContext); 2373 this.expr = expr; 2374 } 2375 2376 @Override 2377 public boolean compatible(Type found, Type req, Warner warn) { 2378 //a void return is compatible with an expression statement lambda 2379 return TreeInfo.isExpressionStatement(expr) && req.hasTag(VOID) || 2380 super.compatible(found, req, warn); 2381 } 2382 } 2383 2384 /** 2385 * Lambda compatibility. Check that given return types, thrown types, parameter types 2386 * are compatible with the expected functional interface descriptor. This means that: 2387 * (i) parameter types must be identical to those of the target descriptor; (ii) return 2388 * types must be compatible with the return type of the expected descriptor; 2389 * (iii) thrown types must be 'included' in the thrown types list of the expected 2390 * descriptor. 2391 */ 2392 private void checkLambdaCompatible(JCLambda tree, Type descriptor, CheckContext checkContext, boolean speculativeAttr) { 2393 Type returnType = checkContext.inferenceContext().asFree(descriptor.getReturnType(), types); 2394 2395 //return values have already been checked - but if lambda has no return 2396 //values, we must ensure that void/value compatibility is correct; 2397 //this amounts at checking that, if a lambda body can complete normally, 2398 //the descriptor's return type must be void 2399 if (tree.getBodyKind() == JCLambda.BodyKind.STATEMENT && tree.canCompleteNormally && 2400 !returnType.hasTag(VOID) && returnType != Type.recoveryType) { 2401 checkContext.report(tree, diags.fragment("incompatible.ret.type.in.lambda", 2402 diags.fragment("missing.ret.val", returnType))); 2403 } 2404 2405 List<Type> argTypes = checkContext.inferenceContext().asFree(descriptor.getParameterTypes(), types); 2406 if (!types.isSameTypes(argTypes, TreeInfo.types(tree.params))) { 2407 checkContext.report(tree, diags.fragment("incompatible.arg.types.in.lambda")); 2408 } 2409 2410 if (!speculativeAttr) { 2411 List<Type> thrownTypes = checkContext.inferenceContext().asFree(descriptor.getThrownTypes(), types); 2412 if (chk.unhandled(tree.inferredThrownTypes == null ? List.<Type>nil() : tree.inferredThrownTypes, thrownTypes).nonEmpty()) { 2413 log.error(tree, "incompatible.thrown.types.in.lambda", tree.inferredThrownTypes); 2414 } 2415 } 2416 } 2417 2418 private Env<AttrContext> lambdaEnv(JCLambda that, Env<AttrContext> env) { 2419 Env<AttrContext> lambdaEnv; 2420 Symbol owner = env.info.scope.owner; 2421 if (owner.kind == VAR && owner.owner.kind == TYP) { 2422 //field initializer 2423 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dupUnshared())); 2424 lambdaEnv.info.scope.owner = 2425 new MethodSymbol(0, names.empty, null, 2426 env.info.scope.owner); 2427 } else { 2428 lambdaEnv = env.dup(that, env.info.dup(env.info.scope.dup())); 2429 } 2430 return lambdaEnv; 2431 } 2432 2433 @Override 2434 public void visitReference(final JCMemberReference that) { 2435 if (pt().isErroneous() || (pt().hasTag(NONE) && pt() != Type.recoveryType)) { 2436 if (pt().hasTag(NONE)) { 2437 //method reference only allowed in assignment or method invocation/cast context 2438 log.error(that.pos(), "unexpected.mref"); 2439 } 2440 result = that.type = types.createErrorType(pt()); 2441 return; 2442 } 2443 final Env<AttrContext> localEnv = env.dup(that); 2444 try { 2445 //attribute member reference qualifier - if this is a constructor 2446 //reference, the expected kind must be a type 2447 Type exprType = attribTree(that.expr, 2448 env, new ResultInfo(that.getMode() == ReferenceMode.INVOKE ? VAL | TYP : TYP, Type.noType)); 2449 2450 if (that.getMode() == JCMemberReference.ReferenceMode.NEW) { 2451 exprType = chk.checkConstructorRefType(that.expr, exprType); 2452 } 2453 2454 if (exprType.isErroneous()) { 2455 //if the qualifier expression contains problems, 2456 //give up atttribution of method reference 2457 result = that.type = exprType; 2458 return; 2459 } 2460 2461 if (TreeInfo.isStaticSelector(that.expr, names) && 2462 (that.getMode() != ReferenceMode.NEW || !that.expr.type.isRaw())) { 2463 //if the qualifier is a type, validate it 2464 chk.validate(that.expr, env); 2465 } 2466 2467 //attrib type-arguments 2468 List<Type> typeargtypes = List.nil(); 2469 if (that.typeargs != null) { 2470 typeargtypes = attribTypes(that.typeargs, localEnv); 2471 } 2472 2473 Type target; 2474 Type desc; 2475 if (pt() != Type.recoveryType) { 2476 target = infer.instantiateFunctionalInterface(that, checkIntersectionTarget(that, resultInfo), null, resultInfo.checkContext); 2477 desc = types.findDescriptorType(target); 2478 chk.checkFunctionalInterface(that, target); 2479 } else { 2480 target = Type.recoveryType; 2481 desc = fallbackDescriptorType(that); 2482 } 2483 2484 List<Type> argtypes = desc.getParameterTypes(); 2485 2486 boolean allowBoxing = 2487 resultInfo.checkContext.deferredAttrContext().phase.isBoxingRequired(); 2488 Pair<Symbol, Resolve.ReferenceLookupHelper> refResult = rs.resolveMemberReference(that.pos(), localEnv, that, 2489 that.expr.type, that.name, argtypes, typeargtypes, allowBoxing); 2490 2491 Symbol refSym = refResult.fst; 2492 Resolve.ReferenceLookupHelper lookupHelper = refResult.snd; 2493 2494 if (refSym.kind != MTH) { 2495 boolean targetError; 2496 switch (refSym.kind) { 2497 case ABSENT_MTH: 2498 targetError = false; 2499 break; 2500 case WRONG_MTH: 2501 case WRONG_MTHS: 2502 case AMBIGUOUS: 2503 case HIDDEN: 2504 case STATICERR: 2505 case MISSING_ENCL: 2506 targetError = true; 2507 break; 2508 default: 2509 Assert.error("unexpected result kind " + refSym.kind); 2510 targetError = false; 2511 } 2512 2513 JCDiagnostic detailsDiag = ((Resolve.ResolveError)refSym).getDiagnostic(JCDiagnostic.DiagnosticType.FRAGMENT, 2514 that, exprType.tsym, exprType, that.name, argtypes, typeargtypes); 2515 2516 JCDiagnostic.DiagnosticType diagKind = targetError ? 2517 JCDiagnostic.DiagnosticType.FRAGMENT : JCDiagnostic.DiagnosticType.ERROR; 2518 2519 JCDiagnostic diag = diags.create(diagKind, log.currentSource(), that, 2520 "invalid.mref", Kinds.kindName(that.getMode()), detailsDiag); 2521 2522 if (targetError && target == Type.recoveryType) { 2523 //a target error doesn't make sense during recovery stage 2524 //as we don't know what actual parameter types are 2525 result = that.type = target; 2526 return; 2527 } else { 2528 if (targetError) { 2529 resultInfo.checkContext.report(that, diag); 2530 } else { 2531 log.report(diag); 2532 } 2533 result = that.type = types.createErrorType(target); 2534 return; 2535 } 2536 } 2537 2538 if (resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) { 2539 if (refSym.isStatic() && TreeInfo.isStaticSelector(that.expr, names) && 2540 exprType.getTypeArguments().nonEmpty()) { 2541 //static ref with class type-args 2542 log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()), 2543 diags.fragment("static.mref.with.targs")); 2544 result = that.type = types.createErrorType(target); 2545 return; 2546 } 2547 2548 if (refSym.isStatic() && !TreeInfo.isStaticSelector(that.expr, names) && 2549 !lookupHelper.referenceKind(refSym).isUnbound()) { 2550 //no static bound mrefs 2551 log.error(that.expr.pos(), "invalid.mref", Kinds.kindName(that.getMode()), 2552 diags.fragment("static.bound.mref")); 2553 result = that.type = types.createErrorType(target); 2554 return; 2555 } 2556 } 2557 2558 if (desc.getReturnType() == Type.recoveryType) { 2559 // stop here 2560 result = that.type = target; 2561 return; 2562 } 2563 2564 that.sym = refSym.baseSymbol(); 2565 that.kind = lookupHelper.referenceKind(that.sym); 2566 2567 ResultInfo checkInfo = 2568 resultInfo.dup(newMethodTemplate( 2569 desc.getReturnType().hasTag(VOID) ? Type.noType : desc.getReturnType(), 2570 lookupHelper.argtypes, 2571 typeargtypes)); 2572 2573 Type refType = checkId(that, lookupHelper.site, refSym, localEnv, checkInfo); 2574 2575 if (!refType.isErroneous()) { 2576 refType = types.createMethodTypeWithReturn(refType, 2577 adjustMethodReturnType(lookupHelper.site, that.name, checkInfo.pt.getParameterTypes(), refType.getReturnType())); 2578 } 2579 2580 //go ahead with standard method reference compatibility check - note that param check 2581 //is a no-op (as this has been taken care during method applicability) 2582 boolean isSpeculativeRound = 2583 resultInfo.checkContext.deferredAttrContext().mode == DeferredAttr.AttrMode.SPECULATIVE; 2584 checkReferenceCompatible(that, desc, refType, resultInfo.checkContext, isSpeculativeRound); 2585 if (!isSpeculativeRound) { 2586 checkAccessibleTypes(that, localEnv, resultInfo.checkContext.inferenceContext(), desc, target); 2587 } 2588 result = check(that, target, VAL, resultInfo); 2589 } catch (Types.FunctionDescriptorLookupError ex) { 2590 JCDiagnostic cause = ex.getDiagnostic(); 2591 resultInfo.checkContext.report(that, cause); 2592 result = that.type = types.createErrorType(pt()); 2593 return; 2594 } 2595 } 2596 2597 @SuppressWarnings("fallthrough") 2598 void checkReferenceCompatible(JCMemberReference tree, Type descriptor, Type refType, CheckContext checkContext, boolean speculativeAttr) { 2599 Type returnType = checkContext.inferenceContext().asFree(descriptor.getReturnType(), types); 2600 2601 Type resType; 2602 switch (tree.getMode()) { 2603 case NEW: 2604 if (!tree.expr.type.isRaw()) { 2605 resType = tree.expr.type; 2606 break; 2607 } 2608 default: 2609 resType = refType.getReturnType(); 2610 } 2611 2612 Type incompatibleReturnType = resType; 2613 2614 if (returnType.hasTag(VOID)) { 2615 incompatibleReturnType = null; 2616 } 2617 2618 if (!returnType.hasTag(VOID) && !resType.hasTag(VOID)) { 2619 if (resType.isErroneous() || 2620 new FunctionalReturnContext(checkContext).compatible(resType, returnType, types.noWarnings)) { 2621 incompatibleReturnType = null; 2622 } 2623 } 2624 2625 if (incompatibleReturnType != null) { 2626 checkContext.report(tree, diags.fragment("incompatible.ret.type.in.mref", 2627 diags.fragment("inconvertible.types", resType, descriptor.getReturnType()))); 2628 } 2629 2630 if (!speculativeAttr) { 2631 List<Type> thrownTypes = checkContext.inferenceContext().asFree(descriptor.getThrownTypes(), types); 2632 if (chk.unhandled(refType.getThrownTypes(), thrownTypes).nonEmpty()) { 2633 log.error(tree, "incompatible.thrown.types.in.mref", refType.getThrownTypes()); 2634 } 2635 } 2636 } 2637 2638 public void visitParens(JCParens tree) { 2639 Type owntype = attribTree(tree.expr, env, resultInfo); 2640 result = check(tree, owntype, pkind(), resultInfo); 2641 Symbol sym = TreeInfo.symbol(tree); 2642 if (sym != null && (sym.kind&(TYP|PCK)) != 0) 2643 log.error(tree.pos(), "illegal.start.of.type"); 2644 } 2645 2646 public void visitAssign(JCAssign tree) { 2647 Type owntype = attribTree(tree.lhs, env.dup(tree), varInfo); 2648 Type capturedType = capture(owntype); 2649 attribExpr(tree.rhs, env, owntype); 2650 result = check(tree, capturedType, VAL, resultInfo); 2651 } 2652 2653 public void visitAssignop(JCAssignOp tree) { 2654 // Attribute arguments. 2655 Type owntype = attribTree(tree.lhs, env, varInfo); 2656 Type operand = attribExpr(tree.rhs, env); 2657 // Find operator. 2658 Symbol operator = tree.operator = rs.resolveBinaryOperator( 2659 tree.pos(), tree.getTag().noAssignOp(), env, 2660 owntype, operand); 2661 2662 if (operator.kind == MTH && 2663 !owntype.isErroneous() && 2664 !operand.isErroneous()) { 2665 chk.checkOperator(tree.pos(), 2666 (OperatorSymbol)operator, 2667 tree.getTag().noAssignOp(), 2668 owntype, 2669 operand); 2670 chk.checkDivZero(tree.rhs.pos(), operator, operand); 2671 chk.checkCastable(tree.rhs.pos(), 2672 operator.type.getReturnType(), 2673 owntype); 2674 } 2675 result = check(tree, owntype, VAL, resultInfo); 2676 } 2677 2678 public void visitUnary(JCUnary tree) { 2679 // Attribute arguments. 2680 Type argtype = (tree.getTag().isIncOrDecUnaryOp()) 2681 ? attribTree(tree.arg, env, varInfo) 2682 : chk.checkNonVoid(tree.arg.pos(), attribExpr(tree.arg, env)); 2683 2684 // Find operator. 2685 Symbol operator = tree.operator = 2686 rs.resolveUnaryOperator(tree.pos(), tree.getTag(), env, argtype); 2687 2688 Type owntype = types.createErrorType(tree.type); 2689 if (operator.kind == MTH && 2690 !argtype.isErroneous()) { 2691 owntype = (tree.getTag().isIncOrDecUnaryOp()) 2692 ? tree.arg.type 2693 : operator.type.getReturnType(); 2694 int opc = ((OperatorSymbol)operator).opcode; 2695 2696 // If the argument is constant, fold it. 2697 if (argtype.constValue() != null) { 2698 Type ctype = cfolder.fold1(opc, argtype); 2699 if (ctype != null) { 2700 owntype = cfolder.coerce(ctype, owntype); 2701 2702 // Remove constant types from arguments to 2703 // conserve space. The parser will fold concatenations 2704 // of string literals; the code here also 2705 // gets rid of intermediate results when some of the 2706 // operands are constant identifiers. 2707 if (tree.arg.type.tsym == syms.stringType.tsym) { 2708 tree.arg.type = syms.stringType; 2709 } 2710 } 2711 } 2712 } 2713 result = check(tree, owntype, VAL, resultInfo); 2714 } 2715 2716 public void visitBinary(JCBinary tree) { 2717 // Attribute arguments. 2718 Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env)); 2719 Type right = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.rhs, env)); 2720 2721 // Find operator. 2722 Symbol operator = tree.operator = 2723 rs.resolveBinaryOperator(tree.pos(), tree.getTag(), env, left, right); 2724 2725 Type owntype = types.createErrorType(tree.type); 2726 if (operator.kind == MTH && 2727 !left.isErroneous() && 2728 !right.isErroneous()) { 2729 owntype = operator.type.getReturnType(); 2730 int opc = chk.checkOperator(tree.lhs.pos(), 2731 (OperatorSymbol)operator, 2732 tree.getTag(), 2733 left, 2734 right); 2735 2736 // If both arguments are constants, fold them. 2737 if (left.constValue() != null && right.constValue() != null) { 2738 Type ctype = cfolder.fold2(opc, left, right); 2739 if (ctype != null) { 2740 owntype = cfolder.coerce(ctype, owntype); 2741 2742 // Remove constant types from arguments to 2743 // conserve space. The parser will fold concatenations 2744 // of string literals; the code here also 2745 // gets rid of intermediate results when some of the 2746 // operands are constant identifiers. 2747 if (tree.lhs.type.tsym == syms.stringType.tsym) { 2748 tree.lhs.type = syms.stringType; 2749 } 2750 if (tree.rhs.type.tsym == syms.stringType.tsym) { 2751 tree.rhs.type = syms.stringType; 2752 } 2753 } 2754 } 2755 2756 // Check that argument types of a reference ==, != are 2757 // castable to each other, (JLS???). 2758 if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) { 2759 if (!types.isCastable(left, right, new Warner(tree.pos()))) { 2760 log.error(tree.pos(), "incomparable.types", left, right); 2761 } 2762 } 2763 2764 chk.checkDivZero(tree.rhs.pos(), operator, right); 2765 } 2766 result = check(tree, owntype, VAL, resultInfo); 2767 } 2768 2769 public void visitTypeCast(final JCTypeCast tree) { 2770 Type clazztype = attribType(tree.clazz, env); 2771 chk.validate(tree.clazz, env, false); 2772 //a fresh environment is required for 292 inference to work properly --- 2773 //see Infer.instantiatePolymorphicSignatureInstance() 2774 Env<AttrContext> localEnv = env.dup(tree); 2775 //should we propagate the target type? 2776 final ResultInfo castInfo; 2777 final boolean isPoly = TreeInfo.isPoly(tree.expr, tree); 2778 if (isPoly) { 2779 //expression is a poly - we need to propagate target type info 2780 castInfo = new ResultInfo(VAL, clazztype, new Check.NestedCheckContext(resultInfo.checkContext) { 2781 @Override 2782 public boolean compatible(Type found, Type req, Warner warn) { 2783 return types.isCastable(found, req, warn); 2784 } 2785 }); 2786 } else { 2787 //standalone cast - target-type info is not propagated 2788 castInfo = unknownExprInfo; 2789 } 2790 Type exprtype = attribTree(tree.expr, localEnv, castInfo); 2791 Type owntype = isPoly ? clazztype : chk.checkCastable(tree.expr.pos(), exprtype, clazztype); 2792 if (exprtype.constValue() != null) 2793 owntype = cfolder.coerce(exprtype, owntype); 2794 result = check(tree, capture(owntype), VAL, resultInfo); 2795 if (!isPoly) 2796 chk.checkRedundantCast(localEnv, tree); 2797 } 2798 2799 public void visitTypeTest(JCInstanceOf tree) { 2800 Type exprtype = chk.checkNullOrRefType( 2801 tree.expr.pos(), attribExpr(tree.expr, env)); 2802 Type clazztype = chk.checkReifiableReferenceType( 2803 tree.clazz.pos(), attribType(tree.clazz, env)); 2804 chk.validate(tree.clazz, env, false); 2805 chk.checkCastable(tree.expr.pos(), exprtype, clazztype); 2806 result = check(tree, syms.booleanType, VAL, resultInfo); 2807 } 2808 2809 public void visitIndexed(JCArrayAccess tree) { 2810 Type owntype = types.createErrorType(tree.type); 2811 Type atype = attribExpr(tree.indexed, env); 2812 attribExpr(tree.index, env, syms.intType); 2813 if (types.isArray(atype)) 2814 owntype = types.elemtype(atype); 2815 else if (!atype.hasTag(ERROR)) 2816 log.error(tree.pos(), "array.req.but.found", atype); 2817 if ((pkind() & VAR) == 0) owntype = capture(owntype); 2818 result = check(tree, owntype, VAR, resultInfo); 2819 } 2820 2821 public void visitIdent(JCIdent tree) { 2822 Symbol sym; 2823 2824 // Find symbol 2825 if (pt().hasTag(METHOD) || pt().hasTag(FORALL)) { 2826 // If we are looking for a method, the prototype `pt' will be a 2827 // method type with the type of the call's arguments as parameters. 2828 env.info.pendingResolutionPhase = null; 2829 sym = rs.resolveMethod(tree.pos(), env, tree.name, pt().getParameterTypes(), pt().getTypeArguments()); 2830 } else if (tree.sym != null && tree.sym.kind != VAR) { 2831 sym = tree.sym; 2832 } else { 2833 sym = rs.resolveIdent(tree.pos(), env, tree.name, pkind()); 2834 } 2835 tree.sym = sym; 2836 2837 // (1) Also find the environment current for the class where 2838 // sym is defined (`symEnv'). 2839 // Only for pre-tiger versions (1.4 and earlier): 2840 // (2) Also determine whether we access symbol out of an anonymous 2841 // class in a this or super call. This is illegal for instance 2842 // members since such classes don't carry a this$n link. 2843 // (`noOuterThisPath'). 2844 Env<AttrContext> symEnv = env; 2845 boolean noOuterThisPath = false; 2846 if (env.enclClass.sym.owner.kind != PCK && // we are in an inner class 2847 (sym.kind & (VAR | MTH | TYP)) != 0 && 2848 sym.owner.kind == TYP && 2849 tree.name != names._this && tree.name != names._super) { 2850 2851 // Find environment in which identifier is defined. 2852 while (symEnv.outer != null && 2853 !sym.isMemberOf(symEnv.enclClass.sym, types)) { 2854 if ((symEnv.enclClass.sym.flags() & NOOUTERTHIS) != 0) 2855 noOuterThisPath = !allowAnonOuterThis; 2856 symEnv = symEnv.outer; 2857 } 2858 } 2859 2860 // If symbol is a variable, ... 2861 if (sym.kind == VAR) { 2862 VarSymbol v = (VarSymbol)sym; 2863 2864 // ..., evaluate its initializer, if it has one, and check for 2865 // illegal forward reference. 2866 checkInit(tree, env, v, false); 2867 2868 // If we are expecting a variable (as opposed to a value), check 2869 // that the variable is assignable in the current environment. 2870 if (pkind() == VAR) 2871 checkAssignable(tree.pos(), v, null, env); 2872 } 2873 2874 // In a constructor body, 2875 // if symbol is a field or instance method, check that it is 2876 // not accessed before the supertype constructor is called. 2877 if ((symEnv.info.isSelfCall || noOuterThisPath) && 2878 (sym.kind & (VAR | MTH)) != 0 && 2879 sym.owner.kind == TYP && 2880 (sym.flags() & STATIC) == 0) { 2881 chk.earlyRefError(tree.pos(), sym.kind == VAR ? sym : thisSym(tree.pos(), env)); 2882 } 2883 Env<AttrContext> env1 = env; 2884 if (sym.kind != ERR && sym.kind != TYP && sym.owner != null && sym.owner != env1.enclClass.sym) { 2885 // If the found symbol is inaccessible, then it is 2886 // accessed through an enclosing instance. Locate this 2887 // enclosing instance: 2888 while (env1.outer != null && !rs.isAccessible(env, env1.enclClass.sym.type, sym)) 2889 env1 = env1.outer; 2890 } 2891 result = checkId(tree, env1.enclClass.sym.type, sym, env, resultInfo); 2892 } 2893 2894 public void visitSelect(JCFieldAccess tree) { 2895 // Determine the expected kind of the qualifier expression. 2896 int skind = 0; 2897 if (tree.name == names._this || tree.name == names._super || 2898 tree.name == names._class) 2899 { 2900 skind = TYP; 2901 } else { 2902 if ((pkind() & PCK) != 0) skind = skind | PCK; 2903 if ((pkind() & TYP) != 0) skind = skind | TYP | PCK; 2904 if ((pkind() & (VAL | MTH)) != 0) skind = skind | VAL | TYP; 2905 } 2906 2907 // Attribute the qualifier expression, and determine its symbol (if any). 2908 Type site = attribTree(tree.selected, env, new ResultInfo(skind, Infer.anyPoly)); 2909 if ((pkind() & (PCK | TYP)) == 0) 2910 site = capture(site); // Capture field access 2911 2912 // don't allow T.class T[].class, etc 2913 if (skind == TYP) { 2914 Type elt = site; 2915 while (elt.hasTag(ARRAY)) 2916 elt = ((ArrayType)elt).elemtype; 2917 if (elt.hasTag(TYPEVAR)) { 2918 log.error(tree.pos(), "type.var.cant.be.deref"); 2919 result = types.createErrorType(tree.type); 2920 return; 2921 } 2922 } 2923 2924 // If qualifier symbol is a type or `super', assert `selectSuper' 2925 // for the selection. This is relevant for determining whether 2926 // protected symbols are accessible. 2927 Symbol sitesym = TreeInfo.symbol(tree.selected); 2928 boolean selectSuperPrev = env.info.selectSuper; 2929 env.info.selectSuper = 2930 sitesym != null && 2931 sitesym.name == names._super; 2932 2933 // Determine the symbol represented by the selection. 2934 env.info.pendingResolutionPhase = null; 2935 Symbol sym = selectSym(tree, sitesym, site, env, resultInfo); 2936 if (sym.exists() && !isType(sym) && (pkind() & (PCK | TYP)) != 0) { 2937 site = capture(site); 2938 sym = selectSym(tree, sitesym, site, env, resultInfo); 2939 } 2940 boolean varArgs = env.info.lastResolveVarargs(); 2941 tree.sym = sym; 2942 2943 if (site.hasTag(TYPEVAR) && !isType(sym) && sym.kind != ERR) { 2944 while (site.hasTag(TYPEVAR)) site = site.getUpperBound(); 2945 site = capture(site); 2946 } 2947 2948 // If that symbol is a variable, ... 2949 if (sym.kind == VAR) { 2950 VarSymbol v = (VarSymbol)sym; 2951 2952 // ..., evaluate its initializer, if it has one, and check for 2953 // illegal forward reference. 2954 checkInit(tree, env, v, true); 2955 2956 // If we are expecting a variable (as opposed to a value), check 2957 // that the variable is assignable in the current environment. 2958 if (pkind() == VAR) 2959 checkAssignable(tree.pos(), v, tree.selected, env); 2960 } 2961 2962 if (sitesym != null && 2963 sitesym.kind == VAR && 2964 ((VarSymbol)sitesym).isResourceVariable() && 2965 sym.kind == MTH && 2966 sym.name.equals(names.close) && 2967 sym.overrides(syms.autoCloseableClose, sitesym.type.tsym, types, true) && 2968 env.info.lint.isEnabled(LintCategory.TRY)) { 2969 log.warning(LintCategory.TRY, tree, "try.explicit.close.call"); 2970 } 2971 2972 // Disallow selecting a type from an expression 2973 if (isType(sym) && (sitesym==null || (sitesym.kind&(TYP|PCK)) == 0)) { 2974 tree.type = check(tree.selected, pt(), 2975 sitesym == null ? VAL : sitesym.kind, new ResultInfo(TYP|PCK, pt())); 2976 } 2977 2978 if (isType(sitesym)) { 2979 if (sym.name == names._this) { 2980 // If `C' is the currently compiled class, check that 2981 // C.this' does not appear in a call to a super(...) 2982 if (env.info.isSelfCall && 2983 site.tsym == env.enclClass.sym) { 2984 chk.earlyRefError(tree.pos(), sym); 2985 } 2986 } else { 2987 // Check if type-qualified fields or methods are static (JLS) 2988 if ((sym.flags() & STATIC) == 0 && 2989 !env.next.tree.hasTag(REFERENCE) && 2990 sym.name != names._super && 2991 (sym.kind == VAR || sym.kind == MTH)) { 2992 rs.accessBase(rs.new StaticError(sym), 2993 tree.pos(), site, sym.name, true); 2994 } 2995 } 2996 } else if (sym.kind != ERR && (sym.flags() & STATIC) != 0 && sym.name != names._class) { 2997 // If the qualified item is not a type and the selected item is static, report 2998 // a warning. Make allowance for the class of an array type e.g. Object[].class) 2999 chk.warnStatic(tree, "static.not.qualified.by.type", Kinds.kindName(sym.kind), sym.owner); 3000 } 3001 3002 // If we are selecting an instance member via a `super', ... 3003 if (env.info.selectSuper && (sym.flags() & STATIC) == 0) { 3004 3005 // Check that super-qualified symbols are not abstract (JLS) 3006 rs.checkNonAbstract(tree.pos(), sym); 3007 3008 if (site.isRaw()) { 3009 // Determine argument types for site. 3010 Type site1 = types.asSuper(env.enclClass.sym.type, site.tsym); 3011 if (site1 != null) site = site1; 3012 } 3013 } 3014 3015 env.info.selectSuper = selectSuperPrev; 3016 result = checkId(tree, site, sym, env, resultInfo); 3017 } 3018 //where 3019 /** Determine symbol referenced by a Select expression, 3020 * 3021 * @param tree The select tree. 3022 * @param site The type of the selected expression, 3023 * @param env The current environment. 3024 * @param resultInfo The current result. 3025 */ 3026 private Symbol selectSym(JCFieldAccess tree, 3027 Symbol location, 3028 Type site, 3029 Env<AttrContext> env, 3030 ResultInfo resultInfo) { 3031 DiagnosticPosition pos = tree.pos(); 3032 Name name = tree.name; 3033 switch (site.getTag()) { 3034 case PACKAGE: 3035 return rs.accessBase( 3036 rs.findIdentInPackage(env, site.tsym, name, resultInfo.pkind), 3037 pos, location, site, name, true); 3038 case ARRAY: 3039 case CLASS: 3040 if (resultInfo.pt.hasTag(METHOD) || resultInfo.pt.hasTag(FORALL)) { 3041 return rs.resolveQualifiedMethod( 3042 pos, env, location, site, name, resultInfo.pt.getParameterTypes(), resultInfo.pt.getTypeArguments()); 3043 } else if (name == names._this || name == names._super) { 3044 return rs.resolveSelf(pos, env, site.tsym, name); 3045 } else if (name == names._class) { 3046 // In this case, we have already made sure in 3047 // visitSelect that qualifier expression is a type. 3048 Type t = syms.classType; 3049 List<Type> typeargs = allowGenerics 3050 ? List.of(types.erasure(site)) 3051 : List.<Type>nil(); 3052 t = new ClassType(t.getEnclosingType(), typeargs, t.tsym); 3053 return new VarSymbol( 3054 STATIC | PUBLIC | FINAL, names._class, t, site.tsym); 3055 } else { 3056 // We are seeing a plain identifier as selector. 3057 Symbol sym = rs.findIdentInType(env, site, name, resultInfo.pkind); 3058 if ((resultInfo.pkind & ERRONEOUS) == 0) 3059 sym = rs.accessBase(sym, pos, location, site, name, true); 3060 return sym; 3061 } 3062 case WILDCARD: 3063 throw new AssertionError(tree); 3064 case TYPEVAR: 3065 // Normally, site.getUpperBound() shouldn't be null. 3066 // It should only happen during memberEnter/attribBase 3067 // when determining the super type which *must* beac 3068 // done before attributing the type variables. In 3069 // other words, we are seeing this illegal program: 3070 // class B<T> extends A<T.foo> {} 3071 Symbol sym = (site.getUpperBound() != null) 3072 ? selectSym(tree, location, capture(site.getUpperBound()), env, resultInfo) 3073 : null; 3074 if (sym == null) { 3075 log.error(pos, "type.var.cant.be.deref"); 3076 return syms.errSymbol; 3077 } else { 3078 Symbol sym2 = (sym.flags() & Flags.PRIVATE) != 0 ? 3079 rs.new AccessError(env, site, sym) : 3080 sym; 3081 rs.accessBase(sym2, pos, location, site, name, true); 3082 return sym; 3083 } 3084 case ERROR: 3085 // preserve identifier names through errors 3086 return types.createErrorType(name, site.tsym, site).tsym; 3087 default: 3088 // The qualifier expression is of a primitive type -- only 3089 // .class is allowed for these. 3090 if (name == names._class) { 3091 // In this case, we have already made sure in Select that 3092 // qualifier expression is a type. 3093 Type t = syms.classType; 3094 Type arg = types.boxedClass(site).type; 3095 t = new ClassType(t.getEnclosingType(), List.of(arg), t.tsym); 3096 return new VarSymbol( 3097 STATIC | PUBLIC | FINAL, names._class, t, site.tsym); 3098 } else { 3099 log.error(pos, "cant.deref", site); 3100 return syms.errSymbol; 3101 } 3102 } 3103 } 3104 3105 /** Determine type of identifier or select expression and check that 3106 * (1) the referenced symbol is not deprecated 3107 * (2) the symbol's type is safe (@see checkSafe) 3108 * (3) if symbol is a variable, check that its type and kind are 3109 * compatible with the prototype and protokind. 3110 * (4) if symbol is an instance field of a raw type, 3111 * which is being assigned to, issue an unchecked warning if its 3112 * type changes under erasure. 3113 * (5) if symbol is an instance method of a raw type, issue an 3114 * unchecked warning if its argument types change under erasure. 3115 * If checks succeed: 3116 * If symbol is a constant, return its constant type 3117 * else if symbol is a method, return its result type 3118 * otherwise return its type. 3119 * Otherwise return errType. 3120 * 3121 * @param tree The syntax tree representing the identifier 3122 * @param site If this is a select, the type of the selected 3123 * expression, otherwise the type of the current class. 3124 * @param sym The symbol representing the identifier. 3125 * @param env The current environment. 3126 * @param resultInfo The expected result 3127 */ 3128 Type checkId(JCTree tree, 3129 Type site, 3130 Symbol sym, 3131 Env<AttrContext> env, 3132 ResultInfo resultInfo) { 3133 return (resultInfo.pt.hasTag(FORALL) || resultInfo.pt.hasTag(METHOD)) ? 3134 checkMethodId(tree, site, sym, env, resultInfo) : 3135 checkIdInternal(tree, site, sym, resultInfo.pt, env, resultInfo); 3136 } 3137 3138 Type checkMethodId(JCTree tree, 3139 Type site, 3140 Symbol sym, 3141 Env<AttrContext> env, 3142 ResultInfo resultInfo) { 3143 boolean isPolymorhicSignature = 3144 sym.kind == MTH && ((MethodSymbol)sym.baseSymbol()).isSignaturePolymorphic(types); 3145 return isPolymorhicSignature ? 3146 checkSigPolyMethodId(tree, site, sym, env, resultInfo) : 3147 checkMethodIdInternal(tree, site, sym, env, resultInfo); 3148 } 3149 3150 Type checkSigPolyMethodId(JCTree tree, 3151 Type site, 3152 Symbol sym, 3153 Env<AttrContext> env, 3154 ResultInfo resultInfo) { 3155 //recover original symbol for signature polymorphic methods 3156 checkMethodIdInternal(tree, site, sym.baseSymbol(), env, resultInfo); 3157 env.info.pendingResolutionPhase = Resolve.MethodResolutionPhase.BASIC; 3158 return sym.type; 3159 } 3160 3161 Type checkMethodIdInternal(JCTree tree, 3162 Type site, 3163 Symbol sym, 3164 Env<AttrContext> env, 3165 ResultInfo resultInfo) { 3166 Type pt = resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.SPECULATIVE, sym, env.info.pendingResolutionPhase)); 3167 Type owntype = checkIdInternal(tree, site, sym, pt, env, resultInfo); 3168 resultInfo.pt.map(deferredAttr.new RecoveryDeferredTypeMap(AttrMode.CHECK, sym, env.info.pendingResolutionPhase)); 3169 return owntype; 3170 } 3171 3172 Type checkIdInternal(JCTree tree, 3173 Type site, 3174 Symbol sym, 3175 Type pt, 3176 Env<AttrContext> env, 3177 ResultInfo resultInfo) { 3178 if (pt.isErroneous()) { 3179 return types.createErrorType(site); 3180 } 3181 Type owntype; // The computed type of this identifier occurrence. 3182 switch (sym.kind) { 3183 case TYP: 3184 // For types, the computed type equals the symbol's type, 3185 // except for two situations: 3186 owntype = sym.type; 3187 if (owntype.hasTag(CLASS)) { 3188 chk.checkForBadAuxiliaryClassAccess(tree.pos(), env, (ClassSymbol)sym); 3189 Type ownOuter = owntype.getEnclosingType(); 3190 3191 // (a) If the symbol's type is parameterized, erase it 3192 // because no type parameters were given. 3193 // We recover generic outer type later in visitTypeApply. 3194 if (owntype.tsym.type.getTypeArguments().nonEmpty()) { 3195 owntype = types.erasure(owntype); 3196 } 3197 3198 // (b) If the symbol's type is an inner class, then 3199 // we have to interpret its outer type as a superclass 3200 // of the site type. Example: 3201 // 3202 // class Tree<A> { class Visitor { ... } } 3203 // class PointTree extends Tree<Point> { ... } 3204 // ...PointTree.Visitor... 3205 // 3206 // Then the type of the last expression above is 3207 // Tree<Point>.Visitor. 3208 else if (ownOuter.hasTag(CLASS) && site != ownOuter) { 3209 Type normOuter = site; 3210 if (normOuter.hasTag(CLASS)) 3211 normOuter = types.asEnclosingSuper(site, ownOuter.tsym); 3212 if (normOuter == null) // perhaps from an import 3213 normOuter = types.erasure(ownOuter); 3214 if (normOuter != ownOuter) 3215 owntype = new ClassType( 3216 normOuter, List.<Type>nil(), owntype.tsym); 3217 } 3218 } 3219 break; 3220 case VAR: 3221 VarSymbol v = (VarSymbol)sym; 3222 // Test (4): if symbol is an instance field of a raw type, 3223 // which is being assigned to, issue an unchecked warning if 3224 // its type changes under erasure. 3225 if (allowGenerics && 3226 resultInfo.pkind == VAR && 3227 v.owner.kind == TYP && 3228 (v.flags() & STATIC) == 0 && 3229 (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) { 3230 Type s = types.asOuterSuper(site, v.owner); 3231 if (s != null && 3232 s.isRaw() && 3233 !types.isSameType(v.type, v.erasure(types))) { 3234 chk.warnUnchecked(tree.pos(), 3235 "unchecked.assign.to.var", 3236 v, s); 3237 } 3238 } 3239 // The computed type of a variable is the type of the 3240 // variable symbol, taken as a member of the site type. 3241 owntype = (sym.owner.kind == TYP && 3242 sym.name != names._this && sym.name != names._super) 3243 ? types.memberType(site, sym) 3244 : sym.type; 3245 3246 // If the variable is a constant, record constant value in 3247 // computed type. 3248 if (v.getConstValue() != null && isStaticReference(tree)) 3249 owntype = owntype.constType(v.getConstValue()); 3250 3251 if (resultInfo.pkind == VAL) { 3252 owntype = capture(owntype); // capture "names as expressions" 3253 } 3254 break; 3255 case MTH: { 3256 owntype = checkMethod(site, sym, 3257 new ResultInfo(VAL, resultInfo.pt.getReturnType(), resultInfo.checkContext), 3258 env, TreeInfo.args(env.tree), resultInfo.pt.getParameterTypes(), 3259 resultInfo.pt.getTypeArguments()); 3260 break; 3261 } 3262 case PCK: case ERR: 3263 owntype = sym.type; 3264 break; 3265 default: 3266 throw new AssertionError("unexpected kind: " + sym.kind + 3267 " in tree " + tree); 3268 } 3269 3270 // Test (1): emit a `deprecation' warning if symbol is deprecated. 3271 // (for constructors, the error was given when the constructor was 3272 // resolved) 3273 3274 if (sym.name != names.init) { 3275 chk.checkDeprecated(tree.pos(), env.info.scope.owner, sym); 3276 chk.checkSunAPI(tree.pos(), sym); 3277 } 3278 3279 // Test (3): if symbol is a variable, check that its type and 3280 // kind are compatible with the prototype and protokind. 3281 return check(tree, owntype, sym.kind, resultInfo); 3282 } 3283 3284 /** Check that variable is initialized and evaluate the variable's 3285 * initializer, if not yet done. Also check that variable is not 3286 * referenced before it is defined. 3287 * @param tree The tree making up the variable reference. 3288 * @param env The current environment. 3289 * @param v The variable's symbol. 3290 */ 3291 private void checkInit(JCTree tree, 3292 Env<AttrContext> env, 3293 VarSymbol v, 3294 boolean onlyWarning) { 3295 // System.err.println(v + " " + ((v.flags() & STATIC) != 0) + " " + 3296 // tree.pos + " " + v.pos + " " + 3297 // Resolve.isStatic(env));//DEBUG 3298 3299 // A forward reference is diagnosed if the declaration position 3300 // of the variable is greater than the current tree position 3301 // and the tree and variable definition occur in the same class 3302 // definition. Note that writes don't count as references. 3303 // This check applies only to class and instance 3304 // variables. Local variables follow different scope rules, 3305 // and are subject to definite assignment checking. 3306 if ((env.info.enclVar == v || v.pos > tree.pos) && 3307 v.owner.kind == TYP && 3308 canOwnInitializer(owner(env)) && 3309 v.owner == env.info.scope.owner.enclClass() && 3310 ((v.flags() & STATIC) != 0) == Resolve.isStatic(env) && 3311 (!env.tree.hasTag(ASSIGN) || 3312 TreeInfo.skipParens(((JCAssign) env.tree).lhs) != tree)) { 3313 String suffix = (env.info.enclVar == v) ? 3314 "self.ref" : "forward.ref"; 3315 if (!onlyWarning || isStaticEnumField(v)) { 3316 log.error(tree.pos(), "illegal." + suffix); 3317 } else if (useBeforeDeclarationWarning) { 3318 log.warning(tree.pos(), suffix, v); 3319 } 3320 } 3321 3322 v.getConstValue(); // ensure initializer is evaluated 3323 3324 checkEnumInitializer(tree, env, v); 3325 } 3326 3327 /** 3328 * Check for illegal references to static members of enum. In 3329 * an enum type, constructors and initializers may not 3330 * reference its static members unless they are constant. 3331 * 3332 * @param tree The tree making up the variable reference. 3333 * @param env The current environment. 3334 * @param v The variable's symbol. 3335 * @jls section 8.9 Enums 3336 */ 3337 private void checkEnumInitializer(JCTree tree, Env<AttrContext> env, VarSymbol v) { 3338 // JLS: 3339 // 3340 // "It is a compile-time error to reference a static field 3341 // of an enum type that is not a compile-time constant 3342 // (15.28) from constructors, instance initializer blocks, 3343 // or instance variable initializer expressions of that 3344 // type. It is a compile-time error for the constructors, 3345 // instance initializer blocks, or instance variable 3346 // initializer expressions of an enum constant e to refer 3347 // to itself or to an enum constant of the same type that 3348 // is declared to the right of e." 3349 if (isStaticEnumField(v)) { 3350 ClassSymbol enclClass = env.info.scope.owner.enclClass(); 3351 3352 if (enclClass == null || enclClass.owner == null) 3353 return; 3354 3355 // See if the enclosing class is the enum (or a 3356 // subclass thereof) declaring v. If not, this 3357 // reference is OK. 3358 if (v.owner != enclClass && !types.isSubtype(enclClass.type, v.owner.type)) 3359 return; 3360 3361 // If the reference isn't from an initializer, then 3362 // the reference is OK. 3363 if (!Resolve.isInitializer(env)) 3364 return; 3365 3366 log.error(tree.pos(), "illegal.enum.static.ref"); 3367 } 3368 } 3369 3370 /** Is the given symbol a static, non-constant field of an Enum? 3371 * Note: enum literals should not be regarded as such 3372 */ 3373 private boolean isStaticEnumField(VarSymbol v) { 3374 return Flags.isEnum(v.owner) && 3375 Flags.isStatic(v) && 3376 !Flags.isConstant(v) && 3377 v.name != names._class; 3378 } 3379 3380 /** Can the given symbol be the owner of code which forms part 3381 * if class initialization? This is the case if the symbol is 3382 * a type or field, or if the symbol is the synthetic method. 3383 * owning a block. 3384 */ 3385 private boolean canOwnInitializer(Symbol sym) { 3386 return 3387 (sym.kind & (VAR | TYP)) != 0 || 3388 (sym.kind == MTH && (sym.flags() & BLOCK) != 0); 3389 } 3390 3391 Warner noteWarner = new Warner(); 3392 3393 /** 3394 * Check that method arguments conform to its instantiation. 3395 **/ 3396 public Type checkMethod(Type site, 3397 Symbol sym, 3398 ResultInfo resultInfo, 3399 Env<AttrContext> env, 3400 final List<JCExpression> argtrees, 3401 List<Type> argtypes, 3402 List<Type> typeargtypes) { 3403 // Test (5): if symbol is an instance method of a raw type, issue 3404 // an unchecked warning if its argument types change under erasure. 3405 if (allowGenerics && 3406 (sym.flags() & STATIC) == 0 && 3407 (site.hasTag(CLASS) || site.hasTag(TYPEVAR))) { 3408 Type s = types.asOuterSuper(site, sym.owner); 3409 if (s != null && s.isRaw() && 3410 !types.isSameTypes(sym.type.getParameterTypes(), 3411 sym.erasure(types).getParameterTypes())) { 3412 chk.warnUnchecked(env.tree.pos(), 3413 "unchecked.call.mbr.of.raw.type", 3414 sym, s); 3415 } 3416 } 3417 3418 if (env.info.defaultSuperCallSite != null) { 3419 for (Type sup : types.interfaces(env.enclClass.type).prepend(types.supertype((env.enclClass.type)))) { 3420 if (!sup.tsym.isSubClass(sym.enclClass(), types) || 3421 types.isSameType(sup, env.info.defaultSuperCallSite)) continue; 3422 List<MethodSymbol> icand_sup = 3423 types.interfaceCandidates(sup, (MethodSymbol)sym); 3424 if (icand_sup.nonEmpty() && 3425 icand_sup.head != sym && 3426 icand_sup.head.overrides(sym, icand_sup.head.enclClass(), types, true)) { 3427 log.error(env.tree.pos(), "illegal.default.super.call", env.info.defaultSuperCallSite, 3428 diags.fragment("overridden.default", sym, sup)); 3429 break; 3430 } 3431 } 3432 env.info.defaultSuperCallSite = null; 3433 } 3434 3435 // Compute the identifier's instantiated type. 3436 // For methods, we need to compute the instance type by 3437 // Resolve.instantiate from the symbol's type as well as 3438 // any type arguments and value arguments. 3439 noteWarner.clear(); 3440 try { 3441 Type owntype = rs.checkMethod( 3442 env, 3443 site, 3444 sym, 3445 resultInfo, 3446 argtypes, 3447 typeargtypes, 3448 noteWarner); 3449 3450 return chk.checkMethod(owntype, sym, env, argtrees, argtypes, env.info.lastResolveVarargs(), 3451 noteWarner.hasNonSilentLint(LintCategory.UNCHECKED)); 3452 } catch (Infer.InferenceException ex) { 3453 //invalid target type - propagate exception outwards or report error 3454 //depending on the current check context 3455 resultInfo.checkContext.report(env.tree.pos(), ex.getDiagnostic()); 3456 return types.createErrorType(site); 3457 } catch (Resolve.InapplicableMethodException ex) { 3458 Assert.error(ex.getDiagnostic().getMessage(Locale.getDefault())); 3459 return null; 3460 } 3461 } 3462 3463 public void visitLiteral(JCLiteral tree) { 3464 result = check( 3465 tree, litType(tree.typetag).constType(tree.value), VAL, resultInfo); 3466 } 3467 //where 3468 /** Return the type of a literal with given type tag. 3469 */ 3470 Type litType(TypeTag tag) { 3471 return (tag == CLASS) ? syms.stringType : syms.typeOfTag[tag.ordinal()]; 3472 } 3473 3474 public void visitTypeIdent(JCPrimitiveTypeTree tree) { 3475 result = check(tree, syms.typeOfTag[tree.typetag.ordinal()], TYP, resultInfo); 3476 } 3477 3478 public void visitTypeArray(JCArrayTypeTree tree) { 3479 Type etype = attribType(tree.elemtype, env); 3480 Type type = new ArrayType(etype, syms.arrayClass); 3481 result = check(tree, type, TYP, resultInfo); 3482 } 3483 3484 /** Visitor method for parameterized types. 3485 * Bound checking is left until later, since types are attributed 3486 * before supertype structure is completely known 3487 */ 3488 public void visitTypeApply(JCTypeApply tree) { 3489 Type owntype = types.createErrorType(tree.type); 3490 3491 // Attribute functor part of application and make sure it's a class. 3492 Type clazztype = chk.checkClassType(tree.clazz.pos(), attribType(tree.clazz, env)); 3493 3494 // Attribute type parameters 3495 List<Type> actuals = attribTypes(tree.arguments, env); 3496 3497 if (clazztype.hasTag(CLASS)) { 3498 List<Type> formals = clazztype.tsym.type.getTypeArguments(); 3499 if (actuals.isEmpty()) //diamond 3500 actuals = formals; 3501 3502 if (actuals.length() == formals.length()) { 3503 List<Type> a = actuals; 3504 List<Type> f = formals; 3505 while (a.nonEmpty()) { 3506 a.head = a.head.withTypeVar(f.head); 3507 a = a.tail; 3508 f = f.tail; 3509 } 3510 // Compute the proper generic outer 3511 Type clazzOuter = clazztype.getEnclosingType(); 3512 if (clazzOuter.hasTag(CLASS)) { 3513 Type site; 3514 JCExpression clazz = TreeInfo.typeIn(tree.clazz); 3515 if (clazz.hasTag(IDENT)) { 3516 site = env.enclClass.sym.type; 3517 } else if (clazz.hasTag(SELECT)) { 3518 site = ((JCFieldAccess) clazz).selected.type; 3519 } else throw new AssertionError(""+tree); 3520 if (clazzOuter.hasTag(CLASS) && site != clazzOuter) { 3521 if (site.hasTag(CLASS)) 3522 site = types.asOuterSuper(site, clazzOuter.tsym); 3523 if (site == null) 3524 site = types.erasure(clazzOuter); 3525 clazzOuter = site; 3526 } 3527 } 3528 owntype = new ClassType(clazzOuter, actuals, clazztype.tsym); 3529 } else { 3530 if (formals.length() != 0) { 3531 log.error(tree.pos(), "wrong.number.type.args", 3532 Integer.toString(formals.length())); 3533 } else { 3534 log.error(tree.pos(), "type.doesnt.take.params", clazztype.tsym); 3535 } 3536 owntype = types.createErrorType(tree.type); 3537 } 3538 } 3539 result = check(tree, owntype, TYP, resultInfo); 3540 } 3541 3542 public void visitTypeUnion(JCTypeUnion tree) { 3543 ListBuffer<Type> multicatchTypes = ListBuffer.lb(); 3544 ListBuffer<Type> all_multicatchTypes = null; // lazy, only if needed 3545 for (JCExpression typeTree : tree.alternatives) { 3546 Type ctype = attribType(typeTree, env); 3547 ctype = chk.checkType(typeTree.pos(), 3548 chk.checkClassType(typeTree.pos(), ctype), 3549 syms.throwableType); 3550 if (!ctype.isErroneous()) { 3551 //check that alternatives of a union type are pairwise 3552 //unrelated w.r.t. subtyping 3553 if (chk.intersects(ctype, multicatchTypes.toList())) { 3554 for (Type t : multicatchTypes) { 3555 boolean sub = types.isSubtype(ctype, t); 3556 boolean sup = types.isSubtype(t, ctype); 3557 if (sub || sup) { 3558 //assume 'a' <: 'b' 3559 Type a = sub ? ctype : t; 3560 Type b = sub ? t : ctype; 3561 log.error(typeTree.pos(), "multicatch.types.must.be.disjoint", a, b); 3562 } 3563 } 3564 } 3565 multicatchTypes.append(ctype); 3566 if (all_multicatchTypes != null) 3567 all_multicatchTypes.append(ctype); 3568 } else { 3569 if (all_multicatchTypes == null) { 3570 all_multicatchTypes = ListBuffer.lb(); 3571 all_multicatchTypes.appendList(multicatchTypes); 3572 } 3573 all_multicatchTypes.append(ctype); 3574 } 3575 } 3576 Type t = check(tree, types.lub(multicatchTypes.toList()), TYP, resultInfo); 3577 if (t.hasTag(CLASS)) { 3578 List<Type> alternatives = 3579 ((all_multicatchTypes == null) ? multicatchTypes : all_multicatchTypes).toList(); 3580 t = new UnionClassType((ClassType) t, alternatives); 3581 } 3582 tree.type = result = t; 3583 } 3584 3585 public void visitTypeIntersection(JCTypeIntersection tree) { 3586 attribTypes(tree.bounds, env); 3587 tree.type = result = checkIntersection(tree, tree.bounds); 3588 } 3589 3590 public void visitTypeParameter(JCTypeParameter tree) { 3591 TypeVar typeVar = (TypeVar)tree.type; 3592 if (!typeVar.bound.isErroneous()) { 3593 //fixup type-parameter bound computed in 'attribTypeVariables' 3594 typeVar.bound = checkIntersection(tree, tree.bounds); 3595 } 3596 } 3597 3598 Type checkIntersection(JCTree tree, List<JCExpression> bounds) { 3599 Set<Type> boundSet = new HashSet<Type>(); 3600 if (bounds.nonEmpty()) { 3601 // accept class or interface or typevar as first bound. 3602 bounds.head.type = checkBase(bounds.head.type, bounds.head, env, false, false, false); 3603 boundSet.add(types.erasure(bounds.head.type)); 3604 if (bounds.head.type.isErroneous()) { 3605 return bounds.head.type; 3606 } 3607 else if (bounds.head.type.hasTag(TYPEVAR)) { 3608 // if first bound was a typevar, do not accept further bounds. 3609 if (bounds.tail.nonEmpty()) { 3610 log.error(bounds.tail.head.pos(), 3611 "type.var.may.not.be.followed.by.other.bounds"); 3612 return bounds.head.type; 3613 } 3614 } else { 3615 // if first bound was a class or interface, accept only interfaces 3616 // as further bounds. 3617 for (JCExpression bound : bounds.tail) { 3618 bound.type = checkBase(bound.type, bound, env, false, true, false); 3619 if (bound.type.isErroneous()) { 3620 bounds = List.of(bound); 3621 } 3622 else if (bound.type.hasTag(CLASS)) { 3623 chk.checkNotRepeated(bound.pos(), types.erasure(bound.type), boundSet); 3624 } 3625 } 3626 } 3627 } 3628 3629 if (bounds.length() == 0) { 3630 return syms.objectType; 3631 } else if (bounds.length() == 1) { 3632 return bounds.head.type; 3633 } else { 3634 Type owntype = types.makeCompoundType(TreeInfo.types(bounds)); 3635 if (tree.hasTag(TYPEINTERSECTION)) { 3636 ((IntersectionClassType)owntype).intersectionKind = 3637 IntersectionClassType.IntersectionKind.EXPLICIT; 3638 } 3639 // ... the variable's bound is a class type flagged COMPOUND 3640 // (see comment for TypeVar.bound). 3641 // In this case, generate a class tree that represents the 3642 // bound class, ... 3643 JCExpression extending; 3644 List<JCExpression> implementing; 3645 if (!bounds.head.type.isInterface()) { 3646 extending = bounds.head; 3647 implementing = bounds.tail; 3648 } else { 3649 extending = null; 3650 implementing = bounds; 3651 } 3652 JCClassDecl cd = make.at(tree).ClassDef( 3653 make.Modifiers(PUBLIC | ABSTRACT), 3654 names.empty, List.<JCTypeParameter>nil(), 3655 extending, implementing, List.<JCTree>nil()); 3656 3657 ClassSymbol c = (ClassSymbol)owntype.tsym; 3658 Assert.check((c.flags() & COMPOUND) != 0); 3659 cd.sym = c; 3660 c.sourcefile = env.toplevel.sourcefile; 3661 3662 // ... and attribute the bound class 3663 c.flags_field |= UNATTRIBUTED; 3664 Env<AttrContext> cenv = enter.classEnv(cd, env); 3665 enter.typeEnvs.put(c, cenv); 3666 attribClass(c); 3667 return owntype; 3668 } 3669 } 3670 3671 public void visitWildcard(JCWildcard tree) { 3672 //- System.err.println("visitWildcard("+tree+");");//DEBUG 3673 Type type = (tree.kind.kind == BoundKind.UNBOUND) 3674 ? syms.objectType 3675 : attribType(tree.inner, env); 3676 result = check(tree, new WildcardType(chk.checkRefType(tree.pos(), type), 3677 tree.kind.kind, 3678 syms.boundClass), 3679 TYP, resultInfo); 3680 } 3681 3682 public void visitAnnotation(JCAnnotation tree) { 3683 log.error(tree.pos(), "annotation.not.valid.for.type", pt()); 3684 result = tree.type = syms.errType; 3685 } 3686 3687 public void visitErroneous(JCErroneous tree) { 3688 if (tree.errs != null) 3689 for (JCTree err : tree.errs) 3690 attribTree(err, env, new ResultInfo(ERR, pt())); 3691 result = tree.type = syms.errType; 3692 } 3693 3694 /** Default visitor method for all other trees. 3695 */ 3696 public void visitTree(JCTree tree) { 3697 throw new AssertionError(); 3698 } 3699 3700 /** 3701 * Attribute an env for either a top level tree or class declaration. 3702 */ 3703 public void attrib(Env<AttrContext> env) { 3704 if (env.tree.hasTag(TOPLEVEL)) 3705 attribTopLevel(env); 3706 else 3707 attribClass(env.tree.pos(), env.enclClass.sym); 3708 } 3709 3710 /** 3711 * Attribute a top level tree. These trees are encountered when the 3712 * package declaration has annotations. 3713 */ 3714 public void attribTopLevel(Env<AttrContext> env) { 3715 JCCompilationUnit toplevel = env.toplevel; 3716 try { 3717 annotate.flush(); 3718 chk.validateAnnotations(toplevel.packageAnnotations, toplevel.packge); 3719 } catch (CompletionFailure ex) { 3720 chk.completionError(toplevel.pos(), ex); 3721 } 3722 } 3723 3724 /** Main method: attribute class definition associated with given class symbol. 3725 * reporting completion failures at the given position. 3726 * @param pos The source position at which completion errors are to be 3727 * reported. 3728 * @param c The class symbol whose definition will be attributed. 3729 */ 3730 public void attribClass(DiagnosticPosition pos, ClassSymbol c) { 3731 try { 3732 annotate.flush(); 3733 attribClass(c); 3734 } catch (CompletionFailure ex) { 3735 chk.completionError(pos, ex); 3736 } 3737 } 3738 3739 /** Attribute class definition associated with given class symbol. 3740 * @param c The class symbol whose definition will be attributed. 3741 */ 3742 void attribClass(ClassSymbol c) throws CompletionFailure { 3743 if (c.type.hasTag(ERROR)) return; 3744 3745 // Check for cycles in the inheritance graph, which can arise from 3746 // ill-formed class files. 3747 chk.checkNonCyclic(null, c.type); 3748 3749 Type st = types.supertype(c.type); 3750 if ((c.flags_field & Flags.COMPOUND) == 0) { 3751 // First, attribute superclass. 3752 if (st.hasTag(CLASS)) 3753 attribClass((ClassSymbol)st.tsym); 3754 3755 // Next attribute owner, if it is a class. 3756 if (c.owner.kind == TYP && c.owner.type.hasTag(CLASS)) 3757 attribClass((ClassSymbol)c.owner); 3758 } 3759 3760 // The previous operations might have attributed the current class 3761 // if there was a cycle. So we test first whether the class is still 3762 // UNATTRIBUTED. 3763 if ((c.flags_field & UNATTRIBUTED) != 0) { 3764 c.flags_field &= ~UNATTRIBUTED; 3765 3766 // Get environment current at the point of class definition. 3767 Env<AttrContext> env = enter.typeEnvs.get(c); 3768 3769 // The info.lint field in the envs stored in enter.typeEnvs is deliberately uninitialized, 3770 // because the annotations were not available at the time the env was created. Therefore, 3771 // we look up the environment chain for the first enclosing environment for which the 3772 // lint value is set. Typically, this is the parent env, but might be further if there 3773 // are any envs created as a result of TypeParameter nodes. 3774 Env<AttrContext> lintEnv = env; 3775 while (lintEnv.info.lint == null) 3776 lintEnv = lintEnv.next; 3777 3778 // Having found the enclosing lint value, we can initialize the lint value for this class 3779 env.info.lint = lintEnv.info.lint.augment(c.annotations, c.flags()); 3780 3781 Lint prevLint = chk.setLint(env.info.lint); 3782 JavaFileObject prev = log.useSource(c.sourcefile); 3783 ResultInfo prevReturnRes = env.info.returnResult; 3784 3785 try { 3786 env.info.returnResult = null; 3787 // java.lang.Enum may not be subclassed by a non-enum 3788 if (st.tsym == syms.enumSym && 3789 ((c.flags_field & (Flags.ENUM|Flags.COMPOUND)) == 0)) 3790 log.error(env.tree.pos(), "enum.no.subclassing"); 3791 3792 // Enums may not be extended by source-level classes 3793 if (st.tsym != null && 3794 ((st.tsym.flags_field & Flags.ENUM) != 0) && 3795 ((c.flags_field & (Flags.ENUM | Flags.COMPOUND)) == 0) && 3796 !target.compilerBootstrap(c)) { 3797 log.error(env.tree.pos(), "enum.types.not.extensible"); 3798 } 3799 attribClassBody(env, c); 3800 3801 chk.checkDeprecatedAnnotation(env.tree.pos(), c); 3802 } finally { 3803 env.info.returnResult = prevReturnRes; 3804 log.useSource(prev); 3805 chk.setLint(prevLint); 3806 } 3807 3808 } 3809 } 3810 3811 public void visitImport(JCImport tree) { 3812 // nothing to do 3813 } 3814 3815 /** Finish the attribution of a class. */ 3816 private void attribClassBody(Env<AttrContext> env, ClassSymbol c) { 3817 JCClassDecl tree = (JCClassDecl)env.tree; 3818 Assert.check(c == tree.sym); 3819 3820 // Validate annotations 3821 chk.validateAnnotations(tree.mods.annotations, c); 3822 3823 // Validate type parameters, supertype and interfaces. 3824 attribStats(tree.typarams, env); 3825 if (!c.isAnonymous()) { 3826 //already checked if anonymous 3827 chk.validate(tree.typarams, env); 3828 chk.validate(tree.extending, env); 3829 chk.validate(tree.implementing, env); 3830 } 3831 3832 // If this is a non-abstract class, check that it has no abstract 3833 // methods or unimplemented methods of an implemented interface. 3834 if ((c.flags() & (ABSTRACT | INTERFACE)) == 0) { 3835 if (!relax) 3836 chk.checkAllDefined(tree.pos(), c); 3837 } 3838 3839 if ((c.flags() & ANNOTATION) != 0) { 3840 if (tree.implementing.nonEmpty()) 3841 log.error(tree.implementing.head.pos(), 3842 "cant.extend.intf.annotation"); 3843 if (tree.typarams.nonEmpty()) 3844 log.error(tree.typarams.head.pos(), 3845 "intf.annotation.cant.have.type.params"); 3846 3847 // If this annotation has a @ContainedBy, validate 3848 Attribute.Compound containedBy = c.attribute(syms.containedByType.tsym); 3849 if (containedBy != null) { 3850 // get diagnositc position for error reporting 3851 DiagnosticPosition cbPos = getDiagnosticPosition(tree, containedBy.type); 3852 Assert.checkNonNull(cbPos); 3853 3854 chk.validateContainedBy(c, containedBy, cbPos); 3855 } 3856 3857 // If this annotation has a @ContainerFor, validate 3858 Attribute.Compound containerFor = c.attribute(syms.containerForType.tsym); 3859 if (containerFor != null) { 3860 // get diagnositc position for error reporting 3861 DiagnosticPosition cfPos = getDiagnosticPosition(tree, containerFor.type); 3862 Assert.checkNonNull(cfPos); 3863 3864 chk.validateContainerFor(c, containerFor, cfPos); 3865 } 3866 } else { 3867 // Check that all extended classes and interfaces 3868 // are compatible (i.e. no two define methods with same arguments 3869 // yet different return types). (JLS 8.4.6.3) 3870 chk.checkCompatibleSupertypes(tree.pos(), c.type); 3871 if (allowDefaultMethods) { 3872 chk.checkDefaultMethodClashes(tree.pos(), c.type); 3873 } 3874 } 3875 3876 // Check that class does not import the same parameterized interface 3877 // with two different argument lists. 3878 chk.checkClassBounds(tree.pos(), c.type); 3879 3880 tree.type = c.type; 3881 3882 for (List<JCTypeParameter> l = tree.typarams; 3883 l.nonEmpty(); l = l.tail) { 3884 Assert.checkNonNull(env.info.scope.lookup(l.head.name).scope); 3885 } 3886 3887 // Check that a generic class doesn't extend Throwable 3888 if (!c.type.allparams().isEmpty() && types.isSubtype(c.type, syms.throwableType)) 3889 log.error(tree.extending.pos(), "generic.throwable"); 3890 3891 // Check that all methods which implement some 3892 // method conform to the method they implement. 3893 chk.checkImplementations(tree); 3894 3895 //check that a resource implementing AutoCloseable cannot throw InterruptedException 3896 checkAutoCloseable(tree.pos(), env, c.type); 3897 3898 for (List<JCTree> l = tree.defs; l.nonEmpty(); l = l.tail) { 3899 // Attribute declaration 3900 attribStat(l.head, env); 3901 // Check that declarations in inner classes are not static (JLS 8.1.2) 3902 // Make an exception for static constants. 3903 if (c.owner.kind != PCK && 3904 ((c.flags() & STATIC) == 0 || c.name == names.empty) && 3905 (TreeInfo.flags(l.head) & (STATIC | INTERFACE)) != 0) { 3906 Symbol sym = null; 3907 if (l.head.hasTag(VARDEF)) sym = ((JCVariableDecl) l.head).sym; 3908 if (sym == null || 3909 sym.kind != VAR || 3910 ((VarSymbol) sym).getConstValue() == null) 3911 log.error(l.head.pos(), "icls.cant.have.static.decl", c); 3912 } 3913 } 3914 3915 // Check for cycles among non-initial constructors. 3916 chk.checkCyclicConstructors(tree); 3917 3918 // Check for cycles among annotation elements. 3919 chk.checkNonCyclicElements(tree); 3920 3921 // Check for proper use of serialVersionUID 3922 if (env.info.lint.isEnabled(LintCategory.SERIAL) && 3923 isSerializable(c) && 3924 (c.flags() & Flags.ENUM) == 0 && 3925 (c.flags() & ABSTRACT) == 0) { 3926 checkSerialVersionUID(tree, c); 3927 } 3928 } 3929 // where 3930 /** get a diagnostic position for an attribute of Type t, or null if attribute missing */ 3931 private DiagnosticPosition getDiagnosticPosition(JCClassDecl tree, Type t) { 3932 for(List<JCAnnotation> al = tree.mods.annotations; !al.isEmpty(); al = al.tail) { 3933 if (types.isSameType(al.head.annotationType.type, t)) 3934 return al.head.pos(); 3935 } 3936 3937 return null; 3938 } 3939 3940 /** check if a class is a subtype of Serializable, if that is available. */ 3941 private boolean isSerializable(ClassSymbol c) { 3942 try { 3943 syms.serializableType.complete(); 3944 } 3945 catch (CompletionFailure e) { 3946 return false; 3947 } 3948 return types.isSubtype(c.type, syms.serializableType); 3949 } 3950 3951 /** Check that an appropriate serialVersionUID member is defined. */ 3952 private void checkSerialVersionUID(JCClassDecl tree, ClassSymbol c) { 3953 3954 // check for presence of serialVersionUID 3955 Scope.Entry e = c.members().lookup(names.serialVersionUID); 3956 while (e.scope != null && e.sym.kind != VAR) e = e.next(); 3957 if (e.scope == null) { 3958 log.warning(LintCategory.SERIAL, 3959 tree.pos(), "missing.SVUID", c); 3960 return; 3961 } 3962 3963 // check that it is static final 3964 VarSymbol svuid = (VarSymbol)e.sym; 3965 if ((svuid.flags() & (STATIC | FINAL)) != 3966 (STATIC | FINAL)) 3967 log.warning(LintCategory.SERIAL, 3968 TreeInfo.diagnosticPositionFor(svuid, tree), "improper.SVUID", c); 3969 3970 // check that it is long 3971 else if (!svuid.type.hasTag(LONG)) 3972 log.warning(LintCategory.SERIAL, 3973 TreeInfo.diagnosticPositionFor(svuid, tree), "long.SVUID", c); 3974 3975 // check constant 3976 else if (svuid.getConstValue() == null) 3977 log.warning(LintCategory.SERIAL, 3978 TreeInfo.diagnosticPositionFor(svuid, tree), "constant.SVUID", c); 3979 } 3980 3981 private Type capture(Type type) { 3982 return types.capture(type); 3983 } 3984 3985 // <editor-fold desc="post-attribution visitor"> 3986 3987 /** 3988 * Handle missing types/symbols in an AST. This routine is useful when 3989 * the compiler has encountered some errors (which might have ended up 3990 * terminating attribution abruptly); if the compiler is used in fail-over 3991 * mode (e.g. by an IDE) and the AST contains semantic errors, this routine 3992 * prevents NPE to be progagated during subsequent compilation steps. 3993 */ 3994 public void postAttr(JCTree tree) { 3995 new PostAttrAnalyzer().scan(tree); 3996 } 3997 3998 class PostAttrAnalyzer extends TreeScanner { 3999 4000 private void initTypeIfNeeded(JCTree that) { 4001 if (that.type == null) { 4002 that.type = syms.unknownType; 4003 } 4004 } 4005 4006 @Override 4007 public void scan(JCTree tree) { 4008 if (tree == null) return; 4009 if (tree instanceof JCExpression) { 4010 initTypeIfNeeded(tree); 4011 } 4012 super.scan(tree); 4013 } 4014 4015 @Override 4016 public void visitIdent(JCIdent that) { 4017 if (that.sym == null) { 4018 that.sym = syms.unknownSymbol; 4019 } 4020 } 4021 4022 @Override 4023 public void visitSelect(JCFieldAccess that) { 4024 if (that.sym == null) { 4025 that.sym = syms.unknownSymbol; 4026 } 4027 super.visitSelect(that); 4028 } 4029 4030 @Override 4031 public void visitClassDef(JCClassDecl that) { 4032 initTypeIfNeeded(that); 4033 if (that.sym == null) { 4034 that.sym = new ClassSymbol(0, that.name, that.type, syms.noSymbol); 4035 } 4036 super.visitClassDef(that); 4037 } 4038 4039 @Override 4040 public void visitMethodDef(JCMethodDecl that) { 4041 initTypeIfNeeded(that); 4042 if (that.sym == null) { 4043 that.sym = new MethodSymbol(0, that.name, that.type, syms.noSymbol); 4044 } 4045 super.visitMethodDef(that); 4046 } 4047 4048 @Override 4049 public void visitVarDef(JCVariableDecl that) { 4050 initTypeIfNeeded(that); 4051 if (that.sym == null) { 4052 that.sym = new VarSymbol(0, that.name, that.type, syms.noSymbol); 4053 that.sym.adr = 0; 4054 } 4055 super.visitVarDef(that); 4056 } 4057 4058 @Override 4059 public void visitNewClass(JCNewClass that) { 4060 if (that.constructor == null) { 4061 that.constructor = new MethodSymbol(0, names.init, syms.unknownType, syms.noSymbol); 4062 } 4063 if (that.constructorType == null) { 4064 that.constructorType = syms.unknownType; 4065 } 4066 super.visitNewClass(that); 4067 } 4068 4069 @Override 4070 public void visitAssignop(JCAssignOp that) { 4071 if (that.operator == null) 4072 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol); 4073 super.visitAssignop(that); 4074 } 4075 4076 @Override 4077 public void visitBinary(JCBinary that) { 4078 if (that.operator == null) 4079 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol); 4080 super.visitBinary(that); 4081 } 4082 4083 @Override 4084 public void visitUnary(JCUnary that) { 4085 if (that.operator == null) 4086 that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol); 4087 super.visitUnary(that); 4088 } 4089 4090 @Override 4091 public void visitReference(JCMemberReference that) { 4092 super.visitReference(that); 4093 if (that.sym == null) { 4094 that.sym = new MethodSymbol(0, names.empty, syms.unknownType, syms.noSymbol); 4095 } 4096 } 4097 } 4098 // </editor-fold> 4099 }